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
by chrome
.
you can also use
pgrep
, inprgep
you can also give pattern for matchyou can also use
awk
with ps like thisTo improve the Padraic's answer: when
check_output
returns a non-zero code, it raises a CalledProcessError. This happens when the process does not exists or is not running.What I would do to catch this exception is:
The output:
You can get the pid of processes by name using
pidof
through subprocess.check_output: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:
In [21]: get_pid("chrome")
Or pas the
-s
flag to get a single pid:Complete example based on the excellent @Hackaholic's answer:
For posix (Linux, BSD, etc... only need /proc directory to be mounted) it's easier to work with os files in /proc. Its 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 custom exception.)
Sample Output (it works like pgrep):