17

My Python project folder structure is as follow:

.python_practice
|--lib
    |--lib.py
    |--__init__.py
|--practice1
    |--my_module.py
    |--__init__.py
|--__init__.py

My launch configuration is

{
    "name": "Python: Module",
    "type": "python",
    "request": "launch",
    "module": "practice1.my_module",
    "console": "integratedTerminal"
 },

In my_module.py

from lib.lib import util_func

When I try to debug using VScode I get an error: "No module named practice1.my_module"

But when I run it with the following command it works fine

python -m practice1.my_module

How could I debug my code so that the relative import work?

Any help will be appreciated, thank you.

Leo Liu
  • 71,098
  • 10
  • 114
  • 135
Dev Khadka
  • 5,142
  • 4
  • 19
  • 33

4 Answers4

7

You can try the following:

{
    "name": "Python: A name example",
    "type": "python",
    "request": "launch",
    "program": "practice1/my_module.py",
    "env": {
        "PYTHONPATH": "${workspaceFolder}"
    },
}
  • Using program instead of module is almost the same.
  • You need to solve the imports as if you had the package installed. Therfore you need to add a PYTHONPATH.
BorjaEst
  • 390
  • 2
  • 11
  • To find where to modfiy this, press ctrl+ shift + p and enter launch.json > click on 'Open launch.json'. Or just click on the cogwheel at the top of the run and debug side-bar. Or command pallette Run > Open Configurations. – Matthias Arras Mar 22 '23 at 14:09
  • Additionally, if your project is installable, you should be able to `pip install -e .` so that it is `--editable` but installed and your modules accesible. – BorjaEst May 11 '23 at 09:38
  • for multiple `pythonpath`, see https://stackoverflow.com/questions/41471578/visual-studio-code-how-to-add-multiple-paths-to-python-path , for `args` see https://stackoverflow.com/questions/51244223/visual-studio-code-how-debug-python-script-with-arguments – yu yang Jian Jul 02 '23 at 05:18
3

This is a known bug involving debugging sub-modules.

Brett Cannon
  • 14,438
  • 3
  • 45
  • 40
3

I have ran into the same issue. You may have two Python interpreters installed and only one has the modules you need. Try selecting another Python version by running from the command pallet (Ctl+Shift+p) then python: Select Interpreter and choose where your python lives. I had:

/usr/bin/python3
/usr/local/bin/python
jmontenegro
  • 301
  • 4
  • 10
2

add env variable "PYTHONPATH" point to my app folder (where my app.py exist)
fixed my problem

{
      "name": "Python: Debugging App",
      "type": "python",
      "request": "launch",
      "program": "app/app.py",
      "console": "integratedTerminal",
      "justMyCode": true,
      "env": {
        "PYTHONPATH": "${workspaceFolder}/app"
      }
},
ofir_aghai
  • 3,017
  • 1
  • 37
  • 43