简体   繁体   English

Python:如何动态生成代码?

[英]Python: How to generate the code on the fly?

I've got a problem, I have to generate program on the fly and then execute it. 我遇到了问题,我必须即时生成程序,然后执行它。 How could we do this? 我们该怎么做?

You can use the eval() function to execute code from a string 您可以使用eval()函数从字符串执行代码

An example would be: 一个例子是:

import math

test=r"dir(math)"

eval(test)

Output 输出量

['__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']

However using eval is very unsafe, I suggest you go through using eval() safely 但是,使用eval是非常不安全的,我建议您安全地使用eval()

smart way: metapython -- http://metapython.org/ 聪明的方法:metapython- http ://metapython.org/

much-derided and not-generally-respected way: eval() -- http://docs.python.org/library/functions.html 根深蒂固且不受普遍尊重的方式: eval() -http : eval()

why do you want to do this, may I ask? 请问为什么要这么做?

如果您的意思是解释器,则只需从命令行键入“ python”。

If you just need to evaluate expression or some python code use eval or literal_eval depends on your requirements... 如果您只需要评估表达式或某些python代码,请使用evalliteral_eval取决于您的要求...

If you need to generate .py files, you may need code generator, here is the basic code generator: http://effbot.org/zone/python-code-generator.htm and then you can execute your code using execfile 如果需要生成.py文件,则可能需要代码生成器,以下是基本的代码生成器: http : //effbot.org/zone/python-code-generator.htm ,然后可以使用execfile执行代码

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM