杀死使用 Python 的 subprocess.Popen() 创建的进程
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4084322/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Killing a process created with Python's subprocess.Popen()
提问by user495511
Here is my thought:
这是我的想法:
First of all, I created a process by using subprocess.Popen
首先,我使用 subprocess.Popen 创建了一个流程
Second, after certain amount of time, I tried to kill it by Popen.kill()
其次,经过一定时间后,我尝试通过 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)
However, "proc1" still exists after Popen.kill(). Could any experts tell me how to solve this issue? I appreciate your considerations.
但是,“proc1”在 Popen.kill() 之后仍然存在。有没有高手能告诉我如何解决这个问题?我很欣赏你的考虑。
Thanks to the comments from all experts, I did all you recommended, but result still remains the same.
感谢所有专家的意见,我做了你推荐的所有事情,但结果仍然一样。
proc1.kill() #it sill cannot kill the proc1
proc1.kill() #it sill cannot kill the proc1
os.kill(proc1.pid, signal.SIGKILL) # either cannot kill the proc1
Thank you all the same.
谢谢大家一样。
And I am still waiting for your precious experience on solving this delicate issue.
我仍在等待您解决这个棘手问题的宝贵经验。
回答by Michael Patterson
How about using os.kill? See the docs here: http://docs.python.org/library/os.html#os.kill
使用 os.kill 怎么样?请参阅此处的文档:http: //docs.python.org/library/os.html#os.kill
回答by pyfunc
In your code it should be
在你的代码中它应该是
proc1.kill()
Both killor terminateare methods of the Popenobject which sends the signal signal.SIGKILLto the process.
两者kill或terminate都是Popen向signal.SIGKILL进程发送信号的对象的方法。
回答by Jorge Niedbalski R.
Only use Popenkill method
只使用Popenkill方法
process = subprocess.Popen(
task.getExecutable(),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
shell=True
)
process.kill()

