How do I execute a string containing Python code in Python?

hekevintran picture hekevintran · Mar 31, 2009 · Viewed 352.3k times · Source

How do I execute a string containing Python code in Python?

Answer

Brian picture Brian · Mar 31, 2009

For statements, use exec(string) (Python 2/3) or exec string (Python 2):

>>> mycode = 'print "hello world"'
>>> exec(mycode)
Hello world

When you need the value of an expression, use eval(string):

>>> x = eval("2+2")
>>> x
4

However, the first step should be to ask yourself if you really need to. Executing code should generally be the position of last resort: It's slow, ugly and dangerous if it can contain user-entered code. You should always look at alternatives first, such as higher order functions, to see if these can better meet your needs.