重定向print測試函式執行過程
阿新 • • 發佈:2018-12-20
import sys
class HasWrite:
def __init__(self):
self.console = sys.stdout
self.store = []
def write(self, string):
self.store.append(string)
def output(self, string):
sys.stdout = self
print(string)
sys.stdout = self.console
hh = HasWrite( )
hh.output('something')
print(hh.store)
通過重定向sys.stdout,測試print函式的執行過程。執行結果,打印出來的hh.store是[‘something’, ‘\n’],而不是[‘something\n’]。 將output函式中的print改為print(string, end=’’)
def output(self, string):
sys.stdout = self
print(string, end='')
sys.stdout = self.console
則輸出結果為[‘something’, ‘’] 說明使用print函式時,會輸出兩次流,一次是string的內容,一次是end的內容;而不是string連線end後一次輸出。