Python 3.4:检查进程是否结束

Python 3.4: check if a process ends

我已经这样调用了一个子进程:

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!