终止使用Python的subprocess.Popen()创建的进程[重复]

2024-03-07

这是我的想法:

首先,我使用 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)

然而,“proc1”在 Popen.kill() 之后仍然存在。 有专家可以告诉我如何解决这个问题吗? 我很欣赏你的考虑。

感谢所有专家的评论,我做了您建议的所有操作,但结果仍然相同。

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

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

还是谢谢大家了。

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


在你的代码中应该是

proc1.kill()

Both kill https://docs.python.org/3/library/subprocess.html#subprocess.Popen.kill or terminate https://docs.python.org/3/library/subprocess.html#subprocess.Popen.terminate的方法是Popen object https://docs.python.org/3/library/subprocess.html#popen-objects。在 macOS 和 Linux 上,kill发送信号signal.SIGKILL https://docs.python.org/3/library/signal.html#signal.SIGKILL到过程和terminate sends signal.SIGTERM https://docs.python.org/3/library/signal.html#signal.SIGTERM。在 Windows 上,它们都称为 Windows'TerminateProcess() https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-terminateprocess功能。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

终止使用Python的subprocess.Popen()创建的进程[重复] 的相关文章

随机推荐