How to Set Environment Variables for Python on Windows, macOS, and Linux

Set environment variables for Python is a foundational skill that helps developers manage configuration, improve security, and keep projects flexible across different systems.

Instead of hard-coding sensitive values like API keys or environment-specific settings, Python environment variables allow you to separate code from configuration in a clean and scalable way. Whether you are building a small script or deploying a production-ready application, understanding how environment variables work can save time, reduce errors, and simplify collaboration. 

In this article, you will learn why environment variables matter and how to set environment variables for Python projects.

Table of Contents

What Environment Variables Are?

Environment variables are key-value pairs stored by the operating system that applications can read at runtime to control behaviour without changing the source code. In simple terms, they act like external settings that tell a program how to run in a specific environment.

For example, instead of hard-coding sensitive or changeable data – such as database credentials, API Keys, file Paths, or debug modes – you store them as environment variables. Python can then access these values when the program runs, making the application more secure, flexible and easier to maintain.

Why do Environmental Variables Matter?

Security :- Keeps sensitive information out of source code.

Flexibility :- Same code can run differently in development, testing and production.

Portability :- Work consistently across different machines and operating systems.

Maintainability :- Changes don’t require editing or redeploying of code.

In Python, environment variables are commonly accessed using the built-in os module, allowing programs to adapt dynamically based on their environment.

Why Does Python Use Environment Variables ?

Python itself does not require environment variables to run, but it uses and respects them because they are a powerful, standard way for the operating system and applications to configure behaviour without changing the code.

Here is a clear breakdown of why Python uses environment aerial and what they are used for?

1 Configuration Without Changing the Code

Environment variables let you change how a Python program leaves without editing the source.

Example:

  • Switching between development/testing/production.
  • Setting API keys or database URL
  • Enabling or disabling debug modes.

Code Example:

export DEUG= true

python app.py

Import os

DEUG = os.getenv(“DEUG”) == “true”

This keeps code portale and safer.

2 Security (Especially for Secrets)

Environment variables are commonly used to store.

  • API Keys
  • Passwords
  • Tokens

Why?

  • They are not hard-coded.
  • They are excluded from source-control.
  • Different machines can use different secrets.

Ex:

Import os 

API_KEY = os.environ[“API_KEY”]

This avoids accidently leaking credentials.

3 Virtual Environments & Dependency Isolation

Python uses environment variables to manage virtual environments.

Important ones include:

VIRTUAL_ENV – path to activate virtual environment 

PATH – determines which python executables run.

PYTHONHOME, PYTHONPATH – These helps python 

  • Find packages
  • Use the correct interpreter
  • Avoid conflicts between projects.

4 Control Python’s Runtime Behavior

Python checks several environment variables before execution to decide how it should behave.

Common ones:

  • PYTHONPATH → extra directories to search for modules
  • PYTHONUNBUFFERED → forces real-time output
  • PYTHONDONTWRITEBYTECODE → prevents .pyc files
  • PYTHONHASHSEED → controls hash randomization

These allow fine-grained control without changing scripts.

5 Cross-Platform Compatibility

Environment variables are:

  • Supported on Windows, macOS, Linux
  • Understood by shells, Docker, CI/CD systems, and servers

This makes Python apps easier to deploy everywhere.

6 Integration with Operating Systems & Tools

Python doesn’t live alone—it integrates with:

  • OS shells
  • Docker containers
  • CI/CD pipelines
  • Cloud platforms

All of these use environment variables as their primary configuration mechanism, so Python follows that standard.

7 Separation of Code and Configuration (Best Practice)

A key software principle is:

Code should not contain environment-specific configuration

Environment variables help enforce that:

  • Same codebase
  • Different environments
  • No rewrites needed

How to Set Environment Variables for Python

  • Windows
  • macOS
  • Linux

Environment variables for Python are not special – Python reads the same os-level environment variables as any other program.

So setting the environment variable for Python really means.

Set the OS environment variable, then run Python from that environment.

Below is the Python focused, practical guide for Windows, MacOS and Linux.

Windows – Python 

1️⃣ Temporary (Command Prompt)

Set DEUG = true

Python app.py

Only applies to that window.

2️⃣ Temporary (PowerShell)

$env:DEBUG=”true”

python app.py

3️⃣ Permanent (Recommended)

1. Press win+R > type sysdm.cpl

2. Advanced -> environment variables.

3. Add under user variables.

Name: DEUG

Value: true

4. Restart terminal/IDE

Python will see it in all future runs.

🍎 macOS (Python)

1️⃣ Temporary (Terminal)

export DEBUG=true

python3 app.py

2️⃣ Permanent (Recommended)

zsh (default shell)

echo ‘export DEBUG=true’ >> ~/.zshrc

source ~/.zshrc

bash (older macOS)

echo ‘export DEBUG=true’ >> ~/.bashrc

source ~/.bashrc

🐧 Linux (Python)

1️⃣ Temporary (Terminal)

export DEBUG=true

python app.py

2️⃣ Permanent (User)

echo ‘export DEBUG=true’ >> ~/.bashrc

source ~/.bashrc

🎯 Setting Environment Variables Only for one Python run

macOS / Linux

DEBUG=true python app.py

Windows (PowerShell)

$env:DEBUG=”true”; python app.py

To set environment variables for Python, set them in the operating system first, then run Python from that environment.

🐍 Verify in Python (All OS) | How to Verify (os.environ)

os.environ is the full dictionary of environment variables, and
os.getenv() is a convenient way to read a single value from it.

Both read from the same source.

1️⃣ os.environ (full environment)

import os

print(os.environ)

  • Returns a dictionary-like object
  • Contains all environment variables
  • Keys and values are strings

Example output (simplified):

{

  ‘PATH’: ‘/usr/bin:/bin’,

  ‘HOME’: ‘/home/user’,

  ‘DEBUG’: ‘true’

}

To check one variable:

print(os.environ[“DEBUG”])

⚠️ Raises KeyError if it doesn’t exist.

2️⃣ os.getenv() (safe single lookup)

import os

print(os.getenv(“DEBUG”))

  • Returns the value or None
  • Does not raise an error
  • Internally reads from os.environ

Equivalent to:

os.environ.get(“DEBUG”)

Expected output:

true

Most Common Mistakes People Make with Environment Variables in Python

Here are the most common mistakes people make with environment variables in Python, with short explanations and fixes.

1️⃣ Thinking Python creates environment variables

Mistake

DEBUG = True

Believing this sets an environment variable.

Reality
This is just a Python variable. Environment variables must be set before Python starts.

Fix
Set it in the OS, then read it in Python:

import os

DEBUG = os.getenv(“DEBUG”)


2️⃣ Setting the variable after starting Python

Mistake

python

export DEBUG=true

Python will not see it.

Fix

export DEBUG=true

python app.py


3️⃣ Forgetting to export the variable (macOS/Linux)

Mistake

DEBUG=true

python app.py

Python won’t see it.

Fix

export DEBUG=true

python app.py

(or DEBUG=true python app.py)


4️⃣ Assuming env vars are booleans

Mistake

if os.getenv(“DEBUG”):

    …

“false” is still truthy!

Fix

DEBUG = os.getenv(“DEBUG”, “”).lower() == “true”


5️⃣ Typos in variable names

Mistake

export DEBIG=true

os.getenv(“DEBUG”)  # returns None

Fix

  • Use consistent naming
  • Prefer uppercase names

6️⃣ Expecting permanence without saving

Mistake

export DEBUG=true

Close terminal → variable gone.

Fix
Add it to:

  • ~/.zshrc
  • ~/.bashrc
  • Windows Environment Variables GUI

7️⃣ Not restarting the terminal / IDE

Mistake
Set variable → immediately run Python in an already-open IDE.

Fix
Restart:

  • Terminal
  • IDE
  • Debugger

8️⃣ Mixing .env files with OS env vars

Mistake
Creating a .env file and assuming Python reads it automatically.

Fix
Use a loader (e.g. python-dotenv):

from dotenv import load_dotenv

load_dotenv()


9️⃣ Hard-coding secrets anyway

Mistake

API_KEY = “abc123”

Even though env vars exist.

Fix

API_KEY = os.environ[“API_KEY”]


🔟 Confusing virtual environments with environment variables

Mistake
Thinking venv isolates env vars.

Reality
Virtual environments do not isolate environment variables.

They are inherited from the shell.


🧠 Best-practice pattern

import os

DEBUG = os.getenv(“DEBUG”, “false”).lower() == “true”

if DEBUG:

    print(“Debug mode enabled”)

Final Words : Setting Environment Variables for Python

Environment variables are a simple but powerful bridge between your operating system and Python programs.

They let you control behaviour , manage configuration and protect secure information without doing any change in your code.

Configure your environment, don’t hard-code it.

Happy Coding 🙂

Leave a Comment