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

 

 
 

 

 

 

 

转载于:https://www.cnblogs.com/valleyofwind/p/8628925.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值