Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python线程仅在连接后打印到标准输出_Python_Multithreading_Python Multithreading - Fatal编程技术网

python线程仅在连接后打印到标准输出

python线程仅在连接后打印到标准输出,python,multithreading,python-multithreading,Python,Multithreading,Python Multithreading,我有一个python程序,我正在尝试添加一个进度条。我的线程类是: class ProgressThread(threading.Thread): def __init__(self): super(ProgressThread, self).__init__() self.stoprequest = threading.Event() def run(self): while not self.stoprequest.is_se

我有一个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)
然后在我的主线程中,我使用上面的thread类,如下所示:

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

我遇到的问题是,在调用join()之前,不会打印点。正确的点数对应于长时间运行方法完成所需的时间,但我希望它们一个接一个地显示出来,只是为了向用户显示程序没有挂起。

我认为问题在于,当您使用
print.”,
时,您没有打印出换行符(逗号阻止了这一点)。默认情况下,在看到换行符之前,标准输出不会刷新到屏幕上。您可以通过在
print
语句之后添加
sys.stdout.flush()
来解决这个问题。这将强制将输出打印到屏幕上。

您的代码在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()

尝试在
打印后添加
sys.stdout.flush()
。是的,这就是问题所在…谢谢!您的测试用例在
print
语句中缺少逗号,这造成了所有的差异。@您说得对。通过添加逗号,我可以重现OP的问题,这确实是一个刷新问题。为什么输出会在CLI中按预期显示,但在添加对flush()的调用之前,在通过process manager(本例中为circus)运行时不会显示?