Python线程只有在join后才输出到stdout

2 投票
2 回答
2632 浏览
提问于 2025-04-18 13:44

我有一个Python程序,我想给它加一个进度条。我的线程类是:

class ProgressThread(threading.Thread):
    def __init__(self):
        super(ProgressThread, self).__init__()
        self.stoprequest = threading.Event()

    def run(self):
        while not self.stoprequest.is_set():
            print ".",
            time.sleep(5)

    def join(self, timeout=None):
        self.stoprequest.set()
        super(ProgressThread, self).join(timeout)

然后在我的主线程中,我是这样使用上面的线程类的:

progress_thread = ProgressThread()
progress_thread.start()
ret = long_running_method()
progress_thread.join()

我遇到的问题是,点(.)不会在我调用join()之前打印出来。虽然点的数量是正确的,和long_running_method完成的时间相对应,但我希望它们能一个一个地显示出来,这样可以告诉用户程序没有卡住。

2 个回答

2

你的代码在我这里的Mac上,Python 2.7.8和3.4.1都能正常运行。这里是我的测试案例:

import threading, time


class ProgressThread(threading.Thread):
   def __init__(self):
       super(ProgressThread, self).__init__()
       self.stoprequest = threading.Event()

   def run(self):
       while not self.stoprequest.is_set():
           print(".")
           time.sleep(1)

   def join(self, timeout=None):
       self.stoprequest.set()
       super(ProgressThread, self).join(timeout)

def long_running_method():
    time.sleep(5)

progress_thread = ProgressThread()
progress_thread.start()
ret = long_running_method()
progress_thread.join()

可能是你的终端或者操作系统有输出缓冲的问题?试着刷新一下你的输出:

import sys
sys.stdout.flush()
3

我觉得问题出在你使用 print ".", 的时候,没有打印出换行符(因为逗号的原因)。默认情况下,输出到屏幕的内容不会立即显示,直到遇到换行符 \n。你可以通过在 print 语句后面加上 sys.stdout.flush() 来解决这个问题。这样可以强制输出内容立刻显示在屏幕上。

撰写回答