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 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 … Read more