Tristan Hayes
Tristan Hayes

Reputation: 13

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.

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.

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.

Upvotes: 0

Views: 1255

Answers (1)

hancar
hancar

Reputation: 797

Read this answer.

BTW a more pythonic solution may be this:

    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(). The common kill in bash is actually the same as p.terminate() (it sends the TERM signal). But the p.kill() corresponds to kill -9 in bash (it sends the KILL signal).

Upvotes: 2

Related Questions