让 Python 杀死一个 pid

Getting Python to kill a pid

这是我现在拥有的当前代码,我想知道如何使用它来终止 pid。

import commands, signal
stuid = commands.getoutput("pgrep student")
deaid = commands.getoutput("pgrep daemon")
print stuid
os.kill(stuid, signal.SIGKILL)
print deaid
os.kill(deaid, signal.SIGKILL)

编辑: 所以,最后,我只是使用 os.system 让终端进入 运行 kill 命令,然后在 kill 之后放置 pid。

import commands, os
stuid = commands.getoutput("pgrep student")
deaid = commands.getoutput("pgrep daemon")
print stuid
os.system("kill "+stuid)
print deaid
os.system("kill "+deaid)

总的来说这是我的最终结果。希望这对以后的人有帮助。

阅读this answer

顺便说一句,一个更 pythonic 的解决方案可能是这样的:

    import re
    import psutil

    convicted = re.compile(r'student|daemon')

    for p in psutil.process_iter():
        if convicted.search(p.name):
            p.terminate()

编辑:为了更准确,我将行 p.kill() 更改为 p.terminate()。 bash中常见的kill其实和p.terminate()是一样的(它发送的是TERM信号)。但是 p.kill() 对应于 bash 中的 kill -9 (它发送 KILL 信号)。