【问题标题】:time.sleep not working as expected when adding end= to print()将 end= 添加到 print() 时,time.sleep 无法按预期工作
【发布时间】:2019-08-23 01:17:16
【问题描述】:

我正在尝试打印一条消息,每个字符之间的暂停时间为 0.2 秒。我在我的 print() 方法中添加了一个 end="" 以便消息出现在 1 行,但是当我启动线程时,在暂停之前只打印 1 个字符,直到剩余的睡眠时间结束并打印消息的其余部分.

没有 end="" 程序可以正常工作,但我不知道为什么。

import time,threading

msg = "68 111 110 117 116 115 32 97 114 101 32 98 111 109 98 "
msg = [int(x) for x in msg.split()]

def print_msg():
    for c in msg:
        print(chr(c),end=""),time.sleep(0.2)

threading.Thread(target=print_msg).start()

【问题讨论】:

    标签: python multithreading


    【解决方案1】:

    很高兴看到 OP 可以提供可执行示例!问题很简单,stdout有缓存,需要flush结果:

    import time, threading
    
    msg = "68 111 110 117 116 115 32 97 114 101 32 98 111 109 98 "
    msg = [int(x) for x in msg.split()]
    
    def print_msg():
        for c in msg:
            print(chr(c), end="", flush=True)
            time.sleep(0.2)
    
    threading.Thread(target=print_msg).start()
    

    【讨论】:

      猜你喜欢
      • 2011-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-23
      相关资源
      最近更新 更多