我用这种方式调用了一个子进程:
myProc = subprocess.Popen([args],shell=False)
我需要检查子进程是否因错误而结束。我没有使用communicate()
,因为我不想实际等待进程结束,我只需要知道子进程是否由于错误而结束。有没有办法做到这一点?
答案 0 :(得分:1)
您可以通过等待进程在后台线程中结束并从该线程执行回调来执行此操作:
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!