How do I interact a JupyterLab extension with Python kernel?

Viewed 859

Is there a way to create an extension for Jupyter Lab that I can manipulate through the Python cells in my notebook?

In Jupyter Notebook, this could be achieved via an IPywidget, which had a Python backend and Javascript front-end. These two could interact, and so I could send instructions to the javascript front-end via Python, and vice-versa.

From what I understand, this is no longer possible in Jupyter Lab, since they disabled the feature to execute javascript via IPython. The recommendation is to create jupyterlab extensions. Is it possible to control such an extension via Python code, and if so how?

In a simple example, I want a sidebar (like the TOC extension) that contains a textbox whose text I can set via Python.

1 Answers

A. Python to JavaScript

Have a look at https://opensourcelibs.com/lib/ipylab

"Control JupyterLab from Python notebooks."

from ipylab import JupyterFrontEnd
app = JupyterFrontEnd()
...

In some cases a possible workaround might be to observe the python cells using the javascript extension and if the python code changes, check if the extension needs to adapt accordingly.

Related:

How to use events in jupyterlab extensions?

B. JavaScript to Python

"ConsolePanel and NotebookPanel now expose a sessionContext: ISessionContext attribute that allows for a uniform way to interact with kernel sessions." Source: https://jupyterlab.readthedocs.io/en/stable/extension/extension_migration.html?highlight=migration#using-session-and-sessioncontext-to-manage-kernel-sessions

Here is an example about kernel messaging:

https://github.com/jupyterlab/extension-examples/tree/master/kernel-messaging

var notebookPanel = this.__getFirstVisibleNotebookPanel(app);   
var sessionContext = notebookPanel.sessionContext;
var kernelConnection = sessionContext.session.kernel;
var future = kernelConnection.requestExecute('1+3');
future.onIOPub  = (msg) => {
    const msgType = msg.header.msg_type;
    switch (msgType) {
      case 'execute_result':
      case 'display_data':
      case 'update_display_data':
        var result = msg.content;
        console.log(result);       
        break;
      default:
        break;
    }
    return;
  };
Related