Search code examples
pythonvisual-studio-codeflaskvscode-debuggervscode-tasks

Attach a debugger to a flask process started by tasks.json in vscode


I have the following tasks.json in my workspace:

{
    "version": "2.0.0",
    "tasks": [
        {
            "label": "Run Locally",
            "dependsOn": ["Run Backend", "Run Frontend"],
            "dependsOrder": "parallel",
        },
        {
            "label": "Run Frontend",
            "type": "shell",
            "options": {
                "cwd": "${workspaceFolder}/frontend"
            },
            "runOptions": {
                "runOn": "folderOpen"
            },
            "command": "npm",
            "args": ["run", "dev"],
            "presentation": {
                "panel": "dedicated"
            }
        },
        {
            "label": "Run Backend",
            "options": {
                "cwd": "${workspaceFolder}/backend"
            },
            "runOptions": {
                "runOn": "folderOpen"
            },
            "command": "python",
            "args": ["-m", "flask", "--debug", "--app", "main", "run"],
            "presentation": {
                "panel": "dedicated"
            }
        },
        
    ]
}

When I open vscode, it starts two terminals: one running the react frontend with npm run dev and another running the flask application with python -m flask --debug --app main run.

What I'm trying to do is to attach the VSCode debugger to the flask process so when I create a breakpoint I can debug the variables, is this even possible?

All solutions I found point to using launch.json, but if possible I'd like to keep this in tasks because it runs automatically when I open VSCode


Solution

  • This is possible. And you can read more about this below:

    https://code.visualstudio.com/docs/python/debugging#_additional-configurations

    Simply create an entry in the launch.json file like so:

    {
        "name": "Python Debugger: Attach using Process Id",
        "type": "debugpy",
        "request": "attach",
        "processId": "${command:pickProcess}"
    }
    

    Select your flask app's process id whenever it asks you to select a process id to attach to.


    Note: for Linux users an additional step could be necessary:

    echo 0 | sudo tee /proc/sys/kernel/yama/ptrace_scope