gpt4 book ai didi

python子进程: find out in the signal handler which child terminated

转载 作者:太空宇宙 更新时间:2023-11-03 17:11:03 24 4
gpt4 key购买 nike

我有一个 python 脚本,它使用 subprocess.Popen 启动多个命令。我添加了一个信号处理程序,如果 child 退出则调用该信号处理程序。我想检查哪个 child 终止了。我可以通过迭代所有子项来做到这一点:

#!/usr/bin/env python
import subprocess
import signal

procs = []

def signal_handler(signum, frame):
for proc in procs:
proc.poll()
if proc.returncode is not None:
print "%s returned %s" % (proc.pid, proc.returncode)
procs.remove(proc)

def main():
signal.signal(signal.SIGCHLD, signal_handler)
procs.append(subprocess.Popen(["/bin/sleep", "2"]))
procs.append(subprocess.Popen(["/bin/sleep","5"]))
# wait so the main process does not terminate immediately
procs[1].wait()

if __name__ == "__main__":
main()

我想避免查询所有子流程。有没有办法在信号处理程序中确定哪个子进程终止?

最佳答案

您可以使用 multiprocessing 获得类似的结果。您可以使用 threading如果您不想生成额外的进程,请改为打包。它具有几乎完全相同的界面。基本上,每个子进程调用都发生在一个新进程中,然后启动您的 sleep 进程。

import subprocess
import multiprocessing

def callback(result):
# do something with result
pid, returncode = result
print pid, returncode


def call_process(cmd):
p = subprocess.Popen(cmd)
p.wait()
return p.pid, p.returncode


def main():
pool = multiprocessing.Pool()
pool.apply_async(call_process, [["/bin/sleep", "2"]], callback=callback)
pool.apply_async(call_process, [["/bin/sleep", "5"]], callback=callback)
pool.close()
pool.join()


main()

关于python子进程: find out in the signal handler which child terminated,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34080297/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com