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

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")>>> x4

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.


In the example a string is executed as code using the exec function.

import sysimport StringIO# create file-like string to capture outputcodeOut = StringIO.StringIO()codeErr = StringIO.StringIO()code = """def f(x):    x = x + 1    return xprint 'This is my output.'"""# capture output and errorssys.stdout = codeOutsys.stderr = codeErrexec code# restore stdout and stderrsys.stdout = sys.__stdout__sys.stderr = sys.__stderr__print f(4)s = codeErr.getvalue()print "error:\n%s\n" % ss = codeOut.getvalue()print "output:\n%s" % scodeOut.close()codeErr.close()


eval and exec are the correct solution, and they can be used in a safer manner.

As discussed in Python's reference manual and clearly explained in this tutorial, the eval and exec functions take two extra parameters that allow a user to specify what global and local functions and variables are available.

For example:

public_variable = 10private_variable = 2def public_function():    return "public information"def private_function():    return "super sensitive information"# make a list of safe functionssafe_list = ['public_variable', 'public_function']safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])# add any needed builtins back insafe_dict['len'] = len>>> eval("public_variable+2", {"__builtins__" : None }, safe_dict)12>>> eval("private_variable+2", {"__builtins__" : None }, safe_dict)Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<string>", line 1, in <module>NameError: name 'private_variable' is not defined>>> exec("print \"'%s' has %i characters\" % (public_function(), len(public_function()))", {"__builtins__" : None}, safe_dict)'public information' has 18 characters>>> exec("print \"'%s' has %i characters\" % (private_function(), len(private_function()))", {"__builtins__" : None}, safe_dict)Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "<string>", line 1, in <module>NameError: name 'private_function' is not defined

In essence you are defining the namespace in which the code will be executed.


matomo