Python Topics : Running a Script with Environment Variables
What Are Environment Variables?
environment variables are dynamic values
used to store configuration settings

API keys and secrets sensitive data needed to interact with external services
database connection strings information required to connect to databases
configuration settings various settings
environment-specific values values that differ between development, testing, and production environments
Why Use Environment Variables?
Security store sensitive information in environment variables
keeps them out of the source code
reduces the risk of exposing sensitive data when sharing or committing code
Flexibility environment variables allow easy switching between configurations
no need to modify code
useful when deploying the application across multiple environments (e.g., development, staging, and production)
Configuration Management use environment variables to centralize configuration management
manage settings externally
makes it easier to update and maintain configurations
Consistency environment variables provide a consistent way to manage settings across different platforms and deployment environments
ensures application behaves as expected regardless of where it is run
Setting Environment Variables
set environment variables in the shell before running script
in Unix-based system
export DATABASE_URL="postgres://user:password@localhost/dbname"
export SECRET_KEY="supersecretkey"
export API_KEY="your_api_key"
in Windows
set DATABASE_URL="postgres://user:password@localhost/dbname"
set SECRET_KEY="supersecretkey"
set API_KEY="your_api_key"
when the script runs it has access to the environment variables
Example Python Script
import os

def main() -> None:
    database_url = os.getenv('DATABASE_URL')
    secret_key = os.getenv('SECRET_KEY')
    api_key = os.getenv('API_KEY')

    if not all([database_url, secret_key, api_key]):
        raise ValueError("Missing one or more environment variables: DATABASE_URL, SECRET_KEY, API_KEY")

    print(f"Connecting to database at {database_url}")
    print(f"Using secret key: {secret_key}")
    print(f"API key: {api_key}")
    # Add application logic here

if __name__ == "__main__":
    main()
Using a .env File with python-dotenv
use use a .env file with python-dotenv to manage environment variables
stores environment variables in a file and load them into the app
create a .env file in project's root of directory
DATABASE_URL=postgres://user:password@localhost/dbname
SECRET_KEY=supersecretkey
API_KEY=your_api_key
load environment variables in main.py
modify script to use python-dotenv to load the environment variables from the .env file
import os
from dotenv import load_dotenv

def main():
    # Load environment variables from .env file
    load_dotenv()

    database_url = os.getenv('DATABASE_URL')
    secret_key = os.getenv('SECRET_KEY')
    api_key = os.getenv('API_KEY')

    if not all([database_url, secret_key, api_key]):
        raise ValueError("Missing one or more environment variables: DATABASE_URL, SECRET_KEY, API_KEY")

    print(f"Connecting to database at {database_url}")
    print(f"Using secret key: {secret_key}")
    print(f"API key: {api_key}")
    # Add your application logic here

if __name__ == "__main__":
    main()
Best Practices
do not write secrets in the code it will end up being as public in the code
can result in leaks
Do not commit the .env file to version control add .env to your .gitignore file
ensure file is not included in version control system
duse separate .env files for different environments use separate .env files for different environments
for example : .env.development, .env.testing, and .env.production
load the appropriate file based on the environment
index