Re: Environment Variables

Steven D. Majewski (sdm7g@virginia.edu)
Wed, 27 Apr 1994 14:17:12 -0400 (EDT)

On Wed, 27 Apr 1994 kevanh@lsl.co.uk wrote:
>
> I am current converting one of old perl programs into python and have come
> up against a problem. How do you set environment variables that can be used
> by commands invoked with posix.popen() ?
>
> In perl all I had to do was:
>
> $ENV{"FRED"} = "bert";
> print `printenv FRED`;
>

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']
>>>

repr() is used force all of the dictionary values to be quoted,
whether they need it or not. ( and since the backquote for
Python works differently, you DON'T want to use `printenv()` ! )

- Steve Majewski (804-982-0831) <sdm7g@Virginia.EDU>
- UVA Department of Molecular Physiology and Biological Physics