strange subprocess behavior when calling ps

Roger Davis rbd at
Wed Nov 17 03:33:52 CET 2010

Hi all,

I have encountered a strange problem with some code I am writing to
search the system process list for certain running processes. I am
using subprocess.Popen() to call '/bin/ps -e'. When I save my code to
the file (whose first line is #!/usr/bin/python) and run it
with the command

% ./

it works perfectly fine, retrieving lines from my pipe to the /bin/ps
output which look exactly as if I had typed the command '/bin/ps -e'
myself into a shell window. Here is a sample line from that output:

 1891 ttys000    0:00.12 -tcsh

Now for the weird part -- when I run this code using the command

% python

I get entirely different output. It only prints out a very few
processes instead of the entire table, and each line also has lots of
environment variable values displayed. Here is the line from that
output which corresponds to the line immediately above:

 1891 s000  S+     0:00.12 -tcsh PATH=/usr/bin:/bin:/usr/sbin:/sbin
TMPDIR=/var/folders/3e/3e-TyTQIG-aOa4x37pbTbk++-H6/-Tmp-/ SHELL=/bin/
tcsh HOME=/Users/hmrgsoft USER=hmrgsoft LOGNAME=hmrgsoft DISPLAY=/tmp/
launch-c1YZNr/org.x:0 SSH_AUTH_SOCK=/tmp/launch-AJ9xbl/Listeners

It's like it's calling up an entirely different ps, or passing it
different command arguments. In both cases, however, I am explicitly
calling /bin/ps with the same -e argument, and there appear to be no
other ps commands on my system, neither do I appear to have any ps
builtin command in any shell.

I am running 2.6.6 under MacOS 10.6.4 on a MacBook Pro Intel. I have
appended the code below. I am running both commands directly in a
Terminal window running tcsh.

Can anyone explain this? Thanks!

Roger Davis

##### code follows

import sys
import subprocess

def main():

	psargs= ["/bin/ps", "-e"]
		ps= subprocess.Popen(psargs, stdout=subprocess.PIPE, close_fds=True)
		psout= ps.communicate()[0]
		pslines= psout.splitlines()
		for line in pslines:
			print "%s" % line
	except KeyboardInterrupt:
		print "Keyboard interrupt received -- terminating."
		print "%s: unexpected error in generation of system process list" %


More information about the Python-list mailing list