Home > Back-end >  Module import errors with Virtual Environments and VSCode
Module import errors with Virtual Environments and VSCode

Time:10-28

I have created a virtual environment to install some Python modules. I am using mini-conda to manage and activate the environments.

One issue that I am facing is that the code runs fine when I run it through the terminal with the virtual environment activated.

However, the same code does not run when I use the "Run Code" button (Ctrl Alt N) in VSCode. It gives me Module Not Found Error.

How can I run the code from VSCode in the context of my virtual environment?

CodePudding user response:

You should use the same interpreter in VSCode; To do this you should use Python: Select Interpreter option; CTRL Shift p(default key-bindings) and search for Python: Select Interpreter or search for it in the VSCode settings.

CodePudding user response:

You must have the enter image description here

Running the code with the Run Code option will run the code with the Code Runner extension. And Code Runner does not change the interpreter as you select a different interpreter in the Select Interpreter panel. It seems to always use the preferred interpreter from the system environment variables.

So although you are in a virtual environment and have some packages installed. But when you run code with Run Code, the interpreter is not the virtual environment of your choice. Although you have selected the virtual environment interpreter in the selection panel, this is only valid for Run Python File and Debug Python File provided by the Python extension.

So, run the code with the Run Python File option provided by the Python extension. Or install the packages you need for the interpreter environment currently used by Code Runner.

You can check the currently used interpreter with the following code

import sys
print(sys.executable)
  • Related