gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 05:14:25 25 4
gpt4 key购买 nike

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

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

我不确定如何更改此设置,以便我可以使用 Popen.pid 获取 pid,同时仍然能够检查执行是否成功。任何帮助,将不胜感激。谢谢。

最佳答案

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

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 变体允许您的代码在子进程退出后立即继续。

关于python - Python中进程执行检查并获取PID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23505274/

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