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

PythonServer Side ProgrammingProgramming

If you want to execute Python statements, you can use exec(string). For example,

>>> my_code = 'print "Hello World!"'
>>> exec(my_code)
Hello World!

But if you just want to evaluate the value of an expression, you can use eval(). For example,

>>> my_expression = "5 + 3"
>>> eval(my_expression)

 Note: Be very cautious while using both eval and exec as they are very powerful functions

and can cause very subtle bugs/ security loopholes in your code.

Updated on 30-Sep-2019 06:58:45