Categories
Jupyter lab

How to attach vscode debugger to a Jupyterlab python extension

In this post I explain how I have managed to attach the VSCode debugger to a running jupyterlab 3 extension.

If you’re developing extensions for Jupyterlab 3 with python, it can be challenging to debug it running from a remote server (in my case, the extension is running in a Docker container). Using debugpy (version 1.6.4) it is possible to attach the VSCode debugger to the process.

First, jupyter_server_config.py needs to have debug set to True:

c.ServerApp.debug = True

In my case, since jupyterlab is running in a container I had to open a port for the debugger to connect through. I’ve picked 8800.

In VSCode, I then created a new debug configuration as follow (launch.json file):


{
    // Use IntelliSense to learn about possible attributes.
    // Hover to view descriptions of existing attributes.
    // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Python: Remote Attach",
            "type": "python",
            "request": "attach",
            "host": "localhost",
            "port": 8800,
            "pathMappings": [
                {
                    "localRoot": "${workspaceFolder}",
                    "remoteRoot": "/opt/extensions/custom_api_extension "
                }
            ]
        }
    ]
}

Finally, in my extension I’ve created a function attach_debugger and called it in the __init__.py file:


def attach_debugger():
    print('Attaching debugger')
    import debugpy
    # This is to work with hot-reload
    debugpy.configure(subProcess=False)
    debugpy.listen(("0.0.0.0", 8800))



def _load_jupyter_server_extension(server_app):
    server_app.log.info("--------- Starting custom API ---------")

    # If you have a config file for your extension, you can map it this way:
    config = CustomApiConfig(config=server_app.config)

    # Optional condition, used to keep the debugger out of the prod module
    if config.debug:
        attach_debugger()

    ...


 

That’s it, it’s now possible to attach VSCode’s debugger to jupyterlab and debug using breakpoints.

Leave a Reply

Your email address will not be published. Required fields are marked *