Python set environment variable when creating venv

大兔子大兔子 提交于 2021-01-20 08:04:45

问题


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?


回答1:


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
}



回答2:


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')



来源:https://stackoverflow.com/questions/62006580/python-set-environment-variable-when-creating-venv

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!