简体   繁体   English

在 vscode 中为 jupyter notebook 创建环境变量

[英]creating environment variables for jupyter notebook in vscode

In vscode settings.json file I can use the following option to define environment variables:在 vscode settings.json文件中,我可以使用以下选项来定义环境变量:

"terminal.integrated.env.osx" : {
    "MY_ENV": "test"
    "MY_ENVTYPE": "qa"
}

Now whenever, I start a new shell in the workspace, the shell loads with the above environment variables, and I can access them typically with os.environ["MY_ENV"] is my python scripts.现在,每当我在工作区中启动一个新的 shell 时,shell 都会加载上述环境变量,我通常可以使用os.environ["MY_ENV"]访问它们,即我的 Z23EEEB4347BDD26BDDFC6B7 脚本。

But with the same settings.json , if I try to access the environment variables in a jupyter notebook I get None .但是使用相同的settings.json ,如果我尝试访问 jupyter notebook 中的环境变量,我会得到None So my question is, is there a way to define environment variables in vscode's settings.json file, so whenever I start a new notebook, the environment variables are loaded by default.所以我的问题是,有没有办法在vscode的settings.json文件中定义环境变量,所以每当我启动一个新的notebook时,都会默认加载环境变量。

Currently the workaround I have found is to add the following code snippet in a top code cell.目前我发现的解决方法是在顶部代码单元格中添加以下代码片段。


import os
os.environ["MY_ENV"] = "test"
os.environ["MY_ENVTYPE"] = "qa"

I am hoping there is a better way to do the same.我希望有更好的方法来做同样的事情。

We could use python-dotenv to solve this problem.我们可以使用python-dotenv来解决这个问题。 Using "pip install python-dotenv" to install the package.使用“pip install python-dotenv”安装 package。 To configure the development environment Please add.env file in the root directory of the project:配置开发环境请在项目根目录下添加.env文件:

.
├── . env
└── test. py

Then we can use the following code to load environment:然后我们可以使用下面的代码来加载环境:

%load_ext dotenv
%dotenv

I am using the following command in settings.json to setup environment variables which are specific to just jupyter notebook.我在settings.json中使用以下命令来设置特定于 jupyter notebook 的环境变量。 Feels a bit hackish though.不过感觉有点hackish。

Using jupyter.runStartupCommands , I am executing bunch of python commands to define environment variables and load jupyter extension.使用jupyter.runStartupCommands ,我正在执行一堆 python 命令来定义环境变量并加载 jupyter 扩展。 Note each command is separated by a newline character.请注意,每个命令都由换行符分隔。

"jupyter.runStartupCommands": [
        "import os\nos.environ['MY_ENV']='mltest'\nos.environ['MY_ENVTYPE']='qa'\n%load_ext autoreload\n%autoreload 2"
    ]

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

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