How do I access environment variables in Python?

Better Stack Team
Updated on January 26, 2023

You can access environment variables in Python using the os module.

Here's an example:

 
import os

# Access an environment variable
value = os.environ['VARIABLE_NAME']

# Set an environment variable
os.environ['VARIABLE_NAME'] = 'value'

You can also use the os.getenv function to get the value of an environment variable. This function takes the name of the environment variable as an argument and returns the value of the variable as a string:

 
import os

value = os.getenv('VARIABLE_NAME')

If the environment variable is not set, os.getenv returns None. You can also specify a default value to be returned if the environment variable is not set:

 
import os

value = os.getenv('VARIABLE_NAME', 'default_value')

This can be useful if you want to use a default value if the environment variable is not set.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →