pythonstringexec

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


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


Editor's note: Never use eval (or exec) on data that could possibly come from outside the program in any form. It is a critical security risk. You allow the author of the data to run arbitrary code on your computer. If you are here because you want to create multiple variables in your Python program following a pattern, you almost certainly have an XY problem. Do not create those variables at all - instead, use a list or dict appropriately.


Solution

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

    import sys
    import StringIO
    
    # create file-like string to capture output
    codeOut = StringIO.StringIO()
    codeErr = StringIO.StringIO()
    
    code = """
    def f(x):
        x = x + 1
        return x
    
    print 'This is my output.'
    """
    
    # capture output and errors
    sys.stdout = codeOut
    sys.stderr = codeErr
    
    exec code
    
    # restore stdout and stderr
    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
    
    print f(4)
    
    s = codeErr.getvalue()
    
    print "error:\n%s\n" % s
    
    s = codeOut.getvalue()
    
    print "output:\n%s" % s
    
    codeOut.close()
    codeErr.close()