I've got a problem, I have to generate program on the fly and then execute it. How could we do this?
Asked
Active
Viewed 4,280 times
2
-
7Can you be a little more specific? – anijhaw Oct 20 '10 at 03:35
-
Specifically, what do you want your code to do? Higher order functions might be in order. Each one could serve as a sort of template for the functionality that you need. – aaronasterling Oct 20 '10 at 03:55
4 Answers
8
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

anijhaw
- 8,954
- 7
- 35
- 36
4
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

shahjapan
- 13,637
- 22
- 74
- 104
3
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?

fish2000
- 4,289
- 2
- 37
- 76