System‎ > ‎

Environment

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
'/home/myusername'

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


# set HOME directory
os.environ['HOME']='/home/user/my/new/home/directory/'



# add new directory to system PATH
newpath='/home/username/tools'

# 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
print(os.environ['PATH'])




see also
get current working director and other file commands