Browse 536 attributed reviews, viewable separately for our classroom and online training
Python ModuleNotFoundError in VS Code using Code Runner
How to solve the problem that Visual Studio Code can't find a module that you've imported.

Posted by Andy Brown on 08 October 2021

You need a minimum screen resolution of about 700 pixels width to see our blogs. This is because they contain diagrams and tables which would not be viewable easily on a mobile phone or small laptop. Please use a larger tablet, notebook or desktop computer, or change your screen resolution settings.

Python ModuleNotFoundError in VS Code using Code Runner

So you're using Visual Studio Code to run Python programs using virtual environments, and you see this error when you run a script importing a module:

Any module not found

The module name then appears in the quotation marks.

You are certain that:

  • You've set up your virtual environment correctly.
  • You've activated it.
  • You've installed the module within the virtual environment.
  • You've read every single StackOverflow article on the web about this.

You know that you can solve the problem by running this command, but you want a more permanent solution:

sys.path.append("Path to your modules here")

Try pressing Ctrl + F5 to run your program.  Does this work?  If so, maybe the problem is with the Code Runner extension that you're using.

If you usually run your programs by pressing Alt + Ctrl + N, you almost certainly are using Code Runner.

To solve this, press Ctrl + , to load up your settings, and if necessary click on this icon to go into JSON view:

JSON view

Click on this icon at the top right of your Visual Studio Code window to see your settings as JSON text.

 

Add this text in:

The text to add

Add this to the bottom of your file, making sure that you put a comma at the end of the previous setting.

Here's the setting if you want to copy it:

"code-runner.executorMap": {

"python": "$pythonPath -u $fullFileName"

}

Note that one delegate (thanks, Michael) reported that the $pythonPath needed to be included in quotation marks, like this:

PythonPath in quotes

However, I didn't need to do this.

If this worked, you've solved your problem!  It did for me, although not before I'd tried too many other solutions involving .env files, .path files, launch.json settings, the PythonPath environment variable and other esoteric options.  Now what was I doing previously?!

I got this information from this blog, which will tell you more about how and why this solution works. 

This blog has 0 threads Add post