【问题标题】:Why is there no delay between same-line printing?为什么同行打印之间没有延迟?
【发布时间】:2016-08-01 09:12:55
【问题描述】:
print 'foo',
time.sleep(1)
print 'bar'

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

但是,在单独的行上同时打印 foobar 会在打印语句之间产生预期的延迟:

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

有什么东西可以堆叠所有打印语句直到收到换行符?

【问题讨论】:

    标签: python printing output delay


    【解决方案1】:

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

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

    参考:sys

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-26
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      相关资源
      最近更新 更多