Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/341.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_Process - Fatal编程技术网

Python 执行任务时侦听线程

Python 执行任务时侦听线程,python,multithreading,process,Python,Multithreading,Process,我试图寻找答案,但找不到任何相关的答案。因此,决定提问 我有一个脚本a。在脚本a的开头,它在一个单独的线程中调用脚本B(或者一个函数,或者可以运行) A继续做一些任务。我想继续执行脚本A,直到脚本B没有完成 在继续A的任务时,我如何倾听B的结束 比如说, Call Script B using subprocess, import file and run function (either way) while(1): count=count+1 if script B ended:

我试图寻找答案,但找不到任何相关的答案。因此,决定提问

我有一个脚本a。在脚本a的开头,它在一个单独的线程中调用脚本B(或者一个函数,或者可以运行)

A继续做一些任务。我想继续执行脚本A,直到脚本B没有完成

在继续A的任务时,我如何倾听B的结束

比如说,

Call Script B using subprocess, import file and run function (either way)
while(1):
   count=count+1
   if script B ended:
        break

有人能举例说明如何检查“脚本B结束”部分吗?

这里有一个非常简单的方法来完成您想要的操作:

import time
from threading import Thread

def stupid_work():
    time.sleep(4)

if __name__ == '__main__':
    t = Thread(target=stupid_work)
    t.start()
    while 1:
        if not t.is_alive():
            print 'thread is done'
            break # or whatever
        else:
            print 'thread is working'    

        time.sleep(1)

线程完成后会死掉,所以您只需间歇性地检查它是否仍然存在。您没有提到需要返回值。如果这样做,则可以向目标函数传递一个队列,并将
如果不是t.is\u alive()
替换为
如果不是q.empty()
。然后执行
q.get()
以在返回值准备就绪时检索返回值。并确保让目标将返回值放入队列中,否则您将等待很长时间。

如果您正在使用子流程模块,则可以执行类似操作

from subprocess import Popen
proc = Popen(["sleep", "100"])

while True:
    if proc.poll() is not None:
        print("proc is done")
        break

有关子流程和轮询的详细信息。

如何调用脚本B?您是使用单独的线程还是单独的进程调用它?它调用另一个使用子进程调用该脚本的函数。(如果有帮助的话,我愿意改变)。非常感谢。我不能投你一票,因为我的名声不好(我需要15票)。但我会记住,一旦我获得了一些选票,我会立即投票。这正是我想要的。非常感谢您提供有关返回值的额外信息。在将来的某个时候,我可能会要求这样做