del on os.environ?

Peter Seibel peter at javamonkey.com
Tue Sep 11 02:13:34 EDT 2001


Hi. I'm having some trouble getting the os.environ variable to do what
I expect. Perhaps I expect the wrong thing. I'm running:

  Python 2.1.1 (#1, Jul 23 2001, 23:16:05) 
  [GCC 2.96 20000731 (Red Hat Linux 7.1 2.96-81)] on linux2
  Type "copyright", "credits" or "license" for more information.
  >>> 

I want to remove a variable from the environment that will be
inherited by children spawned with popen*. But 'del'ing keys from
os.environ doesn't seem to have much effect. Below is a script that
shows what I mean.

Hmmm. After perusing some source it seems that os.py doesn't define
any special behavior for 'del' on it's environ (except in the case
insensitive os's). And I guess there's nothing for it to do unless you
add a non-posix call to unsetenv in posixmodule, which seems sort of
wrong.

Perhaps I should explain what I really am trying to do: I want to
write a Python program that, as portably as possible, runs arbitrary
commands as child processes (think 'make' and you're not too far
off). It seems like I'd want to use the popen family as that allows me
easy access to the input and output streams. Except the only way to
manipulate the environment the children see is by changing
os.environ. I was planning to change it, run popen* and then restore
it. But if I can't unset variables, I have a problem.

And the whole exec*/spawn* suite of functions, seem fraught with non-
or dubious- portability. But maybe I'm just being a chicken.Both exec*
and spawn* are listed as both Unix and Windows; is that really true,
i.e. do they really work the same on both platforms?. And I can't
really use exec* on Windows because fork() isn't supported, right?

Any advice?

-Peter

import os, copy

def showKeyInOsEnviron(key):
    if os.environ.has_key(key):
        print "os.environ['%s'] = %s" % (key, os.environ[key])
    else:
        print "os.environ does not contain key '%s'" % key

def showKeyInSystem(key):
    print 'About to call os.popen("echo $%s"):' % key
    print os.popen("echo $%s" % key).read(),


print "Is FOO in os.environ? Shouldn't be."
showKeyInOsEnviron('FOO')

print "Is FOO in system? Shouldn't be."
showKeyInSystem('FOO')

print "Putting 'FOO' into os.environ."
os.environ['FOO'] = 'bar'

print "Is FOO in os.environ? Should be now."
showKeyInOsEnviron('FOO')

print "Is FOO in system? And here too."
showKeyInSystem('FOO')

print "Taking 'FOO' out of os.environ"
del os.environ['FOO']

print "Is FOO in os.environ? Shouldn't be."
showKeyInOsEnviron('FOO')

print "Is FOO in system? Shouldn't be."
showKeyInSystem('FOO')






More information about the Python-list mailing list