简体   繁体   English

让Python杀死PID

[英]Getting Python to kill a pid

This is the current code I have right now and I'm wondering how I can get it to kill the 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)

Edit: So, in the end, I just used os.system to get the terminal to run the kill command then place the pid after kill. 编辑:因此,最后,我只是使用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)

Overall this is my end result. 总的来说,这是我的最终结果。 Hope this helps people in the future. 希望这对以后的人们有所帮助。

Read this answer . 阅读此答案

BTW a more pythonic solution may be this: 顺便说一句,更pythonic解决方案可能是这样的:

    import re
    import psutil

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

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

Edit: To be more accurate I changed the line p.kill() to p.terminate() . 编辑:为了更准确,我将行p.kill()更改为p.terminate() The common kill in bash is actually the same as p.terminate() (it sends the TERM signal). 常见kill在bash实际上是一样的p.terminate()它发送TERM信号)。 But the p.kill() corresponds to kill -9 in bash (it sends the KILL signal). 但是p.kill()相当于在bash中kill -9 (它发送KILL信号)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM