Python Set Environment Variable

Filed Under: Python

We can set an environment variable in Python using os module. Python os module environ works as a dictionary that holds the environment variables available to the program at that moment.

Note that the environment variables dictionary gets generated when the os module is loaded, so any further change in the environment variables through other ways, such as export via Terminal, will not be reflected.

Print Current Environment Variables

We can print os.environ variable to learn about the existing environment variables that are available to the program.

import os

# current environment variables


environ({'PATH': '/Library/PostgreSQL/10/bin:/Users/pankaj/Downloads/mongodb/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/Users/pankaj/Downloads/apache-maven-3.5.3/bin:/Library/Frameworks/Python.framework/Versions/3.7/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin', 'COMMAND_MODE': 'unix2003', 'MAVEN_OPTS': '-Xmx2048m -XX:MaxPermSize=128m', 'VERSIONER_PYTHON_VERSION': '2.7', 'LOGNAME': 'pankaj', 'XPC_SERVICE_NAME': '', 'PWD': '/Users/pankaj/Documents/github/journaldev/Python-3/basic_examples', 'PYCHARM_HOSTED': '1', 'PYTHONPATH': '/Users/pankaj/Documents/github/journaldev/Python-3', 'SHELL': '/bin/zsh', 'PAGER': 'less', 'LSCOLORS': 'Gxfxcxdxbxegedabagacad', 'PYTHONIOENCODING': 'UTF-8', 'SECURITYSESSIONID': '186a8', 'OLDPWD': '/Applications/PyCharm', 'VERSIONER_PYTHON_PREFER_32_BIT': 'no', 'USER': 'pankaj', 'ZSH': '/Users/pankaj/.oh-my-zsh', 'TMPDIR': '/var/folders/1t/sx2jbcl534z88byy78_36ykr0000gn/T/', 'SSH_AUTH_SOCK': '/private/tmp/', 'XPC_FLAGS': '0x0', 'PYTHONUNBUFFERED': '1', 'M2_HOME': '/Users/pankaj/Downloads/apache-maven-3.5.3', '__CF_USER_TEXT_ENCODING': '0x1F5:0x0:0x0', 'Apple_PubSub_Socket_Render': '/private/tmp/', 'LESS': '-R', 'LC_CTYPE': 'UTF-8', 'HOME': '/Users/pankaj', '__PYVENV_LAUNCHER__': '/Library/Frameworks/Python.framework/Versions/3.7/bin/python3.7'})
Python Current Environment Variable

Python Current Environment Variable

Check if environment variable exists or not?

We can check if environment variable exists or not using in statement.

if 'HOME' in os.environ:
    print('HOME environment variable is already defined. Value =', os.environ['HOME'])
    print('HOME environment variable is not defined.')


HOME environment variable is already defined. Value = /Users/pankaj

Changing the environment variable value can have serious implications for the execution of the program. Hence, it’s advisable to first check if the environment variable exists or not. Then it’s up to you whether you want to modify the value or not. You can always define a new environment variable and use it in your program.

Python set environment variable

We can set an environment variable like we set the values in the dictionary.

os.environ['MYSQL_VERSION'] = '5.7.18'

Note that the environment variable key-value pair must be a string, otherwise an error will be raised.

>>> os.environ['Data'] = 123
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/", line 683, in __setitem__
    value = self.encodevalue(value)
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/", line 753, in encode
    raise TypeError("str expected, not %s" % type(value).__name__)
TypeError: str expected, not int

Python Read Environment Variable

Let’s see how to read the environment variable we have set in the above code snippet.

print('MySQL Version =', os.environ['MYSQL_VERSION'])

Output: MySQL Version = 5.7.18

But is this the correct way to retrieve environment variable value? Let’s see what happens when the environment variable is not present.

>>> print(os.environ['DATA'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/", line 678, in __getitem__
    raise KeyError(key) from None
KeyError: 'DATA'

The better way is to use get() function of environ variable. If the environment variable is not present, then it will return None.

>>> print(os.environ.get('DATA'))

We can also specify a default value to return if the environment variable is not present.

>>> print(os.environ.get('DATA', 'TXT'))
You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: os.environ



    Hello Pankaj,
    I am new to Python and I learn from internet sources.I was using python 3.7.1 version successfully converting the scripts into exe using pyinstaller.Suddenly, I find exe files fail to execute the scripts.I want to know what should the environment path variables for the user and system.i hope you will help.

  2. Ankit Chanpuria says:

    Brilliant post sir, thanks a lot

Leave a Reply

Your email address will not be published. Required fields are marked *

Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages