how can I find out the process ids with a process name

Michael Bentley michael at jedimindworks.com
Sun Sep 2 16:25:06 EDT 2007


On Sep 2, 2007, at 12:26 PM, herman wrote:

> I would like to find out all the process id with the process name
> 'emacs'.
>
> In the shell, i can do this:
>
> $ ps -ef |grep emacs
> root     20731  8690  0 12:37 pts/2    00:00:09 emacs-snapshot-gtk
> root  25649 25357  0 13:55 pts/9    00:00:05 emacs-snapshot-gtk rtp.c
> root  26319 23926  0 14:06 pts/7    00:00:04 emacs-snapshot-gtk
> stressTestVideo.py
> root  26985     1  0 14:15 ?        00:00:01 /usr/bin/emacs-snapshot-
> gtk
> root     27472 21066  0 14:23 pts/5    00:00:00 grep emacs
>
>
> and I can see the process id is 20731, 25649, etc, etc.
>
> But now I would like to do the programmically in my python script.
> I know I can use ' os.system(cmd)' to execute the command 'ps -ef |
> grep emacs', but how
> can I pipe the output of my 'ps -ef | grep emacs' to my python script
> and then run a regression expression with it to get the process Ids?

Are you targeting Linux?  If so, have a look at the /proc system.   
Each process has a directory, and the 'status' file in each process'  
directory tells many things, including process name (the line that  
ends with the process name, begins with 'Name').

Here's a quick bashy way to get pid + process names:

cd /proc
for i in ls [0-9]*/status
do
     echo $i `grep '^Name' $i | cut -f2` | sed 's/\/status//g'
done


hth,
Michael
---
"If we had asked people what they wanted they would have said 'a  
faster horse'."  --Henry Ford





More information about the Python-list mailing list