python - Python2.7 中的 contextlib.redirect_stdout

标签 python redirectstandardoutput

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

相关文章:

python - 如何编写可以临时运行但也可以由主脚本调用的导入函数?

c# - 将标准输出保存在内存中,而不是 C# 中的文件

c# - 如何在 Windows 窗体应用程序中将标准输出重定向到 c# 中的 psexec 进程的文件

.net - 如何在不重定向的情况下读取 Process.StandardOutput ? (F#)

Python 子进程 : how to retrieve the standard output

c# - 为什么我不能在 C# 中使用 Process 获取 C++ 程序的输出?

python - 在 Python 中以编程方式检查模块可用性?

java - 如何使用java/python使用云栈API?

python - 散点图颜色条 - Matplotlib

Python 类型提示 Callable with one known positional type 然后是 *args 和 **kwargs