How to Read Environment Variables in Python
Python’s os
module provides simple access to environment variables, which is essential for 12-factor app configuration and secrets management. Environment variables are the standard way to configure applications without hardcoding sensitive data.
Basic usage:
import os
# Get environment variable with default
database_url = os.getenv('DATABASE_URL', 'sqlite:///default.db')
api_key = os.getenv('API_KEY')
if api_key:
print("API key found")
else:
print("Warning: API_KEY not set")
Reading with error handling:
import os
try:
required_config = os.environ['REQUIRED_CONFIG']
print(f"Config: {required_config}")
except KeyError:
print("Error: REQUIRED_CONFIG environment variable not set")
exit(1)
Reading multiple variables:
import os
config = {
'debug': os.getenv('DEBUG', 'False').lower() == 'true',
'port': int(os.getenv('PORT', '8000')),
'database_url': os.getenv('DATABASE_URL', 'sqlite:///app.db'),
'secret_key': os.environ.get('SECRET_KEY')
}
print(f"Running on port {config['port']}")