Tuesday, February 1, 2022

[SOLVED] How can I run a cleanup script on virtualenv `deactivate`?

Issue

Via autoenv, whenever I cd into a directory with a .env file, I automatically activate my python virtual environment and set some environment variables. This .env file by essence is a setup script.

# /absolute/path/to/project/.env
source /absolute/path/to/project/.venv/bin/activate

export ENV_VAR_1="foo"
export ENV_VAR_2="bar"

But when I'm done working on my project and I type deactivate

  • I expect these environment variables to vanish.
  • In reality, these environment variables persist.

Is there a clean way for me to run a teardown script when I call deactivate that does some project clean up when I'm done for the day?


Solution

Inside the activate script, there is a deactivate block in which you can unset the variables:

deactivate () {
    # ...
    unset ENV_VAR_1
    unset ENV_VAR_2
}


Answered By - user2390182
Answer Checked By - Robin (WPSolving Admin)