How to get PID by process name?
You can get the pid of processes by name using pidof
through subprocess.check_output:
from subprocess import check_outputdef 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_outputdef 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
You can use psutil
package:
Install
pip install psutil
Usage:
import psutilprocess_name = "chrome"pid = Nonefor proc in psutil.process_iter(): if process_name in proc.name(): pid = proc.pid
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 pythonimport osimport sysfor 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 bash1487 : -bash 1779 : /bin/bash