Python2.7 中的 contextlib.redirect_stdout

2024-04-20

我使用Python2.7,我想要这个功能:contextlib.redirect_stdout https://docs.python.org/3/library/contextlib.html#contextlib.redirect_stdout。 我的意思是,我想重定向特定函数(而不是所有程序)的输出。 问题是 - 只有Python3支持“context.redirect_stdout”,而不支持Python2.7。

有人知道如何在Python2.7中使用相同的函数或实现相同的想法吗?

提前致谢


如果您不担心重复使用相同的上下文管理器对象,这样的事情应该可以完成工作。

import sys
import contextlib

@contextlib.contextmanager
def redirect_stdout(target):
    original = sys.stdout
    try:
        sys.stdout = target
        yield
    finally:
        sys.stdout = original
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python2.7 中的 contextlib.redirect_stdout 的相关文章

随机推荐