我不知道何时需要终止子进程。
for package in server.packages:
n = subprocess.Popen(['which', package], stdout=subprocess.DEVNULL)
n.wait()
if n.returncode != 0:
n.kill()
<some other code>
我收到错误消息(使用Python3):
ProcessLookupError: [Errno 3] No such process
有人可以解释我什么时候子进程自杀了,什么时候我需要手动杀死它?
在Python中,Popen.wait
是一个等待子进程终止的阻塞调用。因此,通常在调用return之后无需杀死子进程wait
。请参阅Popen.wait()上的Python文档。
现在,如果您了解了它的工作原理,则可以看到代码失败,因为在某些时候Popen.returncode
返回一个非零值,然后尝试杀死一个不再存在的进程。
这就是为什么ProcessLookupError
提高a的原因。
现在,如此处另一个答案所指出的那样,返回的值可能是None
,这表明子进程可能存在(也许是特定于OS的)问题,可以进行检查。Python文档仅仅状态即None
表示该过程仍在运行(负值也是可能的;见文档的详细信息)。
除此之外,如果出于某种原因需要终止仍在运行的子进程,则必须使用以下方法设置并捕获超时:
try:
# time out in five seconds
n.wait(timeout=5)
except TimeOutExpired:
# you can use kill, terminate or send_signal method; see the docs
n.kill()
...,或者完全不使用wait
:而是让子进程在您执行代码中的其他操作时运行,然后在以后将其杀死:
import os
processes = []
for package in server.packages:
n = subprocess.Popen(['which', package], stdout=subprocess.DEVNULL)
processes.append(n)
<some other code while the subprocesses run (and possibly terminate)>
for p in processes:
try:
p.kill()
except OSError:
# silently fail if the subprocess has exited already
pass
如果您只想检查过程是否还存在怎么办?不幸的是,Python stdlib没有一种检查进程是否正在运行的好方法。但是,可以使用第三方库psutil方便地完成此操作。有了它,检查一个过程是否存在就很容易:
pid = n.pid # where n is a subprocess.Popen object from above examples
import psutil
psutil.pid_exists(pid) # returns True or False
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句