6

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 Answers1

4

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;
  };
Stefan
  • 10,010
  • 7
  • 61
  • 117
  • is there a way if I can wrap this into a function and return the result when function execute – jax Nov 04 '21 at 15:48
  • Yes, you could wrap it in a promise. Also see async method executePythonCode(pythonCode, isExpectingOutput) here: https://github.com/stefaneidelloth/treezjs/blob/master/jupyter_lab_extension/jupyterLabTerminal.js – Stefan Nov 04 '21 at 15:53
  • My big concern here is to return the resuls when a function called. I can dig into it. However new to javascript, don't know much about async and promise. thanks – jax Nov 04 '21 at 17:03
  • @ Stefan thanks a lot it worked perfectly :) – jax Nov 04 '21 at 17:52