I've got a problem, I have to generate program on the fly and then execute it. How could we do this?
A:
If you mean the interpreter, just type 'python' from the command line.
waffle paradox
2010-10-20 03:36:30
+1
A:
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
2010-10-20 03:36:32
A:
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
2010-10-20 03:44:32
You could atleast leave feedback when you downvote
anijhaw
2010-10-20 12:55:41
There, have an upvote ;)
Till Backhaus
2010-10-20 22:23:04
A:
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
Tumbleweed
2010-10-20 05:40:21