Re: Another request for comments on beginner code

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Sun, 6 Mar 1994 00:18:42 -0500

Trying out the initial version posted, the first field sometimes
contained the initial digit of the next field ( PID, I think ).

I don't know if the output of ps is standardized with respect to
the exact column format of the output ( in which case that was
probably a fencepost error ) or if that was due to variance in
ps output on different systems ( or maybe on variance in how
high their PID's go on a particular day. )

In any event, I tried using string.split to separate the fields
and string.[rl]just to align the output. This, however produces
the wrong output on <defunct> processes, which don't have the
middle fields. One could add a check that len(field) > some_number,
but ... well, I expect the answer above was probably that the code
was off by one, and correcting that is a better fix that using
split().

Other than that, my version was pretty much like Tim's.
I bundled it up into a function, and added the feature
to make the host name optional. If no host-name, then
the command pipe is local.

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics

#!/usr/local/bin/python

from os import popen
from string import split, rjust, ljust

def ps( *host ):
cmd = 'ps uax | grep -v root'
if host and host[0] :
cmd = 'rsh ' + host[0] + ' ' + cmd
for line in popen( cmd, 'r' ).readlines():
field = split( line )
print ljust(field[0],10), rjust(field[2],5), rjust(field[3],5),' ',field[-1]

if __name__ == '__main__' :
import sys
if sys.argv[1:] and sys.argv[1]:
ps( sys.argv[1] )
else: ps( )