Visual Studio Code - ModuleNotFoundError, different sys.path in terminal and VSCode?

1.1k views Asked by At

I try running code in Visual Studio code but I keep getting a ModuleNotFoundError. When I run the code in my terminal or in debug mode in VS with the activated conda environment it works fine.

System: Mac M1 12.3

Conda Environment, selected in Visual Studio Code.

I have added this

import os
print('cwd is %s' %(os.getcwd()))
import sys
print('executable is %s' %(sys.executable))
print('path is %s' %(sys.path))

and running in terminal gives:

cwd is /Users/USERNAME/xyz/CodeFolder
executable is /Users/USERNAME/miniforge3/envs/conda_envNAME/bin/python
path is ['/Users/USERNAME/xyz/CodeFolder', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python38.zip', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python3.8', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python3.8/lib-dynload', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python3.8/site-packages']

running in VS via Run Python File (upper right corner button) gives:

cwd is /Users/USERNAME/xyz/CodeFolder
executable is /Users/USERNAME/miniforge3/bin/python
path is ['/Users/USERNAME/xyz/CodeFolder', '/Users/USERNAME/miniforge3/lib/python39.zip', '/Users/USERNAME/miniforge3/lib/python3.9', '/Users/USERNAME/miniforge3/lib/python3.9/lib-dynload', '/Users/USERNAME/miniforge3/lib/python3.9/site-packages']

running in VS via Debug Python File (upper right corner button) gives:

cwd is /Users/USERNAME/xyz/CodeFolder
executable is /Users/USERNAME/miniforge3/envs/conda_envNAME/bin/python
path is ['/Users/USERNAME/xyz/CodeFolder', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python38.zip', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python3.8', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python3.8/lib-dynload', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python3.8/site-packages']

I am confused - How can I get this running in VS Code?

---- Update March 23 2022:

I have three options enter image description here

When I add

    "code-runner.executorMap": {

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

to

settings.json

(see [https://www.wiseowl.co.uk/blog/s2930/module-not-found-error.htm] 2 from @Kyouya Sato)

and run Run Code it works and I also get

cwd is /Users/USERNAME/xyz/CodeFolder
executable is /Users/USERNAME/miniforge3/envs/conda_envNAME/bin/python
path is ['/Users/USERNAME/xyz/CodeFolder', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python38.zip', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python3.8', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python3.8/lib-dynload', '/Users/USERNAME/miniforge3/envs/conda_envNAME/lib/python3.8/site-packages']

without changing

settings.json

it does also not work using Run Code.

Run Python File is not working at all.

1

There are 1 answers