strange subprocess behavior when calling ps

Ned Deily nad at acm.org
Tue Nov 16 23:18:02 EST 2010


In article 
<55f26d5c-aba9-4892-9e2c-1caa9988e7fe at v23g2000vbi.googlegroups.com>,
 Roger Davis <rbd at hawaii.edu> wrote:
> 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 pid.py (whose first line is #!/usr/bin/python) and run it
> with the command
> 
> % ./pid.py
> 
> 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 pid.py
> 
> 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
> Apple_PubSub_Socket_Render=/tmp/launch-BsRx5Y/Render
> COMMAND_MODE=unix2003 __CF_USER_TEXT_ENCODING=0x532:0:0
> TERM_PROGRAM=Apple_Terminal TERM_PROGRAM_VERSION=273 LANG=en_US.UTF-8
> TERM=xterm-color
> 
> 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.

See "man compat".  What you are seeing is the difference between ps(1) 
output in "legacy" mode, attempting to duplicate the old, non-POSIX 
behavior from 10.3 days, or "unix2003" mode.  Terminal login sessions 
are normally automatically started with the COMMAND_MODE environment 
variable set:

$ echo $COMMAND_MODE 
unix2003

Adding an "env={"COMMAND_MODE": "unix2003"}" argument to your subprocess 
Popen call should do the trick.

-- 
 Ned Deily,
 nad at acm.org




More information about the Python-list mailing list