0

Here's my directory structure -

src
    Main.py
    Message.py
    ...
    __init__.py

In Main.py, I have an import statement import src.Message. This works fine when I execute the file on my own using the command python3 -m src.Main.py

However, when I use the VS code debugger to do the same, I get a ModuleNotFoundException.

I assumed that this was because the debugger doesn't use the -m flag, so I used the run Module configuration in the VS Code debugger.

I entered src.Main.py in that, and while the program does start, the debugger is unable to connect to it, and I get an error a few seconds later.

error message

2 Answers 2

4

The problem was the parent folder of 'src' has not been added to the sys.path.

You run python3 -m src.Main.py under the location of src's parent folder, is that right? Then the location of src's parent folder will be added to the sys.path.

So, you need to configure the launch.json file in order to add the related path to the sys.path.

If you open the folder of src in the VSCode:

  "env": {
    "PYTHONPATH": "../"
  },

If you open the folder of src's parent in the VSCode:

  "env": {
    "PYTHONPATH": "${workspaceFolder}"
  },

The launch.json will be looks like this:

"configurations": [
    {
        "name": "Python: Current File",
        "type": "python",
        "request": "launch",
        "program": "${file}",
        "console": "integratedTerminal",
        "env": {
            "PYTHONPATH": "${workspaceFolder}"
          },
    }
]
Sign up to request clarification or add additional context in comments.

Comments

2

If you're going to debug a Module in VSCode, you don't include the .py file extension (only src.Main). In your case, your launch.json file should look like this:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Module",  // Whatever name you see fit!
            "type": "python",
            "request": "launch",
            "module": "src.Main"
        }
    ]
}

An alternative configuration based on the directory instead of the module name:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python Program",  // Whatever name you see fit!
            "type": "python",
            "request": "launch",
            "program": "${workspaceRoot}/src/Main.py",
            "console": "integratedTerminal"
        }
    ]
}

For more information on Python debugging configuration, you can check this link

1 Comment

@dumbPotato21 If you have multiple module you want to debug you can use extension Command Variable and the command extension.commandvariable.file.relativeDirDots to get a dot separated path to the file

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.