加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 为什么同行打印之间没有延迟?

发布时间:2020-12-20 11:53:14 所属栏目:Python 来源:网络整理
导读:print 'foo',time.sleep(1)print 'bar' 这似乎首先运行time.sleep(1),然后一次打
print 'foo',time.sleep(1)
print 'bar'

这似乎首先运行time.sleep(1),然后一次打印“foo bar”.

但是,在自己的行上打印foo和bar会在print语句之间产生预期的延迟:

print 'foo'
time.sleep(1)
print 'bar'

是否有东西堆叠所有打印语句,直到收到新的行字符?

解决方法

print默认打印到sys.stdout并且是行缓冲的.你可以在print语句后每次刷新缓冲区

import time
import sys

print 'foo'
sys.stdout.flush()
time.sleep(1)
print 'bar

参考:sys

另请阅读:How to flush output of Python print?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读