Python os.environ() Method

Imran Alam Jan 30, 2023
  1. Syntax of os.environ():
  2. Example Codes: Get All Environment Variables Using the os.environ() Method
  3. Example Codes: Get the PATH Environment Variable Value Using the os.environ() Method
  4. Example Codes: Set the TEST Environment Variable Value Using the os.environ() Method
  5. Example Codes: Possible Error While Using the os.environ() Method
Python os.environ() Method

The os.environ() method is a built-in function that returns a dictionary of all the environment variables set for the current user.

Syntax of os.environ():

os.environ()

Parameter

This method does not take any parameters.

Return

This method returns a dictionary of all the environment variables set for the current user.

Example Codes: Get All Environment Variables Using the os.environ() Method

In this example, we will get all the environment variables for the current user.

import os

print(os.environ)

Output:

{'TERM': 'xterm-256color', 'SHELL': '/bin/bash', 'USER': 'root', 'PATH': '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games', 'MAIL': '/var/mail/root', 'PWD': '/root', 'LANG': 'en_US.UTF-8', 'SHLVL': '1', 'HOME': '/root', '_': '/usr/bin/python3'}

Example Codes: Get the PATH Environment Variable Value Using the os.environ() Method

In this example, we will get the value of the PATH environment variable.

import os

print(os.environ["PATH"])

Output:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games

Example Codes: Set the TEST Environment Variable Value Using the os.environ() Method

In this example, we will set the value of the TEST environment variable.

import os

os.environ["TEST"] = "test"

print(os.environ["TEST"])

Output:

test

Example Codes: Possible Error While Using the os.environ() Method

If the environment variable does not exist, a KeyError will be raised.

import os

print(os.environ["TEST"])

Output:

Traceback (most recent call last):
File "[test.py](http://test.py/)", line 5, in <module>
print(os.environ['TEST'])
KeyError: 'TEST'

Related Article - Python OS