What is the os.unsetenv() method in Python?

Overview

The os module in Python provides functions that help us interact with the underlying operating system.

The unsetenv() method is used to delete the given environment variable. The deletion affects the subprocesses created by the following method calls:

  1. os.system()
  2. os.popen()
  3. os.fork()
  4. os.execv()

Using os.unsetenv() doesn’t actually delete the keys stored in the os.environ. Instead, we can use the del operator or the pop method on the os.environ dictionary.

Note: Refer to this link to learn more about os.environ.

Syntax

os.unsetenv(key)

Parameter values

  • key: The environment key to be deleted.

Code example

main.py
child.py
import os
os.environ["educative"] = "awesome"
print("The current environment variables are:")
print(os.environ)
os.unsetenv("educative")
print("Executing child.py")
os.system("python child.py")
print("Is the key 'educative' still present in the os.environ dictionary?", "educative" in os.environ)

Explanation

child.py

This Python script tries to print the environment variable educative.

main.py

  • Line 1: We import the os module.
  • Line 3: We create a new environment variable called educative whose value is awesome.
  • Lines 5–6: We print the current environment variables.
  • Line 8: We invoke the unsetenv() method and pass educative as the parameter.
  • Lines 10-11: We execute the child.py script using the os.system() call. This method throws an error indicating that the educative key is not found in the os.environ dictionary. This indicates that unsetenv() affects the child’s process environment only.
  • Line 13: We check if the educative key is still present in the os.environ dictionary.

Free Resources