In my project I use the built-in python virtual env (python -m venv
).
To set environment variables I add multiple export VAR1=VALUE1
to the end of the venv/bin/activate
.
Obviously, when I delete the venv and create a new one, for example with the new python version all my env variables get lost.
So, is there a way to preserve them? May be it is possible to define env variables when creating the venv?
Asked
Active
Viewed 1.3k times
6

Vladimir Vislovich
- 331
- 1
- 3
- 8
-
1if you delete a file, but you want a backup, you could copy it. Or just use a text editor to copy the lines that export variable names, and put that in a different script. You're going to have to edit the new activate script, regardless. – Kenny Ostrom May 25 '20 at 16:30
2 Answers
6
instead of adding to activate
export VAR1=VALUE1
consider writing them into their own file:
~/setupenv.sh:
export VAR1=VALUE1
and add the following to activate
source ~/setupenv.sh
However, personally, I would not do that. I would instead define a bash function to do it:
myownactivate(){
source <path_to_activate>
export VAR1=VALUE1
}

JL Peyret
- 10,917
- 2
- 54
- 73
1
Use dotenv
Essentially, you have to create a simple .env
file that containsyour variables and values and it will load them when you run your application.
You can access them by os.getenv('VAR1')

sagar1025
- 616
- 9
- 22
-
1I would give the same advice for dotenv. But it is not complete without stating, that the application itself is then responsible for loading the env file. That is not exactly what was asked by the OP. – VPfB May 25 '20 at 16:46
-
-
I haven't tried this, but if you add `export VAR1=VALUE1` at the end of `$HOME/.bashrc`, can you still access the environment variable by calling `os.getenv()` ? – sagar1025 May 25 '20 at 18:00