你需要存儲的舊標準輸入,這樣就可以將其還原:
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'語句使得意圖更加清晰(以及代碼的哪一部分應該受到影響)。但顯然沒有必要使用它。 –