Main Tutorials

How to get an environment variable in Python

In this article, we will show you how to access the environment variables in Python.


import os

print(os.environ['HOME'])

print(os.getenv('HOME'))

P.S Tested with Python 3.9.5

1. Get an environment variable

1.1 The below code uses [os.environ(https://docs.python.org/3/library/os.html#os.environ) to print the environment variable HOME.


import os

print(os.environ['HOME']) # /Users/mkyong

1.2 If the requested key does not exist, it raises KeyError(key).


import os

print(os.environ['HOME_NOT_EXISTS'])

Output

Terminal

raise KeyError(key) from None
KeyError: 'PATH_NOT_EXISTS'

1.3 Alternatively, we can use try to handle the non-exists key.


import os, sys

try:  
    # If the requested key does not exist, it raises `KeyError(key)`.
    os.environ['PYTHON_HOME']
except KeyError:
    print('Please define the environment variable PYTHON_HOME')
    sys.exit(1)

If the PYTHON_HOME environment variable does not exist, it will print the below output:

Terminal

  Please define the environment variable PYTHON_HOME

2. Difference between os.environ[], os.getenv() and os.environ.get()

2.1 Below code shows three different ways to print the environment variable HOME.


import os

print(os.environ['HOME'])     # /user/mkyong
print(os.environ.get('HOME')) # /user/mkyong
print(os.getenv('HOME'))      # /user/mkyong

2.2 The main difference between the below three methods:

  • os.environ[] – If the key does not exist, raise exception KeyError, no default value.
  • os.environ.get()– If the key does not exist, it returns None or default value.
  • os.getenv() – If the key does not exist, it returns None or default value. This function is a wrap or shorthand for os.environ.get().

import os

print(os.environ('HOME_KEY_NOT_EXISTS'))                          # raise KeyError

print(os.environ.get('HOME_KEY_NOT_EXISTS'))                      # `None`
print(os.environ.get('HOME_KEY_NOT_EXISTS', '/home/work/python')) # /home/work/python

print(os.getenv('HOME_KEY_NOT_EXISTS'))                           # `None`
print(os.getenv('HOME_KEY_NOT_EXISTS','/home/work/python'))       # /home/work/python

2.3 Review the source code of os.getenv(), it is a wrap of the environ.get function, both os.getenv() and os.environ.get() is the same.

os.py

def getenv(key, default=None):
    """Get an environment variable, return None if it doesn't exist.
    The optional second argument can specify an alternate default.
    key, default and the result are str."""
    return environ.get(key, default)

3.1 The below code print all the environment variables in the current system.


import os

#print everything
for key, value in os.environ.items():
  print('{}: {}'.format(key, value))

Output

Terminal

USER: mkyong
__CFBundleIdentifier: com.microsoft.VSCode
COMMAND_MODE: unix2003
SHELL: /bin/zsh
HOME: /Users/mkyong
TERM: xterm-256color
_: /usr/local/bin/python3

#...

3.2 The below code print all environment variables in alphabetical order.


import os

#print everything in sorted alphabetical order.
for key, value in sorted(os.environ.items()):
  print('{}: {}'.format(key, value))

Output

Terminal

COLORTERM: truecolor
COMMAND_MODE: unix2003
HOME: /Users/mkyong
LANG: en_GB.UTF-8
SHELL: /bin/zsh
SHLVL: 1
_: /usr/local/bin/python3
__CFBundleIdentifier: com.microsoft.VSCode

#...

4. Download Source Code

$ git clone https://github.com/mkyong/python

$ cd os

5. References

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
1 Comment
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Humberto
2 years ago

Nice article