终止使用Python的subprocess.Popen()创建的进程

2024-05-20 11:00:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我的想法是:

首先,我使用subprocess.Popen创建了一个进程

第二,经过一段时间后,我试图用Popen.kill()杀死它

import subprocess
import os, signal
import time

proc1 = subprocess.Popen("kvm -hda /path/xp.img", shell = True)
time.sleep(2.0)
print 'proc1 = ', proc1.pid
subprocess.Popen.kill(proc1)

但是,Popen.kill()之后仍然存在“proc1”。 有专家能告诉我怎么解决这个问题吗? 我很感激你的考虑。

感谢所有专家的评论,我做了你推荐的所有事情,但结果仍然是一样的。

proc1.kill() #it sill cannot kill the proc1

os.kill(proc1.pid, signal.SIGKILL) # either cannot kill the proc1

还是谢谢你。

我仍在等待你解决这个棘手问题的宝贵经验。


Tags: theimportsignaltime进程oskvmpid
3条回答

在你的代码中应该是

proc1.kill()

killterminate都是Popen对象的方法,它们向进程发送信号signal.SIGKILL

只使用Popenkill方法

process = subprocess.Popen(
    task.getExecutable(), 
    stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE, 
    shell=True
)
process.kill()

process.terminate()在使用shell=True时不起作用。这个answer对你有帮助。

相关问题 更多 >