Setting an environment variable.

Nobody nobody at
Tue Jan 3 15:29:29 EST 2012

On Tue, 03 Jan 2012 15:45:20 +1000, Ashton Fagg wrote:

> I'm working with an embedded machine, which is using a Python script to 
> oversee the acquisition of some data. The supervisor script, which is 
> run by crontab every 5 minutes, relies on an environment variable to be 
> set. I've tried to set the environment variable inside crontab, however 
> this doesn't work when the script runs.


> Is there a nice way to do this inside the supervisor script itself? 
> Would an os.system("export foo=/bar/foo/bar") at the very beginning of 
> the script do what I want?

No. It would set the variable only for the child process created by
os.system(), which would be pointless.

To set an environment variable for the current process (and, by default,
any child processes), modify os.environ, e.g.:

	os.environ['foo'] = '/bar/foo/bar'

You can set environment variables for specific child processes created via
subprocess.Popen() using the env= parameter, e.g.:

	env = os.environ.copy()
	env['foo'] = '/bar/foo/bar'
	p = subprocess.Popen(..., env=env)

If env= isn't used, the child will inherit the parent's environment.

More information about the Python-list mailing list