Search code examples
pythonvisual-studio-codeattach-to-process

VSCode debugger attach to local process


One of the great features of PyCharm is that it allows its debugger to attach to python processes running locally (and outside of the IDE).

As I am trying to move to VSCode to work in Python, I am struggling to configure launch.json to simulate PyCharm's attach to local process feature.

{
    "name": "Python: Attach",
    "type": "python",
    "request": "attach",
    "localRoot": "${workspaceFolder}",
    "remoteRoot": "${workspaceFolder}",
    "port": 8001,
    "secret": "my_secret",
    "host": "localhost"
},

This configuration is created by default when I select Python: attach option for debugger but I am convinced this is for remote debugging (with port and all), and most Google search results just talk about remote debugging for Python with VSCode.

Anyone had success in attaching a local debugger or two to multiple python processes running locally?


Solution

  • It seems that VSCode may have added this feature since the last answer was posted.

    In the docs under "Basic Debugging", they explain the process:

    The simplest way to begin debugging a Python file is to use the Run view and click the Run and Debug button. When no configuration has been previously set, you will be presented with a list of debugging options. Select the appropriate option to quickly begin debugging your code.

    Two common options are to use the Python File configuration to run the currently open Python file or to use the Attach using Process ID configuration to attach the debugger to a process that is already running.

    So in your case, you'd select the "Run" tab on the left, then "Run and Debug". You'll be prompted to "Select a debug configuration". Since you are trying to attach to an existing/already running script, select "Attach using Process ID". Then select the Python thread you would like to attach to.

    I just tried this on my machine (VS Code version 1.45.0 and Python Extension version 2020.4.76186) and was able to attach to a running process.