skip to Main Content

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?

2

Answers


  1. 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.

    Login or Signup to reply.
  2. You must have the Code Runner extension installed because the Run Code option is provided by the Code Runner extension.

    The triangle button for running code in the upper right corner has three options, among which Run Code is the way to run code provided by the Code Runner extension, while Run Python File and Debug Python File are the way to run and debug code provided by Microsoft’s official extension Python.

    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)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search