1

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?

Tibor Balogh
  • 27
  • 1
  • 7
  • 2
    To get PID [check this](http://stackoverflow.com/questions/26688936/python-how-to-get-pid-by-process-name). To kill process by PID [check this](http://stackoverflow.com/questions/17856928/how-to-terminate-process-from-python-using-pid). – ElTête May 20 '16 at 11:06

3 Answers3

1

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
MilkeyMouse
  • 581
  • 4
  • 11
1

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()
ElTête
  • 555
  • 1
  • 5
  • 15
  • For some reason the subprocess module doesn't work for me. I tried lots of commands from the module, almost everything. The program doesn't throw any error. I just simply doesn't get any answer. The commands I typed in behaves like it doesn't exist. – Tibor Balogh May 20 '16 at 11:50
-1

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.

RicardoE
  • 1,665
  • 6
  • 24
  • 42