contextlib.redirect_stdout in Python2.7

狂风中的少年 提交于 2020-01-23 06:06:13

问题


I use Python2.7 and I want the function: contextlib.redirect_stdout. I mean, I want to redirect the output of specific function (not the all program). The problem is - only Python3 supports "context.redirect_stdout" and no Python2.7.

Someone know how can I use the same function in Python2.7 or to implement the same idea?

Thanks in advance


回答1:


Something like this should do the job if you're not worried about re-using the same context manager object.

import sys
import contextlib

@contextlib.contextmanager
def redirect_stdout(target):
    original = sys.stdout
    sys.stdout = target
    yield
    sys.stdout = original


来源:https://stackoverflow.com/questions/44226221/contextlib-redirect-stdout-in-python2-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!