Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator
os

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

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

python
communitycreator
os

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring