我想获取一个输出,exec(...)这是我的代码:
exec(...)
code = """ i = [0,1,2] for j in i : print j """ result = exec(code)
如何获得打印输出的内容?我如何得到类似的东西:
0 1 2
问候和感谢。
我和Frédéric有着相同的想法,但是我写了一个上下文管理器来处理替换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())