Visual Studio Code -交互式窗口:即使安装了jupyter,更改环境也不起作用 &



我的问题是这样的:如何在Vscode上更改Python Interactive的环境?,但提供的解决方案似乎对我不起作用。

我在Ubuntu 20.10上,使用从snap store安装的Visual Studio Code 1.53.2。

为了调试它,我使用conda:

重新创建了我的环境:
name: mytrips
channels:
- defaults
- conda-forge
dependencies:
- python=3.8.*
- pip
- numpy==1.19.*
- pandas==1.2.*
- cartopy==0.18.*
- jupyterlab

(我已经把jupyterlab放在那里,所以应该有交互窗口所需的所有依赖项)。

在左下角,解释器被正确地设置为环境"mytrips"。我使用的测试脚本只包含以下两行:

import cartopy

print(cartopy.__version__)

当我右键单击并选择"运行python文件在终端",这是(正确的)发生的事情:

source /home/rick/anaconda3/bin/activate
(base) rick@linux:~/Documents/src/My trips$ source /home/rick/anaconda3/bin/activate
(base) rick@linux:~/Documents/src/My trips$ conda activate mytrips
(mytrips) rick@linux:~/Documents/src/My trips$ /home/rick/anaconda3/envs/mytrips/bin/python "/home/rick/Documents/src/My trips/test.py"
0.18.0

你可以看到cartopy被正确导入了

当我按shift+Enter,或右键单击并选择在交互窗口中运行当前文件时,它返回ModuleNotFoundError: No module named 'cartopy',因为它从基本conda环境中使用python。问题1:我的环境中有jupyter,但它的行为好像没有检测到。

然后,当我点击交互窗口的右上角并选择mytrips环境时,交互窗口打印出以下内容,就好像它刚刚更改了环境一样:

Started 'Python 3' kernel
Python 3.8.6 (default, Sep 25 2020, 09:36:53) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.20.0 -- An enhanced Interactive Python. Type '?' for help.

但是仍然不能导入cartopy,如果我在交互式窗口中检查它现在使用的可执行文件,结果是:

import sys
sys.executable
'usr/bin/python3'

这就是问题2:交互窗口实际上并没有改变我的环境。

为了确认,这里有证据证明环境中有jupytercartopy:

(mytrips) rick@linux:~/Documents/src/My trips$ conda list | grep jupyter
jupyter_client            6.1.7                      py_0  
jupyter_core              4.7.1            py38h06a4308_0  
jupyterlab                2.2.6                      py_0  
jupyterlab_pygments       0.1.2                      py_0  
jupyterlab_server         1.2.0                      py_0  
(mytrips) rick@linux:~/Documents/src/My trips$ conda list | grep ipython
ipython                   7.20.0           py38hb070fc8_1  
ipython_genutils          0.2.0              pyhd3eb1b0_1 
(mytrips) rick@linux:~/Documents/src/My trips$ conda list | grep cartopy
cartopy                   0.18.0           py38h0d9ca2b_1

有什么提示吗?

似乎是最近的问题,已经在VSCode-Jupyter github上出现了几个问题。主线程是下面的链接。我还在这个链接中评论了我的解决方法。

https://github.com/microsoft/vscode-jupyter/issues/4831