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