os.environ - The environment variables mapping in python

os.environ in python has the environment variables set on it as a mapping object during the startup of the Python. The example Python program retrieves the $HOME from the os.environ and adds a new environment value called $TestLogPath and prints it on the terminal.

Os Updated 16 Nov 2018 1 min read

Variable Name

os.environ

Overview

  • Several aspects of a system can be defined and controlled through a set of variables, which are called together as the environment. Example: $HOME environment variable defines the pathname of the home directory of the user.
  • The set of environment variables is available to Python through the variable os.environ of the os module.
  • Based on the implementation new variables can be added and removed as well using the os.environ.
  • The Python os module provides a binary or byte strings version as well through os.environb based on the value of os.supports_bytes_environ. The os.supports_bytes_environ is a binary value.

Example

python
import os

# Print the $HOME environment variable

print("The $Home environment variable as defined:")

print(os.environ['HOME'])

# Add a new variable to the environment

newVar = 'TestLogPath'

os.environ[newVar] = os.environ['HOME']+'/'+'TestLogs'

print("Value of the newly added variable named %s:"%(newVar))

print(os.environ[newVar])

Output

Output
The $Home environment variable as defined:

/Users/PythonCoder

Value of the newly added variable named TestLogPath:

/Users/PythonCoder/TestLogs