Every operating system allows system adminstrators and users to set and use environmental variables. Such variables can be highly useful when writing shell scripts that automate commands and executes tasks on the system. It’s highly feasible to imagine situations where build toolchains may need to know about the location of programs such as compilers, linkers, etc.
Python’s os module has an environ object. It acts like a dictionary and allows scripts to read and write to enviornmental variables. Here are two example scripts found in Programming Python: Powerful Object-Oriented Programming that demonstrate using environmental varaibles in Python. I added comments to help explain the programs.
setenv.py
import os # First print the value associated with the USER # environmental variable print('setenv...', end=' ') print(os.environ['USER']) # Now overwrite the value stored in USER. It will # propagate through the system os.environ['USER'] = 'Brian' # Run the echoenv script to prove the environmental # variable has been updated os.system('python echoenv.py') # Repeat os.environ['USER'] = 'Arthur' os.system('python echoenv.py') # This time, we ask the user for a name os.environ['USER'] = input('?') # Now we are going to run the echoevn script, but connect # it's output to this process and print print(os.popen('python echoenv.py').read())
echoenv.py
import os print('echoenv...') # Just print the value for USER found in os.environ print('Hello, ', os.environ['USER'])
Detailed Explanation
Although the main purpose of this script is to demonstrate how to use environmental variables in Python. However, we are going to use the os.system and os.popopen functions to execute our helper echoenv script to help prove that changes to the environmental variables propogate throughout the system.
Line 6 is the first call to os.environ. We look up the USER value in this environ object which prints out the current user to the console. On line 10, we overwrite the value in USER with “Brian”. Now Brian is the user. Line 14 proves the change by calling os.system and executing echoenv.py. That script will print “Brain” in the console.
Lines 17 and 18 are a repeat of lines 10 and 14. Line 21 is only different in the sense that we ask the user for a value this time. Line 25 uses the os.popopen command to execute echoenv.py. This function returns an object that gives us a handle into the sister process. Rather than having echoenv print to the console directly this time, we use the read() method to print the output in the setenv process.
Example Output
Here is the output when run on my machine.
Patricks-MacBook-Pro:Environment stonesoup$ python setenv.py setenv... stonesoup echoenv... ('Hello, ', 'Brian') echoenv... ('Hello, ', 'Arthur') ?Bob Belcher echoenv... ('Hello, ', 'Bob Belcher')
that post was really nice !
LikeLiked by 1 person