Syntax of os.environ Object
The os.environ object in Python is a dictionary-like object that represents the environment variables of the current operating system environment. It provides a convenient interface for accessing and modifying environment variables within a Python script.
The syntax for os.environ is straightforward:
import os
# Accessing environment variables
value = os.environ['ENV_VARIABLE_NAME']
# Modifying environment variables
os.environ['ENV_VARIABLE_NAME'] = 'new_value'
# Deleting environment variables
del os.environ['ENV_VARIABLE_NAME']
Here, os.environ acts as a dictionary where environment variables are stored as key-value pairs. You can access the value of a specific environment variable using its name as the key, modify its value by assigning a new value to it, or delete it using the del keyword.
Python os.environ Examples
Get an Environment Variable
Python os environ contains all the environment variables. Using the standard dictionary syntax is the simplest approach to get a variable from within your program.
Code
import os
user = os.environ['USER']
user
Output:
rexa
If you import an environment variable using this method and it doesn't exist, Python will throw a KeyError exception.
Using os.environ.get()
It's a good idea to get the KeyError for environment variables that your application needs, but there are some circumstances in which you might want to make some variables optional. Use the dictionary's get() method to prevent the error, which returns None if the requested key doesn't exist in the dictionary:
Code
import os
user = os.environ['VARIABLE_USER']
user
Output
NONE
We can add a second argument as a default value instead of none.
Code
import os
user = os.environ['VARIABLE_USER',’CODING NINJAS’]
user
Output
CODING NINJAS
Set an Environment Variable
Environment variables can also be changed to new strings. Similar to how Python dictionaries work. It's crucial to remember that this modifies the environment variable for this particular session. In other words, altering the environment variable here won't impact it elsewhere.
Code
os.environ['USER'] = 'CODING NINJAS'

You can also try this code with Online Python Compiler
Run Code
Use os.environ.pop() with the key to clear a single environment variable in the current session, and os.environ.clear() to delete all environment variables.
It's crucial to remember that the settings you make in a Python script only affect that particular process; Python os environ does not affect the environment variables on a system-wide level. You will require a shell environment, such as Bash, to permanently delete or set environment variables.
Check out Escape Sequence in Python
Modifying Environment Variables
Modifying environment variables refers to changing the values associated with specific environment variables within the operating system environment. In Python, you can achieve this using the os.environ object.
import os
# Modifying environment variables
os.environ['ENV_VARIABLE_NAME'] = 'new_value'
Here, os.environ['ENV_VARIABLE_NAME'] represents the environment variable you want to modify, and 'new_value' is the new value you want to assign to it. This operation allows you to dynamically update environment variable values within your Python script.
Deleting Environment Variables
Deleting environment variables involves removing specific environment variables from the operating system environment. This can be accomplished using the del keyword in combination with the os.environ object.
import os
# Deleting environment variables
del os.environ['ENV_VARIABLE_NAME']
In this example, del os.environ['ENV_VARIABLE_NAME'] removes the environment variable named 'ENV_VARIABLE_NAME' from the environment. This action effectively removes the variable and its associated value from the environment.
Checking if an Environment Variable Exists
Checking if an environment variable exists involves verifying whether a specific environment variable is present in the operating system environment. You can achieve this in Python by using conditional statements to check for the existence of a key in the os.environ dictionary.
import os
# Checking if an environment variable exists
if 'ENV_VARIABLE_NAME' in os.environ:
print("Environment variable exists.")
else:
print("Environment variable does not exist.")
Here, the if 'ENV_VARIABLE_NAME' in os.environ: statement checks if the environment variable named 'ENV_VARIABLE_NAME' exists in the environment. If it does, the script prints "Environment variable exists"; otherwise, it prints "Environment variable does not exist." This approach allows you to handle situations where you need to perform actions based on the presence or absence of specific environment variables.
Environment Variables
Environment variables are the variables that exist outside of our code as part of your server environment. It can help you by streamlining and making running your scripts and applications more secure. Its primary two features are:
- Automation: Environment variables save us from manually updating the environment variables each time they change. When running a script on someone else's computer, you don't need to change the "user" portion of the path manually; instead, you can use an environment variable that returns the user's name. This means that when utilizing a script on a different system, you no longer need to remember to modify that.
- Enhance Security Practices: Environment variables helps us to hide the [art of code which we don't want other to see. API tokens that grant access to your accounts. If this token is stored as an environment variable, you don't need to type it out in the file explicitly; you only need to call the environment variable. This also means that other people can use your code without having to hardcode their API tokens.
Also see, Merge Sort Python
Using dotenv Manage Environment Variables
You use a package like dotenv to help manage environment variables as you utilize more of them. By reading them from another file, you can set or modify the environment variables for files in a certain directory.
It's helpful when you separate the various stages of your product and place them in different directories. By working in that directory, you can use dotenv to ensure that the environment variables automatically adapt to your chosen environment.
However, remember that dotenv is a different file, and be careful not to forget it when switching between systems.
dotenv reads in environment variables from .env file. The file should be formatted as follows:
api-token = "abcdef"
The python-dotenv package allows an application to import variables defined in a .env file into the environment. You can dotenv in your virtual environment using pip:
pip install python-dotenv
We can call the environment variables in the following way after creating and saving them in the same folder as your Python file:
Code
from dotenv import load_dotenv
load_dotenv()
import os
token = os.environ.get("api-token")
If you have the correct tools, implementing environment variables isn't difficult, like many other Python features.
Frequently Asked Questions
What is the use of python os environ?
The python os environ mapping object represents the user's environmental variables. It gives back a dictionary with the user's environmental variables' values as keys.
How to create os environ?
To create an environment variable in Python, use os.environ['ENV_VARIABLE_NAME'] = 'value'. This assigns a value to the specified environment variable name.
What is the purpose of OS environ?
The purpose of os.environ is to manage and interact with environment variables in the operating system environment. It provides access to system configurations and settings within Python scripts.
Where are python os environ variables stored?
Your environment variables are now stored in yours. env file.
Does python os environ return a string?
Yes, python os environ return strings. We use os. environ to list all key/value pairs in the environment.
Conclusion
In this article, we had a detailed study about environment variables. Further, we learned about python os environ and various aspects of it. That's it from the article. I hope you all like it.
Recommended Readings: