I need to be able to ask a user for a turtle command such as forward(90) and execute it as a turtle command, eg 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
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.