Beginner asks question about Python on Linux

Tim Evans tre17 at student.canterbury.ac.nz
Sat Oct 9 19:00:14 EDT 1999


"Adrian Eyre" <a.eyre at optichrome.com> writes:

> > os.system("ps aux|grep someProcess > pids.temp")
> 
> Try:
> f = os.popen("ps aux|grep " + someProcessStr)
> l = f.readlines()
> f.close()
> 
> --------------------------------------------
> Adrian Eyre <mailto:a.eyre at optichrome.com>
> Optichrome Computer Solutions Ltd
> Maybury Road, Woking, Surrey, GU21 5HX, UK
> Tel: +44 1483 740 233  Fax: +44 1483 760 644
> http://www.optichrome.com 
> --------------------------------------------

The pipe to grep is slightly unnecessary, you could just use python to 
filter the lines.  Try this:

=============== ps.py ===============
#!/usr/bin/python

import os
import string

def pids(program):
    '''Return a list of process ids for all processes that are running
    "program".  Relies on a particular output format for ps a little
    too much.'''

    result = []
    f = os.popen('ps aux', 'r')
    for l in f.readlines():
        fields = string.split(l)
        if fields[10] == program:
            result.append(int(fields[1]))
    return result

if __name__ == '__main__':
    print pids('gnome-terminal')
==============================

$ ./ps.py
[18910, 18925]

--
Tim Evans




More information about the Python-list mailing list