2

I've got a problem, I have to generate program on the fly and then execute it. How could we do this?

user469652
  • 48,855
  • 59
  • 128
  • 165

4 Answers4

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
2

If you mean the interpreter, just type 'python' from the command line.

waffle paradox
  • 2,755
  • 18
  • 19