Question

I need to be able to ask a user for a turtle command such as forward(90) and execute it as a turtle command, e.g turtle.forward(90) and repeat until the user exits. so far I have:

def turtle_input(prompt):
"""Loop to ask for user input and execute as a turtle command"""
import turtle
while True:
    t = input('Enter a turtle command: ')
    if t in ['Quit' , 'quit', 'q', 'Q']:
        break
    turtle.(t)     
return prompt
Était-ce utile?

La solution

executing arbitrary code is usually not a good idea as it is a huge security vulnerability, but here's one way:

eval('turtle.{0}'.format(t))

This isn't a good idea as consider the following string a user could pass in:

t = 'forward(90) or __import__("os").system("rm -rf ~")'

All of a sudden, your home directory starts to get deleted -- Oops.


A slightly less robust, but more secure solution might be to use ast.literal_eval and parse the string yourself:

import ast

#...
funcname,args = t.split('(',1)
args = ast_literal_eval('('+args)
if hasattr(args,'__iter__'):
    getattr(turtle,funcname)(*args)
else:
    getattr(turtle,funcname)(args)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top