[Python]print vs sys.stdout.write,pythonsys.stdout
之前只是在項目中看到過,沒怎麼注意,正好跟對象一起看python學習手冊,看到了這個部分於是來研究下。python版本 2.7.xos win7
print 一般就是執行指令碼的時候,把資訊直接列印到標準輸出,也就是我們通常說的控制台print是python __builtin__ 中的一個方法,來看看他的定義
def print(stream): """ print(value, ..., sep=' ', end='\\n', file=sys.stdout) Prints the values to a stream, or to sys.stdout by default. Optional keyword arguments: file: a file-like object (stream); defaults to the current sys.stdout. sep: string inserted between values, default a space. end: string appended after the last value, default a newline. """ pass
從這裡我們就能看到print也許比我們常用的功能多一些* sep 用來做values之間的分割符,所以當我們 print '2', 'a' 的時候,實際中間是空格* end 預設是換行,所以print總是列印一行資訊* 其實print還可以輸出到檔案中但我們又知道python2中的print 後面是沒有參數列表的
In [2]: print ('a', 'b', sep='|') File "<ipython-input-2-bcb798285c07>", line 1 print ('a', 'b', sep='|') ^SyntaxError: invalid syntax
哦噢,報錯了,其實只要 from __future__ import print_function 就可以像python3一樣使用參數了
In [6]: print('a', 'b')a b In [7]: print('a', 'b', sep='--') #print 多個values 不用逗號分隔a--b In [8]: print('nihao');print('orangle') nihaoorangle In [9]: print('nihao', end='');print('orangle') #print 不換行nihaoorangle
好像print也有不少玩法哦我們直接把print的值寫到檔案對象中,而不是預設的sys.stout試
In [11]: f = open('test.txt', 'w')In [12]: print('haha.....csdn', file=f)In [15]: ls test.txt 磁碟機 D 中的卷沒有標籤。 卷的序號是 0002-FA2E D:\code\python 的目錄2015/01/20 周二 10:37 0 test.txt 1 個檔案 0 位元組 0 個目錄 61,124,526,080 可用位元組In [16]: f.close()到對應的目錄下看看,test.txt的內容,果然是 haha.....csdn, 不過一定要記得 f.close(), 如果不關閉,內容是無法儲存到檔案中的。
sys.stdout.write這個方法調用的是 ,file 對象中的write方法 ,把字元寫到標準輸出中,看起來跟print 差不多。
def write(self, str): """ write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. """ return ""
關係這個方法和print什麼關係呢? 我們來查查可以認為 print是對 sys.stdout.write的友好封裝,也只是從 python學習手冊這樣看到。
區別print 可以把一個對象轉化成str然後放到標準輸出中, sys.stdout.write 需要把對象先轉化成對象在輸出
In [3]: class A(): ...: def __str__(self): ...: return "A" ...: In [5]: a = A()In [6]: print aA In [9]: import sysIn [10]: sys.stdout.write(a)---------------------------------------------------------------------------TypeError Traceback (most recent call last)<ipython-input-10-0697f962911e> in <module>()----> 1 sys.stdout.write(a) TypeError: expected a character buffer object In [11]: sys.stdout.write(str(a))A
所以說不能用 sys.stdout.write來直接代替 print
運用這裡兩者怎麼結合使用?引用 Learning Python 中的一段代碼
import systemp = sys.stdout #store original stdout object for latersys.stdout = open('log.txt','w') #redirect all prints to this log fileprint("testing123") #nothing appears at interactive promptprint("another line") #again nothing appears. It is instead written to log filesys.stdout.close() #ordinary file objectsys.stdout = temp #restore print commands to interactive promptprint("back to normal") #this shows up in the interactive prompt
log.txt檔案中儲存輸出結果為
testing123another line
我們可以把調試中列印的資訊儲存的檔案中,這樣也是追中和尋找錯誤的一個方式
還有就是多線程日誌中可能會用到 sys.stdout.write 來封裝日誌寫入
參考文章:http://woodpecker.org.cn/diveintopython/scripts_and_streams/stdin_stdout_stderr.html
http://stackoverflow.com/questions/3263672/python-the-difference-between-sys-stdout-write-and-print
本文出自 “orangleliu筆記本” 部落格,轉載請務必保留此出處http://blog.csdn.net/orangleliu/article/details/42915501
作者orangleliu 採用署名-非商業性使用-相同方式共用協議