python2.7 - Python 2.7 stdout重定向的疑問
問題描述
先上代碼
import sysclass TestWriter(object): def __init__(self, stream=sys.stdout):super(TestWriter, self).__init__()self.stream = stream def write(self, line):self.stream.write(line)tmp = sys.stdoutf = open(’d:stdout.txt’, ’w’)try: sys.stdout = f adpt = TestWriter() //如果這里我把f當(dāng)參數(shù)傳入,則執(zhí)行結(jié)果如預(yù)期。 adpt.write(’asdfwe’) // 預(yù)期字符串寫入文本,單事實(shí)上字符串輸出到了屏幕。 print ’this is import from print’ //如預(yù)期的輸入到了文本except Exception, e: sys.stdout = tmp print efinally: sys.stdout = tmp f.close()print ’finish’
問題:就如我注釋里寫的,調(diào)用TestWriter.write()的時候沒有實(shí)現(xiàn)sys.stdout的重定向輸出,但之后的print證明了標(biāo)準(zhǔn)輸出已經(jīng)重定向到了文件f對象。斷點(diǎn)跟蹤的時候,self.stream也顯示為f對象求解惑!!!
問題解答
回答1:def __init__(self, stream=sys.stdout)
Python在創(chuàng)建每個函數(shù)時,每個參數(shù)都會被綁定,默認(rèn)值不會隨著值的改變而重新加載
# coding: utf-8D = 2 class Test: def __init__(self, a=D):print aif __name__ == ’__main__’: D = 3 t = Test() print Dinner function: 2outer function: 3
但如果綁定參數(shù)默認(rèn)參數(shù)綁定的是地址,那就不一樣,地址不變,內(nèi)容可以變.
# coding: utf-8D = [3] class Test: def __init__(self, a=D):print 'inner function: ', aif __name__ == ’__main__’: D[0] = 2 t = Test() print 'outer function:', D inner function: [2]outer function: [2]回答2:
In contrast, in Python, execution begins at the top of one file and proceeds in a well-defined order through each statement in the file, ...
http://stackoverflow.com/ques...
python會順序解釋每條語句,所以TestWriter的構(gòu)造器參數(shù)stdout沒有被重定向。
以上都是我猜的
=====================================================================
import sysclass A: def __init__(self, stream=sys.stdout):print(stream)f = open(’test.txt’, ’w’)a = A()sys.stdout = fprint(sys.stdout)
運(yùn)行結(jié)果
相關(guān)文章:
1. mysql優(yōu)化 - 關(guān)于mysql分區(qū)2. javascript - ionic2 input autofocus 電腦成功,iOS手機(jī)鍵盤不彈出3. node.js - 在vuejs-templates/webpack中dev-server.js里為什么要exports readyPromise?4. java - Atom中文問題5. java - MySQL中,使用聚合函數(shù)+for update會鎖表嗎?6. 請教各位大佬,瀏覽器點(diǎn) 提交實(shí)例為什么沒有反應(yīng)7. objective-c - iOS開發(fā)支付寶和微信支付完成為什么跳轉(zhuǎn)到了之前開發(fā)的一個app?8. html5 - 如何實(shí)現(xiàn)帶陰影的不規(guī)則容器?9. vue.js - vue 打包后 nginx 服務(wù)端API請求跨域問題無法解決。10. javascript - 為什么這個點(diǎn)擊事件需要點(diǎn)擊兩次才有效果
