Sys. stdout. write and print and sys. stdout. flush, sys. stdout. write
1. Read the official documentation first.
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 """
We can see that
① Sys. stdout. write writes str to the stream. It is not blocked and will not default end = '\ n' like print'
② Sys. stdout. write can only output one str, while print can output multiple str, and the default sep = ''(one space)
③ Print. The default value is flush = False.
④ Print can also directly write the value to file
1 import sys2 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 instance3 Flush write buffers, if applicable.4 5 This is not implemented for read-only and non-blocking streams.
Flush indicates a refresh. There is a buffer in the output of print and sys. stdout. write.
For example, if you want to output a string to the file, it is written into the memory first (Because print defaults to flush = False, and flush is not executed manually). There is nothing to open the file directly before closing the file, if you execute a flush command, you will have it.
1 import time2 import sys3 4 for i in range(5):5 print(i)6 sys.stdout.flush()7 time.sleep(1)
When the code is executed on the terminal, a number is output in one second. However, if flush is commented out, 01234 will be output once in 5 seconds.