writetonikhil
writetonikhil

Reputation: 25

Environment variables getting preserved in Python script even after exiting

I am running my Test Harness which is written in Python. Before running a test through this test harness, I am exporting some environment variables through a shell script which calls the test harness after exporting the variables. When the harness comes in picture, it checks if the variables are in the environment and does operations depending on the values in the env variables.

However after the test is executed, I think the environment variables values aren't getting cleared as the next time, it picks up those values even if those aren't set through the shell script.

If they are set explicitly, the harness picks up the new values but if we clear it next time, it again picks up the values set in 1st run.

I tried clearing the variables using "del os.environ['var']" command after every test execution but that didn't solve the issue. Does anybody know why are these values getting preserved?

On the shell these variables are not set as seen in the 'env' unix command. It is just in the test harness that it shows the values. None of the env variables store their values in any text files.

Upvotes: 2

Views: 3155

Answers (2)

alexis
alexis

Reputation: 50220

The python process cannot affect the environment of the parent shell process that launched it. If you have a parent shell, its environment will persist unless/until the shell itself changes it.

However, a bash script can set environment variables for the child script only, like this:

export OPTIONS=parent
OPTIONS=child python child.py
echo $OPTIONS

This will echo "parent", not "child", but the python process will see OPTIONS=child. You don't describe your set-up very clearly, but maybe this can help?

Upvotes: 1

kev
kev

Reputation: 161874

A subshell can change variables it inherited from the parent, but the changes made by the child don't affect the parent.
When a new subshell is started, in which the variable exported from the parent is visible. The variable is unsetted by del os.environ['var'], but the value for this variable in the parent stays the same.

Upvotes: 1

Related Questions