2017-02-26 86 views

回答

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一次。此外,我建議你使用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>' 
+0

謝謝你。至於爲什麼使用上下文管理器,我還有點不清楚。 (我使用的是2.7的值) – keynesiancross

+0

如果你只想臨時使​​用'resource',上下文管理器可以確保該資源在*之後被釋放*。我覺得'with'語句使得意圖更加清晰(以及代碼的哪一部分應該受到影響)。但顯然沒有必要使用它。 –

0

在Python 3,以便與語句(上下文管理器)一起工作,必須實施了兩個方法:

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