Environment Variables

Windows CMD, PowerShell, .env files, and Python usage

Overview

Environment variables are key–value settings exposed to processes. They can be set per session (current shell), persisted for future sessions, or loaded from a .env file at app startup. Scripts and tools read these to configure tokens, paths, and defaults without hard‑coding.

Windows CMD (session vs persistent)

REM Session-only (current terminal)
set OUTPUT_DIR=C:\Exports
echo %OUTPUT_DIR%

REM Persist for future terminals (User scope)
setx OUTPUT_DIR "C:\Exports"
REM Open a new terminal to see persisted values
echo %OUTPUT_DIR%

PowerShell equivalents

# Session-only
$env:OUTPUT_DIR = "C:\Exports"
echo $env:OUTPUT_DIR

# Persist (User scope)
[System.Environment]::SetEnvironmentVariable("OUTPUT_DIR","C:\Exports","User")

.env files (project-local)

A text file named .env in the project folder. One KEY=VALUE per line.

Do not commit secrets; add .env to .gitignore. Values are strings; quote only if spaces are required.

# .env
OUTPUT_DIR=C:\Exports
API_TOKEN=xxxxxx
DEBUG=true  # comments are allowed via python-dotenv parser

Python usage (os.getenv and python-dotenv)

Precedence: real OS env usually wins unless override=True is passed to load_dotenv.

import os
from dotenv import load_dotenv  # pip install python-dotenv

# Load .env if present (by default, does not override existing env)
load_dotenv(override=False)

out = os.getenv("OUTPUT_DIR", "C:\\Exports")
token = os.getenv("API_TOKEN", "")
print("OUTPUT_DIR:", out)

Using variables in commands

REM CMD example
python process.py --input "C:\Media\in.mp4" --output %OUTPUT_DIR%

# PowerShell example
python process.py --input "C:\Media\in.mp4" --output $env:OUTPUT_DIR

Reading .env in batch and passing to Python

@echo off
setlocal enabledelayedexpansion
set "HERE=%~dp0"

if exist "%HERE%.env" for /F "usebackq tokens=*" %%A in ("%HERE%.env") do set "%%A"

python "%HERE%process.py" --output "%OUTPUT_DIR%"

Tips

  • Restart the terminal after setx; existing windows don’t see new values.
  • Use different names for dev/prod tokens; keep secrets out of code and logs.
  • Prefer .env for app‑local defaults; use real env vars for machine/user settings.
  • On Windows paths, escape backslashes in Python strings (C:\\Users\\...).