Setting Environment Variables

Peter Hansen peter at engcorp.com
Wed Oct 20 18:06:40 EDT 2004


Greg Lindstrom wrote:
> I am running python 2.3. on an HP-9000 box running Unix and have a POSIX
> script that sets up my production environment.  I would like to run the
> script from inside a python routine and pick up the environment variables
> but am having trouble getting it done.  Suppose the script is called
> setprod.  How can I call this from inside a python script then pick up the
> env's later in my program?  I've tried os.system ('setprod') and
> os.system('. setprod'), but neither seemed to work.

I'm not sure of the solution (there are several alternatives)
but the problem is that os.system() creates a new shell (or
subshell, if you will) that is exited when the script completes.
Obviously that means any changes made to the subshell's environment
will not appear in the environment of the process running the
Python script.

The answer depends on what you are trying to accomplish.  Do
you need the environment variables to be used only in the Python
script, or are you trying to affect the environment even after
the Python script has completed?

(When people try to do this, it's sort of like trying to affect
the variables in the calling routine from inside a subroutine.
Although that's not usually a good idea, there are (ugly) ways
to work around the roadblocks, such as global variables...
in such a case, and perhaps yours, there may be other ways of
looking at the problem that can inspire more elegant solutions.)

-Peter



More information about the Python-list mailing list