python:在exec语句中获取打印输出
我想获取一个exec(...)
的输出。以下是我的代码:
code = """
i = [0,1,2]
for j in i :
print j
"""
result = exec(code)
我该如何获取那些打印出来的内容呢?我想得到类似这样的结果:
0
1
2
谢谢你的帮助。
7 个回答
13
这是一个适合Python 3的版本,参考了@Jochen的回答。我还添加了try-except
语句,这样如果代码出错的话,可以进行错误处理。
import sys
from io import StringIO
import contextlib
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
code = """
i = [0,1,2]
for j in i :
print(j)
"""
with stdoutIO() as s:
try:
exec(code)
except:
print("Something wrong with the code")
print("out:", s.getvalue())
16
你可以在执行某个操作时,把标准输出重定向到一个字符串中,这样你就能捕捉到输出的内容。
Python2
import sys
from cStringIO import StringIO
code = """
i = [0,1,2]
for j in i:
print(j)
"""
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
exec(code)
sys.stdout = old_stdout
print(redirected_output.getvalue())
Python3
import sys
from io import StringIO
code = """
i = [0,1,2]
for j in i:
print(j)
"""
old_stdout = sys.stdout
redirected_output = sys.stdout = StringIO()
exec(code)
sys.stdout = old_stdout
print(redirected_output.getvalue())
68
从Python 3.4开始,标准库里有一个解决方案:https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout
from io import StringIO
from contextlib import redirect_stdout
f = StringIO()
with redirect_stdout(f):
help(pow)
s = f.getvalue()
在旧版本中,你可以写一个上下文管理器来处理替换标准输出(stdout):
import sys
from io import StringIO
import contextlib
@contextlib.contextmanager
def stdoutIO(stdout=None):
old = sys.stdout
if stdout is None:
stdout = StringIO()
sys.stdout = stdout
yield stdout
sys.stdout = old
code = """
i = [0,1,2]
for j in i :
print j
"""
with stdoutIO() as s:
exec(code)
print("out:", s.getvalue())