Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get the process ID of a program in Unix or Linux using Python?

Tags:

python

I'm writing some monitoring scripts in Python and I'm trying to find the cleanest way to get the process ID of any random running program given the name of that program

something like

ps -ef | grep MyProgram 

I could parse the output of that however I thought there might be a better way in python

like image 351
James Avatar asked Sep 21 '10 15:09

James


People also ask

How do I find the process ID of a process in Linux?

The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.

Which is the system call to find the process ID in Unix or Linux?

The pidof command is used to find the process ID of the running program. It prints those IDs into the standard output.

How do I find program process ID?

Task Manager can be opened in a number of ways, but the simplest is to select Ctrl+Alt+Delete, and then select Task Manager. In Windows, first click More details to expand the information displayed. From the Processes tab, select Details to see the process ID listed in the PID column.


2 Answers

From the standard library:

os.getpid() 
like image 147
Derek Swingley Avatar answered Oct 08 '22 00:10

Derek Swingley


If you are not limiting yourself to the standard library, I like psutil for this.

For instance to find all "python" processes:

>>> import psutil >>> [p.info for p in psutil.process_iter(attrs=['pid', 'name']) if 'python' in p.info['name']] [{'name': 'python3', 'pid': 21947},  {'name': 'python', 'pid': 23835}] 
like image 20
Mark Avatar answered Oct 08 '22 01:10

Mark