我使用 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/