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

新手上路,请多包涵

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

原文由 hekevintran 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 210
2 个回答

在示例中,使用 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()

原文由 hekevintran 发布,翻译遵循 CC BY-SA 2.5 许可协议

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

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

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

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

但是,第一步应该是问问自己是否真的需要。执行代码通常应该是最后的手段:如果它可以包含用户输入的代码,那将是缓慢、丑陋和危险的。您应该始终首先查看替代方案,例如高阶函数,看看它们是否能更好地满足您的需求。

原文由 Brian 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题