Setup / Read Environment Variables

Possible duplicate:
How to set environment variables in Python

My python script that calls many python functions and shell scripts. I want to set an environment variable in Python (the main function of the call) and all child processes, including shell scripts, to see a set of environment variables.

I need to set some environment variables as follows:

DEBUSSY 1 FSDB 1 

1 is a number, not a string. Also, how can I read the value stored in the environment variable? (Like DEBUSSY / FSDB in another child python script.)

+78
python environment-variables
May 11 '11 at 23:16
source share
4 answers

Try using the os module.

 import os os.environ['DEBUSSY'] = '1' os.environ['FSDB'] = '1' # Open child processes via os.system(), popen() or fork() and execv() someVariable = int(os.environ['DEBUSSY']) 

See Python Docs at os.environ . Also, for spawning child processes, see the Python docs subprocess .

+172
May 11 '11 at 23:25
source share

First things first :). Reading books is an excellent approach to solving problems; this is the difference between assistance fixes and long-term problem solving investments. Never miss an opportunity to learn .: D

You can interpret 1 as a number, but environment variables do not care. They just pass the lines:

  The argument envp is an array of character pointers to null- terminated strings. These strings shall constitute the environment for the new process image. The envp array is terminated by a null pointer. 

(From environ(3posix) .)

You use environment variables in python using an os.environ dictionary-like object :

 >>> import os >>> os.environ["HOME"] '/home/sarnold' >>> os.environ["PATH"] '/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games' >>> os.environ["PATH"] = os.environ["PATH"] + ":/silly/" >>> os.environ["PATH"] '/home/sarnold/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/silly/' 
+29
May 11 '11 at 23:26
source share

If you want to pass global variables to new scripts, you can create a python file designed only to store global variables (e.g. globals.py). When you import this file at the top of the script child, it must have access to all of these variables.

If you write these variables, then this is a completely different story. This is due to concurrency and blocking variables that I am not going to enter with if you do not want to.

+3
May 11 '11 at 23:26
source share

Use os.environ[str(DEBUSSY)] to read and write ( http://docs.python.org/library/os.html#os.environ ).

As for reading, you should, of course, independently parse the number from the string.

+1
May 11 '11 at 23:25
source share



All Articles