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.
1 2 3 4 5 |
import os # current environment variables print(os.environ) |
Output:
1 2 3 4 |
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'}) <img class="alignnone wp-image-22491 size-full" src="http://all-learning.com/wp-content/uploads/2019/01/Python-Set-Environment-Variable.png" alt="Python Set Environment Variable" width="1200" height="628" /> |
Python Current Environment Variable
Check if environment variable exists or not?
We can check if environment variable exists or not using in
statement.
1 2 3 4 5 6 |
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:
1 2 3 |
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.
1 2 3 |
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.
1 2 3 4 5 6 7 8 9 10 11 |
>>> 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.
1 2 3 |
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.
1 2 3 4 5 6 7 8 9 |
>>> 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
.
1 2 3 4 |
>>> print(os.environ.get('DATA')) None |
We can also specify a default value to return if the environment variable is not present.
1 2 3 4 |
>>> print(os.environ.get('DATA', 'TXT')) TXT |
Reference: os.environ