使用 Python 检查子进程当前是否在任何线程中 运行

Check if subprocess currently running in any thread using Python

我正在使用 threading.Timer 函数同时 运行 多个计时器。一旦每个定时器结束,调用的函数使用带有"say"命令的子进程,如下所示:

subprocess.call(["say", "hello world"])

有时,计时器会在不久后彼此关闭,然后他们就会开始互相交谈。我怎样才能让他们互相等待而不重叠?

我仍然希望在发生这种情况时能够在主程序中做其他事情(例如制作新计时器)所以我认为我不能只使用 popen.wait() 或 .join ()

如果 say 可执行文件运行速度很快,您可以锁定它的调用:

lock = threading.Lock()

def your_thread_function():
    do_something_slow()
    with lock:
        subprocess.call(["say", "hello world"])

如果 say 可执行文件本身很慢,您将不得不存储它的输出并且只在调用结束时打印出来(再次锁定):

lock = threading.Lock()

def your_thread_function():
    # You can also use subprocess.check_output.
    p = subprocess.Popen(["say", "hello world"], stdout=subprocess.PIPE)
    out, err = p.communicate()
    with lock:
        print(out)