How can I access environment variables in Python?

To access environment variables in Python, use the os module, which provides several methods to interact with the system environment. Here’s a detailed guide:

1. Access Environment Variables

Method 1: os.environ (Dictionary-like Object)

Access variables directly using dictionary syntax. Raises KeyError if the variable is not found.

import os

# Get the value of 'HOME' (Unix) or 'USERPROFILE' (Windows)
home_dir = os.environ['HOME']         # Unix/Mac
user_profile = os.environ['USERPROFILE']  # Windows

Method 2: os.environ.get() (Safe Access with Default)

Returns None or a default value if the variable is missing.

api_key = os.environ.get('API_KEY')  # Returns None if not set
debug_mode = os.environ.get('DEBUG', 'False')  # Default: 'False'

Method 3: os.getenv() (Alias for os.environ.get)

Same as get(), but slightly more readable.

db_host = os.getenv('DB_HOST', 'localhost')  # Default: 'localhost'

2. Check if a Variable Exists

Use the in operator to verify existence:

if 'PATH' in os.environ:
    print("PATH exists:", os.environ['PATH'])

3. Case Sensitivity

  • Unix/Mac: Environment variables are case-sensitive (PATHPath).
  • Windows: Variables are case-insensitive, but Python treats them as case-sensitive. Use the exact case stored in the system (e.g., Path on Windows).

4. Handling Errors

Use try-except to catch missing variables:

try:
    secret = os.environ['SECRET_KEY']
except KeyError:
    print("SECRET_KEY not set!")
    secret = None

5. List All Environment Variables

Iterate through all variables:

for key, value in os.environ.items():
    print(f"{key}: {value}")

Example Workflow

import os

# Safely retrieve an API key
api_key = os.getenv('API_KEY')

if not api_key:
    raise ValueError("API_KEY environment variable is missing!")

# Use the API key
print("API Key:", api_key)

Notes

  • Security: Avoid hardcoding secrets in code. Use environment variables for sensitive data.
  • .env Files: For local development, use python-dotenv to load variables from a .env file:
  from dotenv import load_dotenv
  load_dotenv()  # Loads variables from .env

Summary

MethodBehaviorUse Case
os.environ['VAR']Direct access (raises KeyError if missing)When the variable must exist
os.environ.get('VAR')Safe access with None defaultOptional variables
os.getenv('VAR')Same as get()Readability

By using these methods, you can securely and flexibly manage environment variables in Python.

Leave a Reply

Your email address will not be published. Required fields are marked *