如何在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 thenotebookTrackerto get the active notebook panel. - The notebook's cells are stored in the
widgetsarray (instead of callingget_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
相关产品推荐
相关产品推荐

