Explain Codes LogoExplain Codes Logo

How to set environment variables in Python?

python
environment-variables
dotenv
subprocess
Anton ShumikhinbyAnton Shumikhin·Aug 18, 2024
TLDR

Set an environment variable on-the-fly in Python:

import os os.environ['VAR_NAME'] = 'value'

This alters VAR_NAME for the current script's lifetime. Global settings or other programs remain untouched.

To fetch a variable and avoid a nasty KeyError, use the get() method:

value = os.environ.get('VAR_NAME', 'default_value') # If VAR_NAME doesn't exist, we'll get 'default_value'

Use os.environ method to manage variables

Setting environment variables

Add or change environment variables with a simple Python assignment:

# My first environment variable! Mom will be so proud! os.environ['MY_VAR'] = 'Hello, World!'

Checking existence of a variable

Ensure an environment variable exists before using it. Your script will thank you.

if 'MY_VAR' in os.environ: print("Mom's watching!") else: print("You're forgotten, mate!")

Wrestling with non-string variables

Dealing with non-strings? Python's got your back. Just convert them:

os.environ['LUCKY_NUMBER'] = str(7) # Saving your lucky number as an environment variable (just don't tell anyone!)

Scope and persistence of environment variables

Temporary vs. Permanent settings

Variables set with os.environ impact the current process and child processes. Use wisely - they're not here for a long time, just a good time.

Making permanent system variables in Windows

For a deeper impact on the system, Windows users, use SETX:

os.system('SETX SOUP_RECIPE "Delicious" /M') # '/M' is like chanting a permanent spell, but less magical and more annoying

Advanced tips and tricks with environment variables

Using .env files for storing variables

Friends don't let friends hard-code environment variables. Use a .env file:

from dotenv import load_dotenv load_dotenv('/path/to/.env') # Embrace the power of .env files!

Controlling environment for subprocesses

While creating subprocesses, command the environment like a boss:

import subprocess my_env = os.environ.copy() my_env["SECRET_KEY"] = "abc123" # Spawning a subprocess with your secret key. Let the chaos reign! subprocess.run(["some_command"], env=my_env)