尽管像这样的语法正确的 Python 语句列表似乎是一个使用的机会eval()
,但请抵制这种诱惑。这里的语法很简单,函数只有一个参数,我们可以使用re
模块来解析命令,并且只针对有效参数执行看似有效的函数:
import turtle
import re
redist = [ \
'seth(0)', 'forward(drawdist)', 'seth(0)', 'forward(drawdist)', \
'seth(90)', 'forward(drawdist)', 'seth(90)', 'forward(drawdist)', \
'seth(180)', 'forward(drawdist)', 'seth(180)', 'forward(drawdist)', \
'seth(270)', 'forward(drawdist)', 'seth(270)', 'forward(drawdist)' \
]
valid_functions = { \
'seth': turtle.setheading, \
'forward': turtle.forward, \
}
valid_arguments = { \
'drawdist': 50, \
}
turtle.begin_fill()
for command in redist:
match = re.match(r"^(\w+)\((\w+)\)$", command)
if match is None:
raise SyntaxError("Invalid syntax")
function, argument = match.group(1), match.group(2)
if function not in valid_functions:
raise ValueError("Invalid function")
if argument in valid_arguments:
argument = valid_arguments[argument]
elif argument.isdigit():
argument = int(argument)
else:
raise TypeError("Invalid argument")
valid_functions[function](argument)
turtle.end_fill()
turtle.hideturtle()
turtle.mainloop()
对于那些想提前阅读的人,它会画一个实心正方形。我在上面提出的异常可能不是正确的,但重点是在尝试执行作为字符串传递给您的代码时,您需要对所有内容进行错误检查并引发异常。