Python + 禁用打印输出,如何恢复?

3
我在stackoverflow上找到了这段代码(链接)。我一直在使用它,但现在无论我执行多少次enablePrint()函数,都似乎无法使任何print函数正常工作...有什么建议吗?
# Disable
def blockPrint():
    sys.stdout = open(os.devnull, 'w')

# Restore
def enablePrint():
    sys.stdout = sys.__stdout__

使用Print('test')不会输出任何内容。我正在使用Juptyer进行所有操作。

2个回答

2
在Python 3中,为了使用WITH语句(上下文管理器),您只需要实现两种方法:
import os, sys

class HiddenPrints:
    def __enter__(self):
        self._original_stdout = sys.stdout
        sys.stdout = open(os.devnull, 'w')

    def __exit__(self, exc_type, exc_val, exc_tb):
        sys.stdout = self._original_stdout

然后您可以像这样使用它:
with HiddenPrints():
    print("This will not be printed")

print("This will be printed as before")

1

您需要存储旧的 stdin,以便可以恢复它:

import sys
import os

# Disable
def blockPrint():
    sys.__stdout__ = sys.stdout
    sys.stdout = open(os.devnull, 'w')

# Restore
def enablePrint():
    sys.stdout = sys.__stdout__

blockPrint()
print("test")
enablePrint()
print("test")

将会打印一次test。此外,我建议使用上下文管理器:

from contextlib import contextmanager

@contextmanager
def blockPrint():
    import sys
    old_stdout = sys.stdout
    sys.stdout = None
    try:
        yield
    finally:
        sys.stdout = old_stdout

with blockPrint():
    print("test")

print("test")

这将再次打印test一次。

编辑:对于那些想知道为什么需要这样做的人:在某些情况下,sys.__stdout__可能为None(请参见https://docs.python.org/3/library/sys.html) - 例如,在Windows上的IDLE中的Python 3.5 shell中就是这种情况。

Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import sys
>>> repr(sys.__stdout__)
'None'
>>> repr(sys.stdout)
'<idlelib.PyShell.PseudoOutputFile object at 0x03ACF8B0>'

谢谢您。我还不太清楚为什么要使用上下文管理器?(顺便说一下,我正在使用2.7版本) - keynesiancross
如果你只想临时使用一个 资源 ,那么上下文管理器可以确保该资源在使用后被释放。我觉得 with 语句使意图更加清晰(也清楚哪部分代码应受到影响)。但显然没有必要使用它。 - Jonathan von Schroeder

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接