Changing environment variables into python variables

M.-A. Lemburg mal at lemburg.com
Fri Jun 4 05:18:32 EDT 1999


sragsdale at my-deja.com wrote:
> 
> I'm writing a script that needs to import environment variables into
> python as standard variables.  I.E. if the environment variable USER is
> set to 'soren', after my program starts up and does its thing I want
> there to be a variable named USER with a value of 'soren'.
>
> When I try to write this in python, I have this error:
> 
> -------------------------------
> import posix

You should import os, not posix...

> for var in posix.environ.keys():
>     command = var+" = \""+posix.environ[var]+"\""
>     print command
>     eval(command)

This is dangerous, as someone may easily stick some Python code
into your environ, e.g. WIPEOUT="+os.system('rm -rf /')+".

Better do something like this:

import os
namespace = locals()
for key,value in os.environ.items():
	namespace[key] = value

-- 
Marc-Andre Lemburg
______________________________________________________________________
Y2000:                                                   210 days left
Business:                                      http://www.lemburg.com/
Python Pages:                           http://www.lemburg.com/python/





More information about the Python-list mailing list