Skip to content

How to access and set environment variables in Python

Learn how environment variables can be retrieved and created using Python.

Environment variables are stored at the operating system level as key-value pairs, they play a crucial role in abstracting sensitive information.

They also help a programmer in configuring an application just by changing their values instead of hard coding them.

This article will take you through the process of retrieving and setting environment variable values using Python.

Get environment variable values

The os standard library in Python helps in executing tasks at the OS level. We can retrieve environment variables using the following code snippet.

import os

# print all environment variables as a dictionary

# get LANG variable without KeyError

Set environment variable

Setting environment variables is the same as setting a key-value pair in a dictionary. Key and value both must be of string data type.

import os

os.environ["MY_CUSTOM_KEY"] = "secret_value"

FREE VS Code / PyCharm Extensions I Use

✅ Write cleaner code with Sourcery, instant refactoring suggestions: Link*

PySaaS: The Pure Python SaaS Starter Kit

🚀 Build a software business faster with pure Python: Link*

* These are affiliate link. By clicking on it you will not have any additional costs. Instead, you will support my project. Thank you! 🙏