[Tutor] Changing (Unix) environment for python shell/popen() commands

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Sun Jan 23 22:22:02 CET 2005



On Sun, 23 Jan 2005, Scott W wrote:

> I've got to shell out from my python code to execute a command, but
> _must_ set the environment at the same time (or prior to execution).
>
> I saw some comments about setting os.environ[<some shell var>], but
> didn't seem to be seeing this work in subsequent calls using popen2().
>
> Does anyone have a working piece of code setting some env variable
> successfully prior to(or along with) calling popen2() (or friends).

Hi Scott,


Hmm... That should have worked.  We should be able to assign to the
os.environ dictionary: as I understand it, a child process can inherit its
parent's environment.  Let me check this:

###
volado:~ dyoo$ cat print_name_var.py
import os
print "I see", os.environ["NAME"]
volado:~ dyoo$
volado:~ dyoo$
volado:~ dyoo$
volado:~ dyoo$ python print_name_var.py
I see
Traceback (most recent call last):
  File "print_name_var.py", line 2, in ?
    print "I see", os.environ["NAME"]
  File "/sw/lib/python2.3/UserDict.py", line 19, in __getitem__
    def __getitem__(self, key): return self.data[key]
KeyError: 'NAME'
###

Ok, that's expected so far.


Let me see what happens if we try to set to os.environ.

###
volado:~ dyoo$ python
Python 2.3.3 (#1, Aug 26 2004, 23:05:50)
[GCC 3.3 20030304 (Apple Computer, Inc. build 1495)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.environ['name'] = 'Scott'
>>> os.popen('python print_name_var.py').read()
Traceback (most recent call last):
  File "print_name_var.py", line 2, in ?
    print "I see", os.environ["NAME"]
  File "/sw/lib/python2.3/UserDict.py", line 19, in __getitem__
    def __getitem__(self, key): return self.data[key]
KeyError: 'NAME'
'I see\n'
###


On thing we have to be careful of is case-sensitivity: it does matter in
the case of environmental variables.

###
>>> os.environ['NAME'] = 'Scott'
>>> os.popen('python print_name_var.py').read()
'I see Scott\n'
###

And now it works.




> Also, is there any way to get the called programs return code via
> popen() (again, under python 1.5.2)?


Hi Scott,

Yes; although it's a little hard to find it, the Python 1.52 documentation
here:

    http://www.python.org/doc/1.5.2p2/

does have some documentation on popen2:

    http://www.python.org/doc/1.5.2p2/lib/module-popen2.html

You can use a popen2.Popen3 instance, which should give you access to
program return values.


If you have more questions, please feel free to ask.



More information about the Tutor mailing list