Python 3: How to Read Environment Variables
2 min readJan 22, 2023
There are several ways to read environment variables in Python, but some common methods include
- Using the
os.environ
module: This module provides a dictionary-like interface to the environment variables, where the keys are the variable names and the values are the corresponding values. Example:os.environ['MY_VAR']
- Using the
os.getenv()
function: This function allows you to retrieve the value of a specific environment variable. Example:os.getenv('MY_VAR')
- Using the
environ
fromos
fromdotenv
package: This package allows to load of environment variables from a.env
file, which is helpful for development and testing. You can install it via pippip install python-dotenv
, and then you can useos.environ.get
oros.getenv()
function to read the variables from the .env file.
Please note that in order to use the above ways in your python code, you should have the environment variables set in your system before running the code
Here’s an example of using the os.environ
object to read an environment variable in Python:
import os
# Set an environment variable
os.environ['MY_VARIABLE'] = 'my_value'
# Retrieve the value of an environment variable
my_variable = os.environ['MY_VARIABLE']
print(my_variable) # Output: 'my_value'