遇到了很多关于这个问题和输出乱码(尤其是在 Windows 下向输出添加颜色时..),我的解决方案是拥有一个消耗队列的专有打印线程
如果这仍然不起作用,请按照@Or Duanflush=True
的建议添加到您的打印语句
此外,您可能会发现“最正确”,但使用线程显示消息的一种强硬方法是使用logging
可以包装队列(并异步写入许多地方,包括标准输出)或写入系统级的库队列(Python 之外;可用性很大程度上取决于操作系统支持)
import threading
from queue import Queue
def display_worker(display_queue):
while True:
line = display_queue.get()
if line is None: # simple termination logic, other sentinels can be used
break
print(line, flush=True) # remove flush if slow or using Python2
def some_other_worker(display_queue, other_args):
# NOTE accepts queue reference as an argument, though it could be a global
display_queue.put("something which should be printed from this thread")
def main():
display_queue = Queue() # synchronizes console output
screen_printing_thread = threading.Thread(
target=display_worker,
args=(display_queue,),
)
screen_printing_thread.start()
### other logic ###
display_queue.put(None) # end screen_printing_thread
screen_printing_thread.stop()