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

后端 未结 14 2417
一向
一向 2020-11-22 02:42

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

14条回答
  •  被撕碎了的回忆
    2020-11-22 02:56

    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()
    

提交回复
热议问题