2

Suppose created an environment variable in your Python script (which is a process). Is the lifetime of the environment variable the same as the lifetime of the script while it runs? I've set my environment variable and ran my Python code until completion and if I tried to do

echo $MY_CREATED_ENV_VAR

it returns empty. I know that my script creates this environment variable because I could use it within the script itself.

Here is part of the script

import os

os.environ['MY_CREATED_ENV_VAR'] = "1"

# Returns-> MY_CREATED_ENV_VAR = 1 (and usable by other processes in the script)
print("MY_CREATED_ENV_VAR = " + os.environ["MY_CREATED_ENV_VAR"])

# Script ends

does MY_CREATED_ENV_VAR automatically become unset? If not, how would I manually unset this environment variable in the script so as to clean up my code?

Thanks in advance!

Edit: I see that you can unset the variable, but then my question still stands, does python automatically unset the environmental variables? I cannot echo the env variable back in my terminal after the script has finished executing.

jimmyhuang0904
  • 181
  • 3
  • 10
  • 1
    @wrogrammer I don't think he even needs that. His created env var doesn't exist in the parent process, so there's no reason to delete it. – abarnert Jun 09 '18 at 00:25

1 Answers1

4

The environment variable will only be available for child processes not the parent process that spawned the Python program (or parallel processes running after the python script finishes), therefore, it's cleaned up only because it's out of scope.

del os.environ['MY_CREATED_ENV_VAR'] will remove it from the Python's process environment, though

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Ahh okay, even if it does clean up automatically, I should still put a safeguard by explicitly removing them if it is what I wanted. Thanks! – jimmyhuang0904 Jun 09 '18 at 00:29
  • I'm not sure if that'll work since, as mentioned, only that Python process's environment is modified. I was just saying that's how to delete a dictionary value – OneCricketeer Jun 09 '18 at 00:31