简体   繁体   中英

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?

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

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()

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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