Back
How do I execute a string containing Python code in Python?
For statements, use exec(string) (Python 2/3) or exec string (Python 2):
>>> mycode = 'print "hello world"'>>> exec(mycode)Hello world
>>> mycode = 'print "hello world"'
>>> exec(mycode)
Hello world
When you need the value of an expression, use eval(string):
>>> x = eval("2+2")>>> x4
>>> x = eval("2+2")
>>> x
4
31k questions
32.8k answers
501 comments
693 users