Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Access environment variable values in Python
Environment variables in Python are configuration values stored outside the code and are used at runtime by the application. These variables are present in the form of key-value pairs just like dictionaries in Python. These variables can be set, updated, or removed from the configuration file without changing the application code. Python provides many operating system functions to access environment variables without affecting the code of the application. In this article, we will learn the ways in which we can access environment variables in Python.
Using the OS Module
In order to interact with the operating system, Python has an os module with help of which you can interact with the OS as well as access the environment variable. The os.environ dictionary contains all the environment variables in key-value pairs.
We can use the os.environ to access the PATH of the environment variable and also any new environment variable value ?
Example
import os
# Get the value of the PATH environment variable
path = os.environ['PATH']
print("PATH:", path[:50], "...") # Show first 50 chars
# Set a new environment variable
os.environ['MY_VAR'] = 'my value'
# Get the value of the new environment variable
my_var = os.environ['MY_VAR']
print("MY_VAR:", my_var)
PATH: /opt/bin:/usr/local/nvidia/bin:/usr/local/cuda/ ... MY_VAR: my value
Using os.environ.get() to Avoid KeyError
If the environment variable is not found then a KeyError is raised by the code. To avoid such errors we can use os.environ.get() function to access environment variables and avoid KeyErrors if the key is not found ?
import os
# Get the value of a non-existent variable, or return None
my_var = os.environ.get('NON_EXISTENT_VAR')
print("Non-existent var:", my_var)
# Get with default value
my_var_default = os.environ.get('NON_EXISTENT_VAR', 'default value')
print("With default:", my_var_default)
Non-existent var: None With default: default value
Using the Dotenv Module
In the industry, we use different environments while working on development, staging, and production codebase. Each of these environments has separate environment variable files. Dotenv is a third-party library that is used to access environment variables in multiple environments.
Installation
To use dotenv module we have first to install python-dotenv by the following command ?
pip install python-dotenv
After installing the python-dotenv module we have to create a .env file in the root directory of our project and create environment values in it as key-value pairs ?
MY_KEY_VAR=my_value DATABASE_URL=postgresql://localhost:5432/mydb
The MY_KEY_VAR is the key of the env variable and my_value is the value corresponding to it.
Now, we can load the .env file in our Python code wherever required using the dotenv.load_dotenv() function which reads the .env file and loads all environment variables in the os.environ module ?
Example
from dotenv import load_dotenv
import os
# Load the environment variables from the .env file
load_dotenv()
# Get the value of the MY_KEY_VAR environment variable
my_var = os.environ.get('MY_KEY_VAR')
print("From .env file:", my_var)
From .env file: my_value
Using the Argparse Module
The argparse is a standard library in Python that is used to parse command-line arguments. We can pass environment variables as command-line arguments in Python using the argparse library.
Example
import argparse
parser = argparse.ArgumentParser(description='Demo script with environment variables')
parser.add_argument('--my-var', help='Value for MY_VAR environment variable')
parser.add_argument('--debug', action='store_true', help='Enable debug mode')
# For demo purposes, simulate command line args
import sys
sys.argv = ['script.py', '--my-var', 'command line value', '--debug']
args = parser.parse_args()
print("my_var:", args.my_var)
print("debug:", args.debug)
my_var: command line value debug: True
When running the file from command line, you would use ?
python script.py --my-var "my value" --debug
Using the ConfigParser Module
The ConfigParser is a Python library which is used to read configuration files in Python applications. This approach is useful when you have multiple environments with different configurations.
Creating Configuration File
First, create a config.ini file with different sections for each environment ?
[development] MY_VAR=development value DATABASE_URL=sqlite:///dev.db [production] MY_VAR=production value DATABASE_URL=postgresql://prod-server:5432/app
Example
import configparser
import os
# Get the current environment (default to development)
env = os.getenv('ENVIRONMENT', 'development')
# Read the configuration file
config = configparser.ConfigParser()
config.read('config.ini')
# Get the value of the MY_VAR environment variable for the current environment
my_var = config.get(env, 'MY_VAR')
database_url = config.get(env, 'DATABASE_URL')
print(f"Environment: {env}")
print(f"MY_VAR: {my_var}")
print(f"DATABASE_URL: {database_url}")
Environment: development MY_VAR: development value DATABASE_URL: sqlite:///dev.db
Comparison of Methods
| Method | Best For | Pros | Cons |
|---|---|---|---|
os.environ |
Simple system variables | Built-in, no dependencies | No default values, KeyError risk |
dotenv |
Development workflows | Easy .env files, version control | Requires external library |
argparse |
Command-line tools | Flexible, built-in help | Only for CLI arguments |
ConfigParser |
Multi-environment apps | Structured, environment-specific | More complex setup |
Conclusion
Use os.environ.get() for simple environment variables with default values. For development workflows, python-dotenv provides the cleanest solution. Choose ConfigParser when you need structured multi-environment configurations.
