N
N
nano_e_t_42015-12-20 18:36:38
Python
nano_e_t_4, 2015-12-20 18:36:38

How to correctly get the PID of a process in a script?

Hello everyone
Guys, tell me, please, how to do it right:
There is a task of monitoring the process. (the script is written in python> 2.7, the "full process name" is given as input to the script - that is, for example, if it is a terminator, then "/usr/share/terminator/terminator"
I looked, thought, read and found the following implementation options:
Option #1:
Loop through the directory /proc/{pid}/cmdline and look for the right line there.In the end we have a PID
Option #2:
Do something like ps aux | grep process_name in a Python script.Get the PID of the process
Question: How to do it right?All the same, the first option is implemented through native functions, but it is time-consuming and resource-intensive.(All the same, bypassing all /proc/ directories)
The second option, fast but not native, and now I don’t know. Or maybe there are other implementation options?
Thanks

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
nirvimel, 2015-12-20
@nano_e_t_4

from subprocess import check_output
def get_pid(name):
    return map(int, check_output(["pidof", name]).split())

Returns a list of pids matching the given name.

Y
Yuriy Ivanov @Yuriy, 2015-12-20
Ivanov

pidof processname

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question