sys.stdout.write和print和sys.stdout.flush


1. 先看下官方文檔
 1 """
 2 sys.stdout.write(string)
 3   Write string to stream.
 4   Returns the number of characters written (which is always equal to the length of the string).
 5 
 6 print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
 7   Prints the values to a stream, or to sys.stdout by default.
 8 
 9   Optional keyword arguments:
10   file:  a file-like object (stream); defaults to the current sys.stdout.
11   sep:   string inserted between values, default a space.
12   end:   string appended after the last value, default a newline.
13   flush: whether to forcibly flush the stream.
14 """

可以看出

①sys.stdout.write是將str寫到流,原封不動,不會像print那樣默認end='\n'

②sys.stdout.write只能輸出一個str,而print能輸出多個str,且默認sep=' '(一個空格)

③print,默認flush=False.

④print還可以直接把值寫到file中

1 import sys
2 f = open('test.txt', 'w')
3 print('print write into file', file=f)
4 f.close()

 

2. sys.stdout.flush()

1 flush() 
2     method of _io.TextIOWrapper instance
3     Flush write buffers, if applicable.
4     
5     This is not implemented for read-only and non-blocking streams.

flush是刷新的意思,在print和sys.stdout.write輸出時是有一個緩沖區的。

比如要向文件里輸出字符串,是先寫進內存(因為print默認flush=False,也沒有手動執行flush的話),在close文件之前直接打開文件是沒有東西的,如果執行一個flush就有了。

1 import time
2 import sys
3  
4 for i in range(5):
5     print(i)
6     sys.stdout.flush()
7     time.sleep(1)

在終端執行上面代碼,會一秒輸出一個數字。然而如果注釋掉flush,就會在5秒后一次輸出01234

 

 
        

 

 

 

 


免責聲明!

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



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