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當參數傳入,則執行結果如預期。 adpt.write(’asdfwe’) // 預期字符串寫入文本,單事實上字符串輸出到了屏幕。 print ’this is import from print’ //如預期的輸入到了文本except Exception, e: sys.stdout = tmp print efinally: sys.stdout = tmp f.close()print ’finish’
問題:就如我注釋里寫的,調用TestWriter.write()的時候沒有實現sys.stdout的重定向輸出,但之后的print證明了標準輸出已經重定向到了文件f對象。斷點跟蹤的時候,self.stream也顯示為f對象求解惑!!!
問題解答
回答1:def __init__(self, stream=sys.stdout)
Python在創建每個函數時,每個參數都會被綁定,默認值不會隨著值的改變而重新加載
# 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
但如果綁定參數默認參數綁定的是地址,那就不一樣,地址不變,內容可以變.
# 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的構造器參數stdout沒有被重定向。
以上都是我猜的
=====================================================================
import sysclass A: def __init__(self, stream=sys.stdout):print(stream)f = open(’test.txt’, ’w’)a = A()sys.stdout = fprint(sys.stdout)
運行結果
相關文章:
1. 解決Android webview設置cookie和cookie丟失的問題2. javascript - nodejs使用mongoose連接數據庫,使用post提交表單在后臺,后臺處理后調用res.redirect()跳轉界面無效?3. javascript - vue2.0中,$refs對象為什么用駝峰的方式獲取不到屬性?4. javascript - 能否讓vue-cli的express修改express重啟服務5. node.js - npm install全局安裝出錯,請問如何解決?謝謝!6. java - 注解上的屬性可以傳遞嗎?7. android - 分享到微信,如何快速轉換成字節數組8. node.js - mac安裝mongodb第一次啟動失敗9. node.js - npm一直提示proxy有問題10. python bottle跑起來以后,定時執行的任務為什么每次都重復(多)執行一次?
