0 votes
1 view
in Python by (7.9k points)

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

1 Answer

0 votes
by (15.6k points)

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

...