Search code examples
pythonvisual-studio-codebazelvscode-debugger

How to use the vscode python debugger with a project built with bazel?


I want to debug a python file which has a few dependencies that only appear in the runfiles from bazel. How can I debug a bazel build with the vscode debugger?


Solution

  • As someone famous said, "Yes, we can".

    You would need to use the "ptvsd" python package.

    One-time Setup

    • Add "ptvsd" as a Python dependency in Bazel
    • In VS Code, in your launch.json file, add the following configuration:
    {
        "name": "Python: Attach",
        "type": "python",
        "request": "attach",
        "port": 5724,
        "host": "localhost"
    },
    

    Debug

    When you want to debug a specific file:

    • In the Python file you want to debug, add the following lines:
    import ptvsd
    ptvsd.enable_attach(address=('localhost', 5724), redirect_output=True)
    print('Now is a good time to attach your debugger: Run: Python: Attach')
    ptvsd.wait_for_attach()
    
    • Run Bazel on this file as you normally would (bazel run :server for instance)
    • Execution will stop at "Now is a good time to attach your debugger: Run: Python: Attach"
    • In VS Code, click on the "Python: Attach" debug option that we setup earlier:

    Python attach button

    • That's it!

    Feel free to change the port, 5724 in this example.