Python Environmental Variables

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.

import os

# First print the value associated with the USER
# environmental variable
print('setenv...', end=' ')

# 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

# Repeat
os.environ['USER'] = 'Arthur'

# 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

import os

# 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 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 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... stonesoup
('Hello, ', 'Brian')
('Hello, ', 'Arthur')
?Bob Belcher
('Hello, ', 'Bob Belcher')