1. 程式人生 > >python之sys.stdout、sys.stdin,stdout.write等

python之sys.stdout、sys.stdin,stdout.write等

sys.stdin,sys.stdout,sys.stderr: stdin , stdout , 以及stderr 變數包含與標準I/O 流對應的流物件. 如果需要更好地控制輸出,而print 不能滿足你的要求, 它們就是你所需要的. 你也可以替換它們, 這時候你就可以重定向(script.py < file.txt>)輸出和輸入到其它裝置( device ), 或者以非標準的方式處理它們

1.1 sys.stdout 與 print
當我們在 Python 中列印物件呼叫 print obj 時候,事實上是呼叫了 sys.stdout.write(obj+'\n')
print 將你需要的內容列印到了控制檯,然後追加了一個換行符
print 會呼叫 sys.stdout 的 write 方法
以下兩行在事實上等價:
sys.stdout.write('hello'+'\n') 
print 'hello'


1.2sys.stdin 與 raw_input
當我們用 raw_input('Input promption: ') 時,事實上是先把提示資訊輸出,然後捕獲輸入
以下兩組在事實上等價:
hi=raw_input('hello? ') 
print 'hello? ', #comma to stay in the same line 
hi=sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream


1.3從控制檯重定向到檔案
原始的 sys.stdout 指向控制檯
如果把檔案的物件的引用賦給 sys.stdout,那麼 print 呼叫的就是檔案物件的 write 方法
f_handler=open('out.log', 'w') 
sys.stdout=f_handler 
print 'hello'
# this hello can't be viewed on concole 
# this hello is in file out.log
記住,如果你還想在控制檯列印一些東西的話,最好先將原始的控制檯物件引用儲存下來,向檔案中列印之後再恢復 sys.stdout


__console__=sys.stdout 
# redirection start # 
... 
# redirection end 
sys.stdout=__console__




1.4同時重定向到控制檯和檔案
如果我們希望列印的內容一方面輸出到控制檯,另一方面輸出到檔案作為日誌儲存,那麼該怎麼辦?
將列印的內容保留在記憶體中,而不是一列印就將 buffer 釋放重新整理,那麼放到一個字串區域中會怎樣?
a='' 
sys.stdout=a 
print 'hello'
OK,上述程式碼是無法正常執行的
Traceback (most recent call last): File 
".\hello.py", line xx, in print 'hello' 
AttributeError: 'str' 
object has no attribute 'write'
錯誤很明顯,就是上面強調過的,在嘗試呼叫 sys.stdout.write() 的時候,發現沒有 write 方法
另外,這裡之所以提示 attribute error 而不是找不到函式等等,我猜想是因為python 將物件/類的函式指標記錄作為物件/類的一個屬性來對待,只是保留了函式的入口地址