你需要存储的旧标准输入,这样就可以将其还原:
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
一次。此外,我建议你使用contextmanager的:
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
一次。
编辑:对于那些想知道为什么这可以benecessary:在某些情况下sys.__stdout__
可以无(见https://docs.python.org/3/library/sys.html) - 对我来说这是例如在IDLE中在Windows上一个Python 3.5壳的情况。
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
如果你只想临时使用'resource',上下文管理器可以确保该资源在*之后被释放*。我觉得'with'语句使得意图更加清晰(以及代码的哪一部分应该受到影响)。但显然没有必要使用它。 –