0
0
PythonHow-ToBeginner · 3 min read

How to Set Environment Variable in Python Easily

You can set an environment variable in Python using os.environ like this: os.environ['VAR_NAME'] = 'value'. This sets the variable for the current running program.
📐

Syntax

Use the os.environ dictionary to set environment variables in Python. Assign a string value to a key representing the variable name.

  • os.environ['VAR_NAME']: The environment variable name as a string key.
  • 'value': The string value you want to assign.
python
import os
os.environ['MY_VAR'] = '12345'
💻

Example

This example shows how to set an environment variable and then read it back to confirm it was set.

python
import os

# Set environment variable
os.environ['GREETING'] = 'Hello, world!'

# Read and print the environment variable
print(os.environ['GREETING'])
Output
Hello, world!
⚠️

Common Pitfalls

One common mistake is expecting the environment variable to persist outside the Python program. Setting os.environ only affects the current process and its children, not the system or parent shell.

Another mistake is not using strings for both keys and values, which can cause errors.

python
import os

# Wrong: Using non-string value
# os.environ['NUMBER'] = 123  # This will raise a TypeError

# Right: Use string values
os.environ['NUMBER'] = '123'
print(os.environ['NUMBER'])
Output
123
📊

Quick Reference

  • Use import os to access environment variables.
  • Set variables with os.environ['VAR'] = 'value'.
  • Retrieve variables with os.environ.get('VAR') to avoid errors if missing.
  • Changes affect only the current Python process and its children.

Key Takeaways

Use os.environ['VAR_NAME'] = 'value' to set environment variables in Python.
Environment variables set this way only last during the program run.
Always use strings for both variable names and values.
Use os.environ.get('VAR_NAME') to safely read variables without errors.
Changes do not affect the system or parent shell environment.