gpt4 book ai didi

python - Python2.7 中的 contextlib.redirect_stdout

转载 作者:行者123 更新时间:2023-12-04 12:17:10 28 4
gpt4 key购买 nike

我使用 Python2.7 并且我想要函数: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

关于python - Python2.7 中的 contextlib.redirect_stdout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44226221/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com