Tibor Balogh
Tibor Balogh

Reputation: 27

Get a PID number of a process and than kill it with Python

I use Python code that starts omxplayer. It plays songs and sometimes plays an advertisement during the song. In this case two players run. The problem comes when the omxplayer times out. After time out I cannot close it, so till now I've used

os.system("killall -9 omxplayer.bin")

It is ok when just one song is being played , but when an advertisement has ended during a song and the omxplayer times out (do not know why, but time out happens very often) this command kills both omxplayers. So it would be great if I can get the PID of the processes (omxplayer.bin) store it in a variable in python and use it to kill the process. But I would appreciate any solution which can return the PID of a given process and than kill it from the python code. I tried so many things so far. Anybody can help me with this?

Upvotes: 1

Views: 8499

Answers (3)

RicardoE
RicardoE

Reputation: 1725

I know this question is old, but here is what I came out with, it works for java proceses:

First get the pid

def getPidByName(name):
    process = check_output(["ps", "-fea"]).split('\n')
    for x in range(0, len(process)):
        args = process[x].split(' ')
        for j in range(0, len(args)):
            part = args[j]
            if(name in part):
                return args[2]

And then kill it pid = getPidByName("user-access") os.kill(int(pid), signal.SIGKILL)

just as @ElTête mentioned.

For different process you might have to adjust the return index in args, depending in the process you are trying to kill. Or just iterate across the command and kill where you find an occurrence of the name. This mainly because "pidof" won't work on macOs or windows.

Upvotes: -1

ElTête
ElTête

Reputation: 585

A possible solution, as I commented:

import os
import signal
from subprocess import check_output

def get_pid(name):
    return check_output(["pidof", name])

def main():
    os.kill(get_pid(whatever_you_search), signal.SIGTERM) #or signal.SIGKILL 

if __name__ == "__main__":
    main()

Upvotes: 1

MilkeyMouse
MilkeyMouse

Reputation: 591

I'd recommend using psutil, specifically psutil.process_iter():

>>> # get all PIDs
>>> psutil.pids()
[0, 4, 472, 648, 756, ...]
>>> # but for iteration you should use process_iter()
>>> for proc in psutil.process_iter():
>>>     try:
>>>         if pinfo.name() == "omxplayer":
>>>             pinfo.terminate()
>>>     except psutil.NoSuchProcess:
>>>         pass

Upvotes: 1

Related Questions