37

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"
    }
halfer
  • 19,824
  • 17
  • 99
  • 186
Max Power
  • 8,265
  • 13
  • 50
  • 91

7 Answers7

52

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}"}
        }
    ]
}
James Hirschorn
  • 7,032
  • 5
  • 45
  • 53
  • 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. – asa Jan 18 '21 at 10:03
  • 2
    `"env": { "PYTHONPATH": "${workspaceRoot}"}` good workaround! – R.Liu Feb 03 '21 at 07:06
  • It pains me have to do this, but thank you for sharing it. – rsmith54 Apr 22 '21 at 20:36
  • 1
    I was using a virtual environment (.venv folder) and ran into a `ModuleNotFound` error with the debugger. This solved it. – abk Oct 08 '21 at 04:10
  • 1
    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 answer – Melih Dal Dec 24 '21 at 19:22
  • this is the only helpfull answer. **** with __init.py__ didn't help me. Thank you. – Alex Sham Apr 19 '22 at 12:51
  • 2
    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. – Mote Zart May 18 '22 at 22:16
  • `"env": { "PYTHONPATH": "${workspaceFolder}"}` worked for me in 2022 – D10001 Oct 12 '22 at 22:05
13

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/"
            }
        }
    ]
}
JBSnorro
  • 6,048
  • 3
  • 41
  • 62
13

In my case, I quickly fixed it selecting the right interpreter: enter image description here

enter image description here

plmk
  • 2,194
  • 1
  • 15
  • 21
9

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

epak96
  • 306
  • 2
  • 7
  • 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... – Max Power Nov 14 '18 at 16:59
  • 3
    This is a [known bug](https://github.com/Microsoft/ptvsd/issues/1010) of not working with sub-packages. – Brett Cannon Nov 14 '18 at 20:41
  • 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: https://github.com/DonJayamanne/pythonVSCode/issues/1441 – Max Power Nov 15 '18 at 17:41
  • FYI that's the wrong repo: you want github.com/microsoft/vscode-python . – Brett Cannon Nov 19 '18 at 20:24
  • 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. – J. Gwinner Sep 20 '22 at 00:42
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.

gary69
  • 3,620
  • 6
  • 36
  • 50
  • 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 gary – Abdeali Chandanwala Apr 15 '20 at 15:23
2

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"
        }
    ]
}
Gino Ureta
  • 21
  • 1
0

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.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
capohugo
  • 111
  • 1
  • 2