Access environment variable values in Python
Last Updated :
28 Apr, 2025
An environment variable is a variable that is created by the Operating System. Environment variables are created in the form of Key-Value pairs. To Access environment variables in Python's we can use the OS module which provides a property called environ that contains environment variables in key-value pairs. In this article, we will see how to use environment variables in Python.
How to Use Environment Variables in Python?
These are the different ways of accessing environment variables:
- Using os.environ()
- Access All Environment Variables
- Access Single Environment Variable
- Get value of the Environment variable
- Using os.getenv()
- Using python-dotenv Package
Access All Environment Variables Using os.environ()
Here, we are accessing all the environment variables that are present in the environment.
Python3
# import os module
import os
# display all environment variable
print(os.environ)
Output

Access Single Environment Variable Using os.environ()
Here, we are extracting single environment variable of COMPUTERNAME from the above list. If we try to access an environment variable that is not available we will get KeyError.
Python3
# import os module
import os
# access environment variable
print(os.environ['COMPUTERNAME'])
Output
DESKTOP-M2ASD91
Get value of the environment variable key using os.environ
Here, we are extracting single environment variable key of USERPROFILE path from the environ list. This will return None if the given key is not found.
Python3
# import os module
import os
# access environment variable using the key
print(os.environ.get('USERPROFILE'))
Output
C:\Users\suraj
Return default value if the key doesn't exist
Python3
# import os module
import os
# return default value if no
# key/environment variable if found
print(os.environ.get('DATABASE_NAME', 'example.database.net'))
Output
example.database.net/
Access Environment Variables Using os.getenv()
In this example, the code uses the os.getenv()
function to retrieve the value of the 'PATH' environment variable and assigns it to the variable home_dir
. The script then prints the obtained 'PATH' value.
Python3
import os
home_dir = os.getenv('PATH')
print(home_dir)
Output

Use Environment Variables Using Python dotenv Package
Firstly install python-dotenv
package by using the following command:
pip install python-dotenv
Create a file named .env
in the root of your project and add your environment variables with the format KEY=VALUE
. For example:
DATABASE_URL=mydatabaseurl
API_KEY=yourapikey
Use the dotenv
module to load the variables from the .env
file. Then, you can access them like regular Python variables. In this code, load_dotenv()
is used to load environment variables from a .env
file. The script then retrieves the values of "DATABASE_URL" and "API_KEY" using os.getenv()
and prints them for use in the script.
Python3
from dotenv import load_dotenv
import os
# Load environment variables from the .env file
load_dotenv()
# Access environment variables
database_url = os.getenv("DATABASE_URL")
api_key = os.getenv("API_KEY")
# Now you can use these variables in your script
print(f"Database URL: {database_url}")
print(f"API Key: {api_key}")
Output
Database URL: mydatabaseurl
API Key: yourapikey
Similar Reads
Assigning Values to Variables In this article, we will learn how to assign values to variables in Python and other languages also.Assigning Values to Variables in PythonBelow are the steps and methods by which we can assign values to variables in Python and other languages:Direct Initialization MethodUsing Conditional OperatorAs
4 min read
Context Variables in Python Context variable objects in Python is an interesting type of variable which returns the value of variable according to the context. It may have multiple values according to context in single thread or execution. The ContextVar class present in contextvars module, which is used to declare and work wi
4 min read
Different ways to access Instance Variable in Python Instance attributes are those attributes that are not shared by objects. Every object has its own copy of the instance attribute i.e. for every object, instance attribute is different. There are two ways to access the instance variable of class: Within the class by using self and object reference.Us
2 min read
Assign Function to a Variable in Python In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability.Example:Python# defining a function def a(): print(
3 min read
How to use/access a Global Variable in a function - Python In Python, variables declared outside of functions are global variables, and they can be accessed inside a function by simply referring to the variable by its name.Pythona = "Great" def fun(): # Accessing the global variable 'a' print("Python is " + a) fun()OutputPython is Great Explanation:Here a i
3 min read
How To Print A Variable's Name In Python In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simp
3 min read
Get Variable Name As String In Python In Python, getting the name of a variable as a string is not as straightforward as it may seem, as Python itself does not provide a built-in function for this purpose. However, several clever techniques and workarounds can be used to achieve this. In this article, we will explore some simple methods
3 min read
Print Single and Multiple variable in Python In Python, printing single and multiple variables refers to displaying the values stored in one or more variables using the print() function.Let's look at ways how we can print variables in Python:Printing a Single Variable in PythonThe simplest form of output is displaying the value of a single var
2 min read
How to check if a Python variable exists? Checking if a Python variable exists means determining whether a variable has been defined or is available in the current scope. For example, if you try to access a variable that hasn't been assigned a value, Python will raise a NameError. Letâs explore different methods to efficiently check if a va
3 min read
How to get value from address in Python ? In this article, we will discuss how to get the value from the address in Python. First, we have to calculate the memory address of the variable or python object which can be done by using the id() function. Syntax: id(python_object) where, python_object is any python variable or data structure like
4 min read