简体   繁体   中英

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

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

smart way: metapython -- http://metapython.org/

much-derided and not-generally-respected way: eval() -- http://docs.python.org/library/functions.html

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...

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

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.

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