【问题标题】:Getting Python to kill a pid让 Python 杀死一个 pid
【发布时间】:2017-10-31 20:46:55
【问题描述】:

这是我现在拥有的当前代码,我想知道如何让它杀死 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命令,然后把pid放在kill之后。

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)

总的来说,这是我的最终结果。希望这对未来的人们有所帮助。

【问题讨论】:

标签: python python-2.7 pid


【解决方案1】:

阅读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 信号)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多