System‎ > ‎


How to get and set environment variables in Python?

import os

# get HOME directory

os.environ.get('HOME') # returns None if variable does not exist

os.getenv('TOOLS', os.getcwd() )  # returns second alternative value (working directory), if variable 'TOOLS' does not exist

# set HOME directory

# add new directory to system PATH

# append to PATH
os.environ['PATH'] += os.pathsep + newpath

# or, set new path in beginning of PATH
os.environ['PATH'] = newpath + os.pathsep + os.environ['PATH']

# or, using: os.pathsep.join( [list, of, multiple, paths] )
os.environ['PATH'] = os.pathsep.join( [ newpath, os.environ['PATH'] ] )

# check: print PATH environment variable

see also
get current working director and other file commands