您的位置:首頁技術文章
文章詳情頁

python2.7 - Python 2.7 stdout重定向的疑問

瀏覽:92日期:2022-07-22 11:37:00

問題描述

先上代碼

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對象求解惑?。?!python2.7 - Python 2.7 stdout重定向的疑問

python2.7 - Python 2.7 stdout重定向的疑問

python2.7 - Python 2.7 stdout重定向的疑問

問題解答

回答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)

運行結果python2.7 - Python 2.7 stdout重定向的疑問

標簽: Python 編程
相關文章:
国产综合久久一区二区三区