Programmatic Parsing of ps

O

octopusgrabbus

I have Python 2.6.6. I would like to get this output

ps -ef | grep 'fglgo csm'

into a list. What is the best way to do that? I've been reading the
documentation, and am lost.

Thank you.
cmn
 
E

Emile van Sebille

On 2/9/2011 10:58 AM octopusgrabbus said...
I have Python 2.6.6. I would like to get this output

ps -ef | grep 'fglgo csm'

into a list. What is the best way to do that? I've been reading the
documentation, and am lost.

Thank you.
cmn

commands.getoutput

Emile
 
D

Dan Stromberg

On 2/9/2011 10:58 AM octopusgrabbus said...

commands.getoutput

Emile

Also, consider using "ps -eo pid,comm" (or similar) instead of ps -ef
- it should be easier to parse that way.
 
B

bsergean

If you're on Linux you should

* Have a look at the /proc/ filesystem, there's probably what you want
there.

Here's a small script that print all the pid/cmd from the process ran
with your user.

#!/usr/local/bin/python

import os
import re
import stat
from os.path import join

for pid in (pid for pid in os.listdir('/proc') if re.match('\d',
pid)):
cmdline_fn = join('/proc', pid, 'cmdline')
cmdline = open(cmdline_fn).read()
uid = os.stat(cmdline_fn)[stat.ST_UID]

if os.getuid() == uid:
print pid, cmdline


For a more cross-platform solution there's a module that does that (I
forgot it's name but with some googling you might find it)
 
D

Dan Stromberg

FWIW, Linux' /proc is very different from pretty much all other *ix's.
I like Linux' design better, but it might be good to put the Linux
/proc assumption in one place, in case you need to port to another *ix
someday.

If you're on Linux you should

* Have a look at the /proc/ filesystem, there's probably what you want
there.

Here's a small script that print all the pid/cmd from the process ran
with your user.

#!/usr/local/bin/python

import os
import re
import stat
from os.path import join

for pid in (pid for pid in os.listdir('/proc') if re.match('\d',
pid)):
   cmdline_fn = join('/proc', pid, 'cmdline')
   cmdline = open(cmdline_fn).read()
   uid = os.stat(cmdline_fn)[stat.ST_UID]

   if os.getuid() == uid:
       print pid, cmdline


For a more cross-platform solution there's a module that does that (I
forgot it's name but with some googling you might find it)




Also, consider using "ps -eo pid,comm" (or similar) instead of ps -ef
- it should be easier to parse that way.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,141
Messages
2,570,817
Members
47,367
Latest member
mahdiharooniir

Latest Threads

Top