How to get PID by process name?
Solution 1
You can get the pid of processes by name using pidof
through subprocess.check_output:
from subprocess import check_output
def get_pid(name):
return check_output(["pidof",name])
In [5]: get_pid("java")
Out[5]: '23366\n'
check_output(["pidof",name])
will run the command as "pidof process_name"
, If the return code was non-zero it raises a CalledProcessError.
To handle multiple entries and cast to ints:
from subprocess import check_output
def get_pid(name):
return map(int,check_output(["pidof",name]).split())
In [21]: get_pid("chrome")
Out[21]:
[27698, 27678, 27665, 27649, 27540, 27530, 27517, 14884, 14719, 13849, 13708, 7713, 7310, 7291, 7217, 7208, 7204, 7189, 7180, 7175, 7166, 7151, 7138, 7127, 7117, 7114, 7107, 7095, 7091, 7087, 7083, 7073, 7065, 7056, 7048, 7028, 7011, 6997]
Or pas the -s
flag to get a single pid:
def get_pid(name):
return int(check_output(["pidof","-s",name]))
In [25]: get_pid("chrome")
Out[25]: 27698
Solution 2
You can use psutil
package:
Install
pip install psutil
Usage:
import psutil
process_name = "chrome"
pid = None
for proc in psutil.process_iter():
if process_name in proc.name():
pid = proc.pid
Solution 3
For posix (Linux, BSD, etc... only need /proc directory to be mounted) it's easier to work with os files in /proc. It's pure python, no need to call shell programs outside.
Works on python 2 and 3 ( The only difference (2to3) is the Exception tree, therefore the "except Exception", which I dislike but kept to maintain compatibility. Also could've created a custom exception.)
#!/usr/bin/env python
import os
import sys
for dirname in os.listdir('/proc'):
if dirname == 'curproc':
continue
try:
with open('/proc/{}/cmdline'.format(dirname), mode='rb') as fd:
content = fd.read().decode().split('\x00')
except Exception:
continue
for i in sys.argv[1:]:
if i in content[0]:
print('{0:<12} : {1}'.format(dirname, ' '.join(content)))
Sample Output (it works like pgrep):
phoemur ~/python $ ./pgrep.py bash
1487 : -bash
1779 : /bin/bash
Solution 4
you can also use pgrep
, in prgep
you can also give pattern for match
import subprocess
child = subprocess.Popen(['pgrep','program_name'], stdout=subprocess.PIPE, shell=True)
result = child.communicate()[0]
you can also use awk
with ps like this
ps aux | awk '/name/{print $2}'
Solution 5
Complete example based on the excellent @Hackaholic's answer:
def get_process_id(name):
"""Return process ids found by (partial) name or regex.
>>> get_process_id('kthreadd')
[2]
>>> get_process_id('watchdog')
[10, 11, 16, 21, 26, 31, 36, 41, 46, 51, 56, 61] # ymmv
>>> get_process_id('non-existent process')
[]
"""
child = subprocess.Popen(['pgrep', '-f', name], stdout=subprocess.PIPE, shell=False)
response = child.communicate()[0]
return [int(pid) for pid in response.split()]
B Faley
Updated on July 02, 2021Comments
-
B Faley almost 3 years
Is there any way I can get the PID by process name in Python?
PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 3110 meysam 20 0 971m 286m 63m S 14.0 7.9 14:24.50 chrome
For example I need to get
3110
bychrome
. -
Avinash Raj over 9 years+1 seems like a perfect answer. could you explain this
return check_output(["pidof",name])
-
Padraic Cunningham over 9 years@AvinashRaj, added an explanation, hopefully makes it a little more clear
-
ThiefMaster over 9 yearsWhy not go through /proc entries instead of calling external tools? While common in bash scripts, it's usually not very clean to do so in python scripts. Also, what if there are multiple processes with that name? I would at least
splitlines()
the output and covert the pids to ints. -
Padraic Cunningham over 9 years@ThiefMaster, what is not clean about using the pidof command?
-
ThiefMaster over 9 yearsIs it even available by default on all/most linux systems?
-
Padraic Cunningham over 9 years@ThiefMaster, as far as I know yes it is. Also I used split with map to convert to ints and handle the case if there are multiple processes with that name. I still don't get your problem with using the command. parsing the top output will also give multiple process id's
-
ThiefMaster over 9 yearsYou could use one of the helper functions in the subprocess module.. much more readable. Also, executing it inside a shell is a really bad idea!
-
Hackaholic over 9 yearsyep its just a concept, I have given to OP
-
sobolevn over 8 yearsit is better to run with
shell=False
. -
Jaime M. about 8 yearsNote that check_output() is not available in Python 2.6 and older versions.
-
Padraic Cunningham about 8 years@JaimeM., it is pretty trivial to implement gist.github.com/edufelipe/1027906
-
Vraj Solanki almost 8 years@PadraicCunningham What does it mean when I get the CalledProcessError and how do it fix it to get the process Id. I am trying to make the script and run in OpenWRT.
-
Rajan Ponnappan about 7 yearsIn this case, since we aren't going anything useful in try/catch, we can also use
subprocess.call
rather thansubprocess.check_output
with try/catch block. -
Alejandro Blasco about 7 years@RajanPonnappan With
subprocess.call
you only gets the return code ($?), howeversubprocess.check_output
returns what you really want: the command output (in this case, the list of PIDs) -
Rajan Ponnappan about 7 yearsYou are right. I got confused between the behavior of
check_call
andcheck_output
. -
Dennis Golomazov almost 7 yearsGreat answer! I've written a complete example based on it here: stackoverflow.com/a/44712205/304209
-
Voldemort's Wrath almost 5 years@AvinashRaj Since the poster of this answer has not been active, I turn to you. When I use the first snippet of code, it throws a
FileNotFoundError
. Why is this? -
Admin over 4 yearsOn Solaris family /proc is binary, not textual.
-
Brian Hannay about 3 years@Voldemort'sWrath if you run the snippet on a device without a pidof command such as Windows, the command will not be found. This could be one reason.