我遇到了一个问题,我必须即时生成程序然后执行它。 我们怎么能这样做?
请您参考如下方法:
您可以使用 eval() 函数从字符串中执行代码
一个例子是:
import math
test=r"dir(math)"
eval(test)
输出
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']
但是使用eval是很不安全的,建议你通过using eval() safely
