In this article we will explore how to work with environment variables in Python.
Table of Contents
- Introduction
- How to get environment variables using Python
- How to set environment variables using Python
- Conclusion
Introduction
Environment variables are variables stored outside the program (at operating system level) that can affect how the program runs and help store sensitive information.
For example, your program might be using some API which has a secret key. This secret key should be stored as an environment variable outside the code you are running.
But why would we do that?
Using environment variables has two main advantages:
- Improved sensitive data security – when you have multiples developers working on one code base, you might want to keep your secret keys outside of the code base for improved security practices. Or if you are sharing your source code for a program on GitHub, you want to keep your secret API key private and not accessible to everyone who downloads the code.
- Automation – keeping secrets stored in environment variables helps you stay away from manually updating code base when, for example, you are running the same code on someone else’s machine. So instead of changing your source code based on a different “user” running the code, you could automatically update it using environment variables.
Next, let’s explore how to work with environment variables in Python!
In this tutorial we will work with the os module that provides a portable way of using operating system dependent functionality, which is built-in in Python, so there is nothing additional to install.
How to get environment variables using Python
In Python, environment variables are implemented though the os module and can be retrieved using os.environ which provides a mapping of key-value pairs that represent the process environment.
To get all environment variables using Python, simply run:
#Import the required dependency
import os
#Get all environment variables
env_vars = os.environ
#Print environment variables
for key, value in dict(env_vars).items():
print(f'{key} : {value}')
and you should get a complete mapping of your environment variables printed out:
TERM_PROGRAM : vscode
SHELL : /bin/bash
TERM_PROGRAM_VERSION : 1.72.2
ORIGINAL_XDG_CURRENT_DESKTOP : undefined
USER : datas
PATH : /Library/Frameworks/Python.framework/Versions/3.7
__CFBundleIdentifier : com.microsoft.VSCode
LANG : en_US.UTF-8
HOME : /Users/datas
COLORTERM : truecolor
_ : /usr/local/bin/python3
__PYVENV_LAUNCHER__ : /usr/local/bin/python3
In order to get the value for a specific environment variable, we will use os.environ.get(). It will retrieve the value of the environment variable specified.
For example, I would like to retrieve the USER environment variable:
#Import the required dependency
import os
#Get specific environment variable
user_var = os.environ.get('USER')
#Print environment variables
print(user_var)
and you should get a specific user variable set on your system printed out.
In my case it’s:
datas
If you are going to look up an environment variable where there will be no matching for the key, the code should simply return ‘None’.
Let’s try to look up some environment variable that doesn’t exist, like ‘TEST_PASSWORD’:
#Import the required dependency
import os
#Get specific environment variable
pwd_var = os.environ.get('TEST_PASSWORD')
#Print environment variables
print(pwd_var)
and you should get:
None
How to set environment variables using Python
In Python, environment variables are implemented though the os module and can be set using os.environ which is the same as inserting a key-value pair into a dictionary.
Both the environment variable key and value must be in a string format.
In the previous section we tried retrieving a non-existent environment variable ‘TEST_PASSWORD’, and the code returned ‘None’.
Let’s now set this environment variable with a custom value and print it out:
#Import the required dependency
import os
#Set specific environment variable
os.environ['TEST_PASSWORD'] = '12345'
#Get specific environment variable
pwd_var = os.environ.get('TEST_PASSWORD')
#Print environment variables
print(pwd_var)
and you should get:
12345
Note: the changes to environment variables (in our case the added environment variable) are only valid for this one session while running the code. It will not affect the system environment variables or environment variables in other sessions.
Conclusion
In this article we explored how to work with environment variables in Python.
We focused on how to get existing environment variables using Python, as well as how to set environment variables for a session in Python.
Feel free to leave comments below if you have any questions or have suggestions for some edits and check out more of my Python Programming tutorials.