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:
os.system()os.popen()os.fork()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 osos.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
osmodule. - Line 3: We create a new environment variable called
educativewhose value isawesome. - Lines 5–6: We print the current environment variables.
- Line 8: We invoke the
unsetenv()method and passeducativeas the parameter. - Lines 10-11: We execute the
child.pyscript using theos.system()call. This method throws an error indicating that theeducativekey is not found in theos.environdictionary. This indicates thatunsetenv()affects the child’s process environment only. - Line 13: We check if the
educativekey is still present in theos.environdictionary.