python 中sys.stdout.write 和 print >> sys.stdout的區別(轉)


下面應該可以解你的惑了:

print >> sys.stdout的形式就是print的一種默認輸出格式,等於print "%VALUE%"

看下面的代碼的英文注釋,是print的默認幫助信息

 1 # coding=utf-8
 2 import sys, os
 3  
 4 list1Display = ['1', '2', '3']
 5 list2Display = ['abc', 'def', 'rfs']
 6 while list2Display != []:
 7     # Prints the values to a stream, or to sys.stdout by default.
 8     # Optional keyword arguments:
 9     # file: a file-like object (stream); defaults to the current sys.stdout.
10     # sep:  string inserted between values, default a space.
11     # end:  string appended after the last value, default a newline.
12     # print 可以將值輸出到指定的輸出流(可以是文件句柄),若不指定,
13     # 則輸出到stdout(標准輸出)
14     # 一般我們使用的時候不加輸出定向符“>>”到輸出的file對象,本代碼中對象是stdout
15     # 下面的print在stdout對象中每次輸出兩個值
16     print >> sys.stdout, list2Display.pop(), list1Display.pop()
17 os.system( "pause" )

 

上 文中只演示了python2.x中的用法,2.x中的print無法指定end符號為其他值,默認會輸出一個"\n",也就是用一次必定換到下一行,到了 3.x中print成為了一個真正意義上的函數,后來就可以任意指定end符號的值,你可以輸出一次后末尾添加上任意你想要的值,而不是強制換行。

 

 

1 # coding=utf-8
2 import sys, os
3 import time
4 for i in range( 100 ):
5     time.sleep( .5 )
6     sys.stdout.write( "File transfer progress :[%3d] percent complete!\r" % i )
7     sys.stdout.flush()

 

因此在2.x中若想實現輸出不換行,只能直接調用stdout對象的write方法了,下面也是一個實例,因為stdout沒有end這個符號這一說,輸出不會換行,因此如果你想同一樣輸出多次,在需要輸出的字符串對象里面加上"\r",就可以回到行首了。

體會一下,將上面的"\r"拿掉試試看,是不是不換行而直接輸出了?明白了么。很長一段時間內python都會停留在2.x的時代。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM