Python Get environment variables

Posted in Python by Dirk - last update: Feb 14, 2024

In Python, you can access environment variables using the os module. You can access all variables via os.environ() or access a specific variable using os.getenv() or os.environ.get()

Get all environment variables

You can get all environment variables using the os.environ() function of the os module

import os

# Get all environment variables
all_variables = os.environ

# Print all variables and their values
for variable, value in all_variables.items():
    print(f"{variable}: {value}")

Note: os.environ is an instance of the os._Environ class in Python. It’s essentially a mapping object representing the environment variables of the current process. The keys are variable names, and the values are their corresponding values in the environment.

While os.environ behaves like a dictionary, it’s not exactly a regular dictionary object. However, you can perform typical dictionary operations on it, such as iterating over its items, checking for the existence of a key, or retrieving values using square bracket notation.

In the example above for variable, value in all_variables.items(): we iterate over all the elements of the os.environ object and getting the values for all the keys

Get a Specific Environment Variable:

Using os.getenv()

Example

import os

# Specify the variable name
variable_name = "MY_VARIABLE"

# Attempt to get the value, with a default value in case it doesn't exist
value = os.getenv(variable_name)

# Handle the case when the variable doesn't exist
if value is None:
    print(f"{variable_name} does not exist.")
else:
    print(f"{variable_name} value: {value}")

If the variable variable_name is not an environment variable - the os.getenv(variable_name)will return None.

Alternatively - you can specify a default value when using os.getenv()

import os

# Specify the variable name
variable_name = "MY_VARIABLE"

# Attempt to get the value, with a default value in case it doesn't exist
value = os.getenv(variable_name, "default_value")

If the variable variable_name is not an environment value - the valuevariable will get the default_value

Using os.getenv().get()

The os.environ is a dictionary like object and can be accessed directly using the get() function. The get() method can be used with or without a default value if the variable is not present.

import os

variable_name = "MY_VARIABLE"
value = os.environ.get(variable_name)

os.environ.get() will retun None if the environmnet variable does not exist. Alternatively - a default value can be used as in the example below:

import os

variable_name = "MY_VARIABLE"
value = os.environ.get(variable_name, "default_value")

In this case - when no environment variable is found, the default_value will be used.

Using os.environ()

You can try to access the variable directly using the variable as the key in os.environ as it behaves like a dictionary object. However, if you reference a key in a dictionary that does not exist you will get a KeyError so you need to handle it with a try-except block:

import os

variable_name = "MY_VARIABLE"

try:
    value = os.environ[variable_name]
    print(f"{variable_name} value: {value}")
except KeyError:
    print(f"{variable_name} does not exist.")

Create, Delete, and Modify Environment Variables:

Create Environment Variables:

import os

# Specify the variable name and value
variable_name = "NEW_VARIABLE"
variable_value = "new_value"

# Set the environment variable
os.environ[variable_name] = variable_value

Modify Environment Variables

import os

# Specify the variable name and new value
variable_name = "EXISTING_VARIABLE"
new_value = "updated_value"

# Update the environment variable
os.environ[variable_name] = new_value

Delete Environment Variables


import os

# Specify the variable name
variable_name = "UNWANTED_VARIABLE"

# Remove the environment variable if it exists
if variable_name in os.environ:
    del os.environ[variable_name]

Environment variables: when to use

Where Environment variables can be used:

  • Configuration: Storing configuration parameters for an application.
  • Authentication: Storing API keys, passwords, or other sensitive information.
  • System Configuration: Customizing the behavior of scripts or programs.
  • Path Definitions: Specifying directories for file operations.

Remember that modifying environment variables in a running Python process only affects that process. It won’t persist after the script ends. If you want to make changes permanent, you may need to set them outside of the Python script (e.g., in shell profile files like .bashrc or system settings).

Manage environment variables using decouple

To manage environment variables in a more structured and secure way, you can use the python-decouple library. python-decouple allows you to define configuration variables in a separate file and easily access them in your Python code. This is particularly useful for keeping sensitive information, such as API keys or database credentials, separate from your codebase.

Here’s a step-by-step guide on how to use python-decouple to manage environment variables:

Install python-decouple

You can install the library using pip:

pip install python-decouple

Create a .env file

Create a file named .env in your project’s root directory. This file will store your environment variables.

Example .env file:

# .env
SECRET_KEY=mysecretkey
DEBUG=True
DATABASE_URL=sqlite:///db.sqlite3

Access environment variables in your Python code

Use python-decouple to access environment variables from the .env file.

# main.py
from decouple import config

# Load environment variables from .env file
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
DATABASE_URL = config('DATABASE_URL')

# Use the variables in your code
print(f"Secret Key: {SECRET_KEY}")
print(f"Debug Mode: {DEBUG}")
print(f"Database URL: {DATABASE_URL}")

In this example, config() is used to retrieve values from the .env file. The cast parameter is used to convert the value to a specific type (e.g., bool for DEBUG).

Add .env to your .gitignore file:

It’s a good practice to add the .env file to your .gitignore to avoid accidentally committing sensitive information.

Example .gitignore:

.env
__pycache__
*.pyc
*.pyo
.DS_Store

Run your Python script:

When you run your Python script, python-decouple will read the variables from the .env file.


python main.py

By using python-decouple, you can keep your environment variables organized and separate from your codebase, making it easier to manage configuration settings, especially in production environments where sensitive information should be kept secure.

Other articles