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.
Table of Contents
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
print(os.environ)
Output:
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': 'com.apple.xpc.launchd.oneshot.0x10000003.pycharm', '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 CE.app/Contents/bin', '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/com.apple.launchd.1o59WVsq9I/Listeners', '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/com.apple.launchd.U1NEZUKVjH/Render', '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
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'])
else:
print('HOME environment variable is not defined.')
Output:
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/os.py", line 683, in __setitem__
value = self.encodevalue(value)
File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/os.py", 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/os.py", 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'))
None
We can also specify a default value to return if the environment variable is not present.
>>> print(os.environ.get('DATA', 'TXT'))
TXT
Reference: os.environ
There is good out of the box Python solution called [pycrosskit][1].
It will create environment variables that are persistent both for Linux and Windows.
Usage:
# Will Set Persistent Value for Variable in System
# * subkey works only for windows like file in folder
# * reg_path works only for windows as register path
SysEnv.set_var(name, value, subkey, reg_path=default_reg_path)
# Will Get Persistent Value for Variable in System
# * reg_path works only for windows as register path
# * delete, deletes key from environment and its subkeys after read
SysEnv.get_var(name, reg_path=default_reg_path, delete=False)
[1]: https://pypi.org/project/pycrosskit/
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.
Ramajayam
Brilliant post sir, thanks a lot