Python +禁用打印输出,无法取回它

时间:2017-02-26 03:34:42

标签: python

我找到了这段代码elsewhere on stackoverflow。我一直在使用它,但现在我似乎无法使任何打印功能工作,无论我执行enablePrint()多少次......任何想法?

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

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

和Print('test')导致无输出。我在Juptyer做这一切。

2 个答案:

答案 0 :(得分:1)

您需要存储旧的标准输入,以便您可以恢复它:

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__可以是无(见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>'

答案 1 :(得分:0)

在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")