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
.
os.unsetenv(key)
key
: The environment key to be deleted.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)
child.py
This Python script tries to print the environment variable educative
.
main.py
os
module.educative
whose value is awesome
.unsetenv()
method and pass educative
as the parameter.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.educative
key is still present in the os.environ
dictionary.