python:在exec语句中获取打印输出 [英] python: get the print output in an exec statement

查看:350
本文介绍了python:在exec语句中获取打印输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获取exec(...)的输出,这是我的代码:

I want to get the output of an exec(...) Here is my code:

code = """
i = [0,1,2]
for j in i :
    print j
"""
result = exec(code)

我如何获得打印输出的内容? 我怎么能得到像这样的东西:

How could I get the things that print outputed? How can I get something like:

0
1
2

致谢和感谢.

推荐答案

我和Frédéric有相同的想法,但是我写了一个上下文管理器来处理替换stdout的问题:

I had the same idea as Frédéric, but i wrote a context manager to handle replacing 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())

这篇关于python:在exec语句中获取打印输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆