Categories
environment-variables python

How do I access environment variables in Python?

2826

How do I get the value of an environment variable in Python?

0

    4101

    Environment variables are accessed through os.environ:

    import os
    print(os.environ['HOME'])
    

    To see a list of all environment variables:

    print(os.environ)
    

    If a key is not present, attempting to access it will raise a KeyError. To avoid this:

    # Returns `None` if key doesn't exist
    print(os.environ.get('KEY_THAT_MIGHT_EXIST'))
    
    # Returns `default_value` if key doesn't exist
    print(os.environ.get('KEY_THAT_MIGHT_EXIST', default_value))
    
    # Returns `default_value` if key doesn't exist
    print(os.getenv('KEY_THAT_MIGHT_EXIST', default_value))
    

    11

    • 1

      hello rod, thanks for your effective reply concerning ‘default-installation’; effective in point of view to understand it quickly rather than go through the links. That’s really I appreciated 🙂 but about my (1) question please look at the command and outputs snippet below: >>> import os >>> print os.environ[‘PYTHONPATH’] Traceback (most recent call last): File “<console>”, line 1, in <module> File “C:\Python25\lib\os.py”, line 435, in getitem return self.data[key.upper()] KeyError: ‘PYTHONPATH’ >>> print os.environ.get(‘PYTHONPATH’) None >>> // PLZ to be continue…//

      Feb 5, 2011 at 14:47


    • In a 1st way script is throwing Exception whereas with 2nd one giving None. So, is there any way to get it meaningful value or am I doing in a wrong way??? Amit.

      Feb 5, 2011 at 14:49

    • 9

      os.environ is a dictionary. Trying to access a key not present in the dictionary will throw a KeyError. The get method simply returns None when the key does not exists. Do you have PYTHONPATH set? Can you try with a variable such as PATH, that is guaranteed to exist? Does it return a meaningful value?

      – Rod

      Feb 5, 2011 at 19:21

    • 2

      PYTHONPATH is used to add new search path to Python (sys.path) from outside Python. Have a look at docs.python.org/using/cmdline.html#environment-variables

      – Rod

      Feb 7, 2011 at 14:41

    • 33

      .get() can also be given a default.

      Sep 21, 2018 at 15:25

    319

    To check if the key exists (returns True or False)

    'HOME' in os.environ
    

    You can also use get() when printing the key; useful if you want to use a default.

    print(os.environ.get('HOME', '/home/username/'))
    

    where /home/username/ is the default

    3

    • 4

      Which is better, "HOME" in os.environ or os.environ.get('HOME')?

      – endolith

      Feb 3, 2017 at 16:11

    • 15

      @endolith They do different things. The first returns True or False, while the second returns a value, possibly None.

      – Trenton

      Feb 13, 2018 at 22:38

    • 4

      @endolith, the correct question woud be "HOME" in os.environ vs os.environ.get('HOME') is None. As you can see first is far more readable & comfortable to work with.

      Oct 16, 2019 at 13:43

    74

    Here’s how to check if $FOO is set:

    try:  
       os.environ["FOO"]
    except KeyError: 
       print "Please set the environment variable FOO"
       sys.exit(1)
    

    3

    • 5

      Try can be faster. The case of env vars is likely best for ‘try’: stackoverflow.com/a/1835844/187769

      Feb 5, 2017 at 16:49

    • 24

      @RandomInsano faster =/= better. This code looks less readable than an "if 'FOO' not in os.environ: ..." block

      Oct 13, 2017 at 13:27

    • If you just setup the variable you need to close the Terminal before you can test it.

      – Shane S

      Jun 16 at 5:21