Open In App

Python | os.environ object

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

os.environ in Python is a mapping object that represents the user’s OS environmental variables. It returns a dictionary having the user’s environmental variable as key and their values as value.

os.environ behaves like a Python dictionary, so all the common dictionary operations like get and set can be performed. We can also modify os.environ but any changes will be effective only for the current process where it was assigned and it will not change the value permanently.

os.environ Object Syntax in Python

Syntax: os.environ

Parameter: It is a non-callable object. Hence, no parameter is required

Return Type: This returns a dictionary representing the user’s environmental variables

Python os.environ Object Examples

Below are some examples by which we can fetch environment variables with os.environ in Python and set an environment variable using the OS module in Python:

Access User Environment Variables Using os.environ Object

In this example, the below code uses the `os.environ` object to retrieve and print the list of user’s environment variables, employing the `pprint` module to display them in a readable format.

Python3




# importing os module 
import os
import pprint
   
# Get the list of user's
env_var = os.environ
   
# Print the list of user's
print("User's Environment variable:")
pprint.pprint(dict(env_var), width = 1)


Output:

{'CLUTTER_IM_MODULE': 'xim',
 'COLORTERM': 'truecolor',
 'DBUS_SESSION_BUS_ADDRESS': 'unix:path=/run/user/1000/bus',
 'DESKTOP_SESSION': 'ubuntu',
 'DISPLAY': ':0',
 'GDMSESSION': 'ubuntu',
 'GJS_DEBUG_OUTPUT': 'stderr',
 'GJS_DEBUG_TOPICS': 'JS '
                     'ERROR;JS '
                     'LOG',
 'GNOME_DESKTOP_SESSION_ID': 'this-is-deprecated',
 'GNOME_SHELL_SESSION_MODE': 'ubuntu',
 'GTK_IM_MODULE': 'ibus',
 'HOME': '/home/ihritik',
 'IM_CONFIG_PHASE': '2',
 'JAVA_HOME': '/opt/jdk-10.0.1',
 'JOURNAL_STREAM': '9:28586',
 'JRE_HOME': '/opt/jdk-10.0.1/jre',
 'LANG': 'en_IN',
 'LANGUAGE': 'en_IN:en',
 'LESSCLOSE': '/usr/bin/lesspipe '
              '%s '
              '%s',
 'LESSOPEN': '| '
             '/usr/bin/lesspipe '
             '%s',
 'LOGNAME': 'ihritik',
 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:
/usr/local/games:/snap/bin:/usr/local/java/jdk-10.0.1/bin:
/usr/local/java/jdk-10.0.1/jre/bin:/opt/jdk-10.0.1/bin:/opt/jdk-10.0.1/jre/bin',
 'PWD': '/home/ihritik',
 'QT4_IM_MODULE': 'xim',
 'QT_IM_MODULE': 'ibus',
 'SESSION_MANAGER': 'local/hritik:@/tmp/.ICE-unix/1127, unix/hritik:/tmp/.ICE-unix/1127',
 'SHELL': '/bin/bash',
 'SHLVL': '2',
 'SSH_AUTH_SOCK': '/run/user/1000/keyring/ssh',
 'TERM': 'xterm-256color',
 'TEXTDOMAIN': 'im-config',
 'TEXTDOMAINDIR': '/usr/share/locale/',
 'USER': 'ihritik',
 'USERNAME': 'ihritik',
 'VTE_VERSION': '4804',
 'WAYLAND_DISPLAY': 'wayland-0',
 'XDG_CONFIG_DIRS': '/etc/xdg/xdg-ubuntu:/etc/xdg',
 'XDG_CURRENT_DESKTOP': 'ubuntu:GNOME',
 'XDG_MENU_PREFIX': 'gnome-',
 'XDG_RUNTIME_DIR': '/run/user/1000',
 'XDG_SEAT': 'seat0',
 'XDG_SESSION_DESKTOP': 'ubuntu',
 'XDG_SESSION_ID': '2',
 'XDG_SESSION_TYPE': 'wayland',
 'XDG_VTNR': '2',
 'XMODIFIERS': '@im=ibus',
 '_': '/usr/bin/python3'}

Retrieving Specific Environment Variables Using os.environ Object

In this example, this code uses the os.environ object to retrieve and print the values of specific environment variables (‘HOME’ and ‘JAVA_HOME’). It demonstrates accessing the values directly using square bracket notation for an existing variable (‘HOME’) and using the os.environ.get() method for a variable that may not exist (‘JAVA_HOME’).

Python3




# importing os module 
import os
 
# 'HOME' environment variable
home = os.environ['HOME']
   
print("HOME:", home)
    
# 'JAVA_HOME' environment variable
java_home = os.environ.get('JAVA_HOME')
   
# 'JAVA_HOME' environment variable
print("JAVA_HOME:", java_home)


Output:

HOME: /home/ihritik
JAVA_HOME: /opt/jdk-10.0.1

Set an Environment Variable Using the OS Module

In this example, the Python code prints the current value of the ‘JAVA_HOME’ environment variable using `os.environ[‘JAVA_HOME’]`, then modifies the value of ‘JAVA_HOME’ to ‘/home/ihritik/jdk-10.0.1’, and prints the modified value using the same method.

Python3




# importing os module 
import os
   
# Print the value
print("JAVA_HOME:", os.environ['JAVA_HOME'])
   
# Modify the value
os.environ['JAVA_HOME'] = '/home / ihritik / jdk-10.0.1'
   
# Print the modified value
print("Modified JAVA_HOME:", os.environ['JAVA_HOME'])


Output:

JAVA_HOME: /opt/jdk-10.0.1
Modified JAVA_HOME: /home/ihritik/jdk-10.0.1

Add New Environment Variable Using os.environ Object

In this example, the Python code uses the `os.environ` object to add a new environment variable named ‘GeeksForGeeks’ with the value ‘www.geeksforgeeks.org’. It then retrieves and prints the value of the added environment variable using os.environ[‘GeeksForGeeks’].

Python3




# importing os module 
import os
   
# Add a new environment variable 
os.environ['GeeksForGeeks'] = 'www.geeksforgeeks.org'
   
# Get the value 
print("GeeksForGeeks:", os.environ['GeeksForGeeks'])


Output:

GeeksForGeeks: www.geeksforgeeks.org

Access Environment Variable that Does Not Exists

In this example, the Python code attempts to print the value of the ‘MY_HOME’ environment variable using os.environ['MY_HOME']. However, there is a syntax error in the code due to the missing closing parenthesis in the print statement, which would result in a SyntaxError.

Python3




# importing os module 
import os
   
# Print the value
print("MY_HOME:", os.environ['MY_HOME']


Output:

Traceback (most recent call last):
  File "osenviron.py", line 8, in 
    print("MY_HOME:", os.environ['MY_HOME'])
  File "/usr/lib/python3.6/os.py", line 669, in __getitem__
    raise KeyError(key) from None
KeyError: 'MY_HOME'

Handling Error while Access Environment Variable which Does Not Exists

In this example, the code demonstrates two methods to access the value of the environment variable ‘MY_HOME.’ The first method uses `os.environ.get()` with a default message if the variable is not found, while the second method uses a try-except block to catch a KeyError if the variable is not present.

Python3




# importing os module 
import os
   
# Method 1
print("MY_HOME:", os.environ.get('MY_HOME', "Environment variable does not exist"))
   
# Method 2
try:
    print("MY_HOME:", os.environ['MY_HOME'])
except KeyError: 
    print("Environment variable does not exist")


Output:

MY_HOME: Environment variable does not exist
Environment variable does not exist

Frequently Asked Questions ( FAQs )

What do you mean by OS environment?

The Operating System (OS) environmental or OS environ means or OS environ define the software and hardware infrastructure that enables computer programs to run. It includes the OS kernel, system libraries, and device drivers, providing an interface for application software to interact with the computer hardware.

How can I access environment variables in Python?

In Python, you can access environment variables using the `os` module. By using os.environ, we can access a dictionary-like object containing environment variables. For example, `value = os.environ.get(‘VARIABLE_NAME’)` retrieves the value of the specified environment variable.



Last Updated : 12 Jan, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads