Search code examples
pythonvisual-studio-codejupyterpython-venvvirtual-environment

Jupyter refuses to load virtual environment in VS Code interactive mode


After getting ModuleNotFoundError when trying to load packages in python interactive mode in VS Code, I now suspect that the current virtual environment is not loading correctly when in the Jupyter Kernel, although I have selected it in the upper right dropdown (see screenshot).

selected environment

I therefore ran a cell with

import os
os.environ['VIRTUAL_ENV']

and got


import os...
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
c:\Users\user\OneDrive\Desktop\aig\decoding_methods.py in 
      2 import os
----> 3 os.environ['VIRTUAL_ENV']

C:\Python37\lib\os.py in __getitem__(self, key)
    679         except KeyError:
    680             # raise KeyError with the original key value
--> 681             raise KeyError(key) from None
    682         return self.decodevalue(value)
    683 

KeyError: 'VIRTUAL_ENV'

indicating that the virtual environment indeed is not loading. There's no problem loading the environment and the modules in the console. Is this a bug or am I doing something wrong?


Solution

  • The solution was to re-install the kernel, but specifying the --name flag:

    So first: pip install ipykernel followed by

    python -m ipykernel install --user --name=myenv

    Source