And answered partially by Steve Majewski:
> The environment variables can be read from dictionary posix.environ
> ( or more portably, from os.environ, but if you are going to
> use the values in system and/or popen, the semantics of environment
> variable are probably different anyway, so I'll stick to posix. )
>
> There's no builtin function to return the print string of all
> of the environment variables, but it's easy to write one:
>
> >>> def printenv():
> ... s = ''
> ... for e in os.environ.items():
> ... s = s + e[0] + '=' + repr(e[1]) + ' '
> ... return s
> ...
> >>> os.environ['FRED']='bert'
> >>> os.system( printenv()+';echo $FRED' )
> bert
> 0
> >>> os.popen( printenv()+';echo $FRED', 'r' ).readlines()
> ['bert\012']
> >>>
Steven's hack works, sort of (unless you have a string in your
environment containing a single quote), but is hardly elegant.
Unfortunately, in current Python, fiddling with os.environ doesn't
affect the environment passed to processes created with popen() and
system(). You can use fork() and execve() to start a process passing
it os.environ -- you could even write a popen() clone to do this
automatically.
The reason why os.environ isn't passed by default to popen() and
system() is that different UNIX versions have different interfaces to
set the environment -- sometimes it's called putenv(), sometimes it's
called setenv(), sometimes you have to do it yourself. I suppose I
*could* add it but never thought there would be much use for it, so
I never bothered. If someone contributes a hack, I'd gratefully
accept it. (The hack should probably do an assignment to the C
variable environ on each call to system() or popen() -- the function
to create such a variable already exists since it is also used by
execve()).
--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>
URL: <http://www.cwi.nl/cwi/people/Guido.van.Rossum.html>