gpt4 book ai didi

Python 3.4 : check if a process ends

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

我以这种方式调用了子进程:

myProc = subprocess.Popen([args],shell=False)

我需要检查子进程是否因错误而结束。我没有使用 communicate() ,因为我不想真正等待进程结束,我只需要知道子进程是否由于错误而结束。有办法做到这一点吗?

最佳答案

您可以通过在后台线程中等待进程结束并从该线程执行回调来完成此操作:

import subprocess
from threading import Thread

def async_wait(proc, cb):
if proc.wait() != 0:
# If you don't need a generic async_wait, you can
# just execute whatever cb would do here,
# and not pass it in as a separate function.
cb(proc)

def handle_error(proc):
print("%s failed!" % proc)

myProc = subprocess.Popen(["ls", "/asdfsd"], shell=False)
t = Thread(target=async_wait, args=(myProc, handle_error)).start()
t.start()
print("hi")

输出:

hi
ls: cannot access /asdfsd: No such file or directory
<subprocess.Popen object at 0x7f26d8c70210> failed!

关于Python 3.4 : check if a process ends,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29124248/

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