Can't get VSCode/Python debugger to find my project modules
Asked Answered
U

8

48

I have a project and am trying to debug my main.py. I am really confused why I am getting the following error from the imports at the top of my file (only) when running the debugger:

Exception has occurred: ModuleNotFoundError
No module named 'bbb'
  File "/Users/maxepstein/myproject/bbb/train/__main__.py", line 8, in <module>
    from bbb.mysubfolder.myfile import myfunction

My project folder structure, as shown by these print statements (as shown by the debugger) confirms my 'bbb' module exists, and has an __init__.py:

import os
print(os.getcwd())
print(os.listdir())
print(os.listdir('bbb'))

/Users/maxepstein/myproject
['requirements.txt', 'bbb', 'resources', '__init__.py', 'readme.md', 'results', '.gitignore', '.git', '.vscode', 'bbenv']
['config', 'tests', '__init__.py', 'utils', 'predict', 'train']

I'm trying to debug as "debug current file - integrated terminal", below is the applicable debug settings from my debug settings.json. After searching online, I really thought adding "cwd": "/Users/maxepstein/myproject" below would be my solution but it hasn't helped.

"version": "0.2.0",
"configurations": [
    {
        "name": "Python: Current File (Integrated Terminal)",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "console": "integratedTerminal",
        "cwd": "/Users/maxepstein/myproject"
    }
Unbacked answered 13/11, 2018 at 22:15 Comment(0)
C
13

When I am debugging a Python module in VS Code I use the Module debug configuration instead of the Current File one. For you it might look like this:

{
    "name" : "Python: Module",
    "type" : "python",
    "request": "launch",
    "module": "bbb",
    "args": []
}

See the documentation https://code.visualstudio.com/docs/python/debugging

Also, in VS Code, these steps will auto-populate these settings for you:

Debug -> Add Configuration -> Python: Module

Chausses answered 14/11, 2018 at 16:12 Comment(5)
hey thanks for this answer. I'm actually trying to debug a my bbb.train module (the file I was in before was bbb/train/__main__.py, but am still getting No module named bbb.train when I run the debugger in Python: Module mode. Any idea why? When I run python -m bbb.train from an external shell at the same path the debugger seems to be in, it runs fine, which is confusing me...Unbacked
This is a known bug of not working with sub-packages.Asdic
Hi Brett, I got the debugger to run two days ago by explicitly adding the pythonpath to current folder as suggested in your github issue. I was just going to confirm that works again yesterday, but now am running into this new issue with the VSCode debugger: github.com/DonJayamanne/pythonVSCode/issues/1441Unbacked
FYI that's the wrong repo: you want github.com/microsoft/vscode-python .Asdic
I upvoted, as I think this is the closest to my issue, but now I'm getting "No module named blah.__main__; 'blah' is a package and cannot be directly executed" From the CLI, executing 'blah' works as it's been installed via packages, i.e. python -m pip install blah via pyproject.toml. To make matters worse, I have to execute 'blah' as sudo, so for now I've given up being able to debug it.Escapee
L
70

A simple workaround to the bug mentioned by @BrettCannon is to add the following env entry to the launch.json configuration:

{
    "version": "0.2.0",
    "configurations": [
        {
           "name": "Python: Current File",
           "type": "python",
           "request": "launch",
           "program": "${file}",
           "console": "integratedTerminal",
           "env": { "PYTHONPATH": "${workspaceRoot}"}
        }
    ]
}
Lido answered 5/8, 2020 at 19:6 Comment(8)
Please note, if one is using WSL, all the PYTHONPATH's are assumed to start in the C:/ directory and not in the mnt/ directory. At least I couldn't make it work using mnt.Latricelatricia
"env": { "PYTHONPATH": "${workspaceRoot}"} good workaround!Balsam
It pains me have to do this, but thank you for sharing it.Christeenchristel
I was using a virtual environment (.venv folder) and ran into a ModuleNotFound error with the debugger. This solved it.Soileau
how to find launch.jason: on the right panel, find Run&Debug. On the top you will find a drop down menu. Possibly writing "Python: Current File". Press and click on Add Configuration. It will open launch.jason. then follow the answerShewmaker
this is the only helpfull answer. **** with init.py didn't help me. Thank you.Saccharometer
I agree @AlexSham and what a nightmare I spent 3+ hours on SO with this problem, including putting my actual python path in that spot as many suggest. Only this exact above syntax solved the problem. To others with this issue:U should at least try this solution even if it seems unlikely to work.Mims
"env": { "PYTHONPATH": "${workspaceFolder}"} worked for me in 2022Abiosis
S
24

In my case, I quickly fixed it selecting the right interpreter: 
( The interpreter is shown at bottom-left or bottom-right, depending on the version. )

( The interpreter is shown at bottom-left or bottom-right, depending on the version. )

interpreter selection

Socket answered 17/10, 2021 at 18:29 Comment(4)
Awesome!! Saved my day. ThanksDichroic
Worked for me as well (on mac)! Opened command pallete manually (cmd+shift+p). Used pipenv --venv to find location.Sennacherib
Best answer imho but the UI changed, the Interpreter selection is now on the right corner.Maniple
Worked with Conda Environment too. Used (Ctrl+Shift+P) and typed "Select Interpreter"Capua
M
15

Had the same problem when importing from a nested directory, and fixed it by appending to the env variable PYTHONPATH:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "cwd": "${workspaceFolder}",
            "env": {
                "PYTHONPATH":"${PYTHONPATH}:/home/maxepstein/myproject/"
            }
        }
    ]
}
Mcspadden answered 17/3, 2020 at 12:23 Comment(0)
C
13

When I am debugging a Python module in VS Code I use the Module debug configuration instead of the Current File one. For you it might look like this:

{
    "name" : "Python: Module",
    "type" : "python",
    "request": "launch",
    "module": "bbb",
    "args": []
}

See the documentation https://code.visualstudio.com/docs/python/debugging

Also, in VS Code, these steps will auto-populate these settings for you:

Debug -> Add Configuration -> Python: Module

Chausses answered 14/11, 2018 at 16:12 Comment(5)
hey thanks for this answer. I'm actually trying to debug a my bbb.train module (the file I was in before was bbb/train/__main__.py, but am still getting No module named bbb.train when I run the debugger in Python: Module mode. Any idea why? When I run python -m bbb.train from an external shell at the same path the debugger seems to be in, it runs fine, which is confusing me...Unbacked
This is a known bug of not working with sub-packages.Asdic
Hi Brett, I got the debugger to run two days ago by explicitly adding the pythonpath to current folder as suggested in your github issue. I was just going to confirm that works again yesterday, but now am running into this new issue with the VSCode debugger: github.com/DonJayamanne/pythonVSCode/issues/1441Unbacked
FYI that's the wrong repo: you want github.com/microsoft/vscode-python .Asdic
I upvoted, as I think this is the closest to my issue, but now I'm getting "No module named blah.__main__; 'blah' is a package and cannot be directly executed" From the CLI, executing 'blah' works as it's been installed via packages, i.e. python -m pip install blah via pyproject.toml. To make matters worse, I have to execute 'blah' as sudo, so for now I've given up being able to debug it.Escapee
D
4

You can use the current file debug configuration. In the file you're debugging that's importing the modules add the full path to the modules you're trying to import to your system path.

sys.path.append('/Users/my_repos/hw/assignment')
import src.network as network

The module here is src, located in the assignment directory.

Duhamel answered 7/2, 2020 at 17:39 Comment(1)
path to my project folder - if I am testing a py file in a sub folder ... import sys before sys.path.append('path to project') then all Module import worked. Thanks garyAffection
A
4

I run the debugger from VS Code. My structure in VS code:

myproject
+vscode
+---launch.json
|
+src
+---test/
+------MainTest.py
+---Main.py

the launch.json that saved me:

{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "python",
            "request": "launch",
            "program": "${file}",
            "env": {"PYTHONPATH": "${workspaceRoot}:src"},
            "console": "integratedTerminal"
        }
    ]
}
Arrest answered 29/1, 2021 at 19:7 Comment(0)
B
2

Based on the other answers, I had to change my launch.json to the following to be able to successfully debug any arbitrary python module I'd written in my project (by hitting F5 to start debugging with my .py file as VSCode's active file). Otherwise, I'd run into the same "ModuleNotFoundError" when the file tried to import from a different custom module.
OS = Ubuntu 20.04 (WSL2)

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "debug-my-code",
            "type": "python",
            "python": "/home/<user>/<path/to/my/repo>/.venv/bin/python",
            "request": "launch",
            "program": "${relativeFileDirname}/${fileBasename}",
            "purpose": ["debug-test"],
            "console": "integratedTerminal",
            "justMyCode": true,
            "env": {"PYTHONPATH": "/home/<user>/<path/to/my/repo>"},
        }
    ]
}

Notes

  • I had to put the full absolute path to my venv python as the python path - even using ~ in place of /home/user/ was rejected
  • similarly, I had to put the full absolute path to my repo in the PYTHONPATH environment variable
  • For the program I needed to specify the relative path to the file I was debugging, relative to the repo root.

E.g. if the file I'm trying to debug is <repo-root>/src/data/process.py, then "${relativeFileDirname}" gets me src/data, while "${fileBasename}" adds on the specific module process.py

Hope this helps someone. I tried many other combinations but this was the only one to finally work.

Balinese answered 7/3, 2023 at 6:29 Comment(1)
setting the env worked for me, but this seems like a bug with the python extension, since it seems to just ignore the "python"; one potentially relevant observation i made is that this only happens to my tasks which run modules with a __main__.py, running a fastapi server with "module": "uvicorn" pointing to a __init__.py uses the "python" as expectedProthalamium
S
1

Perhaps you have not changed the interpreter of the debugger. Click on the interpreter and choose the right one:

Click the interpreter and choose the right one

Subatomic answered 13/11, 2023 at 2:42 Comment(1)
This is exactly the same as @pmlks answer above but with a more recent screenshot.Maniple

© 2022 - 2025 — McMap. All rights reserved.