进程执行检查并在Python中获取PID

时间:2014-05-06 22:01:22

标签: python if-statement subprocess popen pid

我需要在后台运行bash命令,但之后需要杀死它(os.kill())。我还想确保命令运行我有这个以确保命令运行。

if subprocess.Popen("tcpdump -i eth0 -XX -w /tmp/tmp.cap &", shell=True).wait() == 0:

我不确定如何改变这一点,所以我可以使用Popen.pid获取pid,同时仍能检查执行是否成功。 任何帮助,将不胜感激。 感谢。

2 个答案:

答案 0 :(得分:2)

要启动子进程,请等待一段时间并将其终止,然后检查其退出状态是否为零:

import shlex
from subprocess import Popen
from threading import Timer

def kill(process):
    try:
        process.kill()
    except OSError: 
        pass # ignore

p = Popen(shlex.split("tcpdump -i eth0 -XX -w /tmp/tmp.cat"))
t = Timer(10, kill, [p]) # run kill in 10 seconds
t.start()
returncode = p.wait()
t.cancel()
if returncode != 0:
   # ...

或者您可以自己实施超时:

import shlex
from subprocess import Popen
from time import sleep, time as timer # use time.monotonic instead

p = Popen(shlex.split("tcpdump -i eth0 -XX -w /tmp/tmp.cat"))

deadline = timer() + 10 # kill in 10 seconds if not complete
while timer() < deadline:
    if p.poll() is not None: # process has finished
        break 
    sleep(1) # sleep a second
else: # timeout happened
    try:
        p.kill()
    except OSError:
        pass

if p.wait() != 0:
   # ...

假设sleep使用与timer类似的时钟。

threading.Timer变体允许您的代码在子进程退出后立即继续。

答案 1 :(得分:0)

使用Popen.poll()方法。您也可以获取Popen.returncode以确定流程是否成功完成。

import subprocess

tasks = [subprocess.Popen('ping www.stackoverflow.com -n 5 && exit 0', shell=True),
         subprocess.Popen('ping www.stackoverflow.com -n 5 && exit 1', shell=True)]

for task in tasks:
    while task.poll() is None:
        # the task has not finished
        pass

    print task
    print task.pid
    print task.returncode