如何在Python中执行包含Python代码的字符串?

发布于 2021-02-02 23:18:52

如何在Python中执行包含Python代码的字符串?

关注者
0
被浏览
107
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    对于语句,请使用exec(string)(Python 2/3)exec string(Python 2)

    >>> mycode = 'print "hello world"'
    >>> exec(mycode)
    Hello world
    

    当需要表达式的值时,请使用eval(string)

    >>> x = eval("2+2")
    >>> x
    4
    

    但是,第一步应该是问自己是否真的需要。通常,执行代码应该是最后的选择:如果代码中可能包含用户输入的代码,那么它将很慢,很丑陋而且很危险。你应该始终首先考虑替代项,例如高阶函数,以查看它们是否可以更好地满足你的需求。



  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    在示例中,使用exec函数将字符串作为代码执行。

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


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看