How to Read Environment Variable in Python Easily
In Python, you can read environment variables using the
os.environ dictionary or the os.getenv() function. Both methods allow you to access variables set in your system environment safely and easily.Syntax
To read an environment variable in Python, you use the os module. The two common ways are:
os.environ['VARIABLE_NAME']: Accesses the variable directly but raises an error if it does not exist.os.getenv('VARIABLE_NAME'): Returns the variable value orNoneif it does not exist, avoiding errors.
python
import os # Access environment variable directly value = os.environ['MY_VAR'] # Access environment variable safely value_safe = os.getenv('MY_VAR')
Example
This example shows how to read an environment variable named MY_VAR. It prints the value if set, or a default message if not.
python
import os # Try to get environment variable MY_VAR my_var = os.getenv('MY_VAR') if my_var is not None: print(f'MY_VAR value: {my_var}') else: print('MY_VAR is not set')
Output
MY_VAR is not set
Common Pitfalls
Common mistakes include:
- Using
os.environ['VAR']without checking if the variable exists, which causes aKeyError. - Assuming environment variables are always strings; they are, so convert if needed.
- Not setting environment variables before running the script.
Use os.getenv() to avoid errors when the variable might be missing.
python
import os # Wrong way: may raise KeyError if VAR not set # value = os.environ['VAR'] # Right way: returns None if VAR not set value = os.getenv('VAR') if value is None: print('VAR is not set') else: print(f'VAR value: {value}')
Output
VAR is not set
Quick Reference
| Method | Description | Behavior if Variable Missing |
|---|---|---|
| os.environ['VAR'] | Access variable directly | Raises KeyError if missing |
| os.getenv('VAR') | Get variable safely | Returns None if missing |
| os.getenv('VAR', 'default') | Get variable with default | Returns 'default' if missing |
Key Takeaways
Use os.getenv() to safely read environment variables without errors.
os.environ['VAR'] raises an error if the variable does not exist.
Environment variables are strings; convert them if needed.
Always check if the variable exists before using it.
Set environment variables in your system or shell before running Python scripts.