You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JupyterLab扩展的activate方法中访问Notebook?

Accessing the Current Notebook in JupyterLab (vs Jupyter Notebook)

Hey there, making the jump from Jupyter Notebook to JupyterLab means ditching that global Jupyter object approach—JupyterLab uses a more modular, service-based architecture instead. Let's fix that getNotebook function for your plugin.

First, you need to tap into JupyterLab's service system, specifically the notebook panel tracker that keeps tabs on open notebooks. Here's how to adjust your code:

module.exports = [{
  id: 'jupyterlab_workspace_module',
  autoStart: true,
  // Declare dependencies on the services we need
  requires: ['@jupyterlab/notebook', '@jupyterlab/apputils'],
  activate: function(app) {
    // Grab the notebook panel tracker from the service manager
    const notebookTracker = app.serviceManager.getService('@jupyterlab/notebook').tracker;

    // Implement your getNotebook function
    function getNotebook() {
      // Get the currently active notebook panel
      const activePanel = notebookTracker.currentWidget;
      if (!activePanel) {
        return null; // Return null if no notebook is open/active
      }
      // The actual notebook instance lives in the panel's content property
      return activePanel.content;
    }

    // Example usage
    const notebook = getNotebook();
    if (notebook) {
      // Replace notebook.get_cells()[0] with notebook.widgets[0]
      const firstCell = notebook.widgets[0];
      console.log('First cell in active notebook:', firstCell);
    }

    // Bonus: Listen for when the active notebook changes
    notebookTracker.currentChanged.connect((_, newPanel) => {
      if (newPanel) {
        const updatedNotebook = newPanel.content;
        // Do something when the user switches to a different notebook
      }
    });
  }
}];

Key Differences from Jupyter Notebook:

  • No global Jupyter.notebook—instead, we use the notebookTracker to get the active notebook panel.
  • The notebook's cells are stored in the widgets array (instead of calling get_cells()).
  • You need to declare dependencies on the services your plugin uses (like @jupyterlab/notebook) so JupyterLab loads those services before your plugin activates.

If you run into issues where the tracker isn't available, double-check that you've added the correct dependencies in your plugin's requires array—this ensures JupyterLab injects the necessary services properly.

内容的提问来源于stack exchange,提问作者Stefan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 17:37:44