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

Karthik Gurusamy kar1107 at gmail.com
Tue Sep 4 19:05:38 EDT 2007


On Sep 2, 12:26 pm, herman <Herman.Schu... at gmail.com> wrote:
> Hi,
>
> 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?
>

Try commands module; it's simple to just get the output. subprocess
module is a newer way to doing things. But commands.getoutput() is lot
simpler for simple shell like tasks.

>>> import commands
>>> commands.getoutput("ps -ef | grep emacs | awk '{print $2}'")
'21739\n15937\n15287\n5097\n14797\n31777\n8779\n2973\n5413\n13024\n13026'
>>>

Your script can then use the output as its input.

Karthik

> Thank you.





More information about the Python-list mailing list