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當參數(shù)傳入,則執(zhí)行結(jié)果如預期。 adpt.write(’asdfwe’) // 預期字符串寫入文本,單事實上字符串輸出到了屏幕。 print ’this is import from print’ //如預期的輸入到了文本except Exception, e: sys.stdout = tmp print efinally: sys.stdout = tmp f.close()print ’finish’
問題:就如我注釋里寫的,調(diào)用TestWriter.write()的時候沒有實現(xiàn)sys.stdout的重定向輸出,但之后的print證明了標準輸出已經(jīng)重定向到了文件f對象。斷點跟蹤的時候,self.stream也顯示為f對象求解惑!!!


問題解答
回答1:def __init__(self, stream=sys.stdout)
Python在創(chuàng)建每個函數(shù)時,每個參數(shù)都會被綁定,默認值不會隨著值的改變而重新加載
# 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ù)默認參數(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)
運行結(jié)果
相關(guān)文章:
1. javascript - immutable配合react提升性能?2. javascript - sublime快鍵鍵問題3. 如何解決Centos下Docker服務啟動無響應,且輸入docker命令無響應?4. javascript - 移動端上不能實現(xiàn)拖拽布局嗎?5. vue.js - Vue 如何像Angular.js watch 一樣監(jiān)聽數(shù)據(jù)變化6. 實現(xiàn)bing搜索工具urlAPI提交7. index.php錯誤,求指點8. thinkPHP5中獲取數(shù)據(jù)庫數(shù)據(jù)后默認選中下拉框的值,傳遞到后臺消失不見。有圖有代碼,希望有人幫忙9. angular.js - 單頁應用(ng/vue)該如何監(jiān)聽用戶離開當前頁面(或者路由)?10. javascript - ios返回不執(zhí)行js怎么解決?

網(wǎng)公網(wǎng)安備