tags:

views:

127

answers:

4

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
+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
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
You could atleast leave feedback when you downvote
anijhaw
There, have an upvote ;)
Till Backhaus
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