Bondgirl
Bondgirl

Reputation: 115

Explain launch.json for vscode and debugging in python

since forever, I have been struggling with the launch.json in vscode. Every time with a new project (structure) I do not understand why it's not working how I want it to. Can someone explain in a general way how to do that? The meaning of the must-have arguments and how that works.

As an example I would like to give following structure:

workpace
|   .vscode
│   ├── launch.json
│   └── settings.json
└── tree
    ├── branch1
         ├── leaf1
         └── leaf2
               ├── pyhelp.py
               └── pytest.py   

Maybe this is giving it some extra complexity but assume I want to debug a pytest. So, when cd into leaf2 and running

pytest pytest.py

from the terminal everything works fine. Running

~/workspace/tree/branch1/leaf2$ python /pytest.py 

does not work. (ModuleNotFoundError: No module named 'leaf2.pyhelp')

Opening the pytest.py in VS Code and using the debugger, does not either. First error gives me

Exception has occurred: ModuleNotFoundError

No module named 'leaf2.pyhelp'

Within the script I am doing:

from leaf2.pyhelp import something

I figured the sub import (leaf2.pyhelp) is a problem.

from test import *

works.

My launch.json has been changed back and forth. I changed a lot without any clue..apparently. Still here is the structure:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Current File",
            "type": "debugpy",
            "request": "launch",
            "program": "${file}",
            "console": "integratedTerminal",
            "justMyCode": false,
            "cwd": "${workspaceFolder}/tree/branch1/"
            }

I use a poetry environment that is not stored within the repo. Actually I really don't know where the problem is. Not sure if it's the launch.json or has something to do with different handling of pytest. What happens when I call "python script.py" in terminal and what is different when running a code with pytest script.py? When printing the sys.path they seem to have the same directories to check...

Any help is much appreciated!

Upvotes: -1

Views: 275

Answers (1)

MingJie-MSFT
MingJie-MSFT

Reputation: 9437

You could create a .env file under your workspace.

Add the PYTHONPATH of your leaf2. Then add the following codes to your settings.json:

"python.envFile": "${workspaceFolder}/.env",

Upvotes: 1

Related Questions