简体   繁体   English

Python2.7 中的 contextlib.redirect_stdout

[英]contextlib.redirect_stdout in Python2.7

I use Python2.7 and I want the function: contextlib.redirect_stdout .我使用 Python2.7 并且我想要函数: 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.问题是 - 只有 Python3 支持“context.redirect_stdout”而没有 Python2.7。

Someone know how can I use the same function in Python2.7 or to implement the same idea?有人知道如何在 Python2.7 中使用相同的函数或实现相同的想法吗?

Thanks in advance提前致谢

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
    try:
        sys.stdout = target
        yield
    finally:
        sys.stdout = original

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM