Search code examples
pythonvisual-studio-codepippython-import

VSCode: import of pip3-installed modules suddenly quit working


I have been developing in a certain folder for months, undre python 3.10. Today, suddenly, VS code thinks that my imported modules don't exist. In particular, any that were installed by pip3. The same is true of an actual python process running in that context. But pip thinks they're installed!

Possible culprit: a few days ago a package wouldn't install, and in a bit of haste and frustration I said "sudo pip3 install ..." Apparently a bad idea. Today I uninstalled all those pieces that I had installed, and made sure that everything under my site-packages folder belongs to my user. Didn't help.

Deleting pycache from my working folder didn't help.

Now here's the stumper: I created a new folder and into it wrote the following tiny program:

import numpy, cv2, PIL
print("success")

It works great, with or without the intervention of VScode!

Here's the relevant part of my launch.json, in case it could be somehow creating a strange environment. The environment variable MOCK is recognized by my code, shouldn't be an issue anywhere else, right? It certainly isn't new.

{
        "name": "UIServer",
        "type": "python",
        "request": "launch",
        "program": "${workspaceFolder}/UIServer.py",
        "console": "integratedTerminal",
        "justMyCode": false,
        "env": {
            "MOCK": "true"
          },
     },

enter image description here


Solution

  • I think this was caused by the incorrect python interpreter.

    From the pictures you posted, we can see that your Python package was installed in Python 3.9, while you are using Python 3.8 in vscode.

    enter image description here

    You can use shortcuts "Ctrl+Shift+P" and type "Python: Select Interpreter" to choose the interpreter python 3.9 which you installed the python package in.

    At the same time, I recommend users to try creating virtual environments (conda or venv), which is more convenient for managing Python packages.