1. 程式人生 > >sys.stdout的應用,Python標準輸出sys.stdout的重定向

sys.stdout的應用,Python標準輸出sys.stdout的重定向

#本文純菜鳥,所有部落格為個人學習記錄所用。不對的地方希望大家多多指教。

sys.stdout  :  standard output file object; used by print()

sys._stdout_  :  the original stdout; don't touch!

從sys的help文件中對sys.stdout的定義得知,sys.stdout 中儲存的是輸出去向的引用。比如說sys.stdout預設指向的是cmd的視窗([1]中稱之為"控制檯(console)",我個人理解“控制檯”指的就是cmd視窗)。

當我們在Python中列印一個物件時print (obj),實際上是呼叫了 sys.stdout.write(obj+'\n')。

print將需要的內容列印到控制檯,然後追加一個換行符。

以下兩行實際上是等價的:

sys.stdout.write('hello'+'\n')
print 'hello'

下面給出一個使用sys.stdout的例子:
#coding=gbk
#將模組string的help文件儲存到名為”help_for_string.log“的檔案中
import sys,string
f = open('d:\\help_for_string.log','w')
sys.stdout = f
help(string)
f.close()
sys.stdout=sys.__stdout__ #兩個下劃線__stdout__

預設情況下,sys.stdout指向的控制檯,help(string)會將string的幫助文件輸出到cmd視窗上。若將sys.stdout指向被以“w”方式開啟的檔案“help_for_string.log”時,本該輸出到cmd介面的內容被輸出到(“w”)檔案中。使用print()同樣可以將某內容

參考:

[1] Python標準輸出sys.stdout重定向