简体   繁体   English

Python 创建venv时设置环境变量

[英]Python set environment variable when creating venv

In my project I use the built-in python virtual env ( python -m venv ).在我的项目中,我使用内置的 python 虚拟环境( python -m venv )。
To set environment variables I add multiple export VAR1=VALUE1 to the end of the venv/bin/activate .要设置环境变量,我将多个export VAR1=VALUE1添加到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.显然,当我删除 venv 并创建一个新的时,例如使用新的 python 版本,我所有的 env 变量都会丢失。
So, is there a way to preserve them?那么,有没有办法保存它们呢? May be it is possible to define env variables when creating the venv?在创建 venv 时是否可以定义 env 变量?

instead of adding to activate而不是添加activate

export VAR1=VALUE1

consider writing them into their own file:考虑将它们写入自己的文件中:

~/setupenv.sh : ~/setupenv.sh

export VAR1=VALUE1

and add the following to activate并添加以下内容以activate

source ~/setupenv.sh

However, personally, I would not do that.但是,就我个人而言,我不会那样做。 I would instead define a bash function to do it:我会改为定义一个 bash function 来做到这一点:

myownactivate(){
  source <path_to_activate>
  export VAR1=VALUE1
}

Use dotenv使用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.本质上,您必须创建一个简单的.env文件,其中包含您的变量和值,它会在您运行应用程序时加载它们。

You can access them by os.getenv('VAR1')您可以通过os.getenv('VAR1')访问它们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM