在JupyterLab中以编程方式运行计算单元

2024-09-27 23:15:43 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在一个Jupyerlab笔记本中编写一个代码,在用户不做任何事情的情况下运行其他单元格。我找到了解决办法:

from IPython.display import Javascript
Javascript('JupyterLab.notebook.execute_cells_below()')

但它在JupyterLab中似乎不起作用,它抛出了一个错误:

Javascript Error: notebook is not defined

使用JupyterLab有类似的方法吗


Tags: 代码用户fromimportexecuteipythondisplay情况
2条回答

在编写JupyterLab扩展时,我发现了如何以编程方式执行单元格。这并不完全是您要求的,但可能有助于其他人搜索此主题。JupyterLab的代码似乎比JupyterNotebook更复杂

JupyterLab提供了这种方法

NotebookActions.run(notebook, sessionContext);

它执行当前选定的单元格。还有一些其他方法(例如“runalldown”)。也看到

https://github.com/jupyterlab/jupyterlab/blob/master/packages/notebook/src/actions.tsx

一些示例代码(另请参见my JupyterLab extension for treezjs):

var { NotebookActions } = require("@jupyterlab/notebook");    
var app = ... //injected with activate method of extension

var pythonCode = 'print("Hello World")';

this.__notebookPanel = this.__getFirstVisibleNotebookPanel(app);

executePythonCodeWithCell(pythonCode)

async executePythonCodeWithCell(pythonCode){
    
    var self=this;

    var NotebookActions = this.__dependencies['NotebookActions'];

    return new Promise(async (resolve, reject) => {

        if(self.__notebookPanel){
            var notebook = self.__notebookPanel.content;
            var notebookModel = notebook.model;
            var sessionContext = self.__notebookPanel.sessionContext;   
            
            var options = { };
            var cellModel = notebookModel.contentFactory.createCell('code',options);                
            cellModel.value.text = pythonCode;

            const activeCellIndexBackup = notebook.activeCellIndex;

            
            var newCellIndex = notebookModel.cells.length;
            notebookModel.cells.insert(newCellIndex, cellModel);                
            notebook.activeCellIndex = newCellIndex;

            var cell = notebook.activeCell;
            
            try{
                await NotebookActions.run(notebook, sessionContext);
            } catch(error){
                reject(error);
            } 
            
            var htmlArray = [];

            for(var output of cell.outputArea.node.children){                               
                htmlArray.push(output.innerHTML);
            }                   
           
            await NotebookActions.deleteCells(notebook);
            
            notebook.activeCellIndex = activeCellIndexBackup;

            resolve(htmlArray);     

        }               
        
    });     
}

__getFirstVisibleNotebookPanel(app){
        var mainWidgets = app.shell.widgets('main');
        var widget = mainWidgets.next();
        while(widget){
            var type = widget.constructor.name;
            if(type == 'NotebookPanel'){  //other wigets might be of type DocumentWidget
                if (widget.isVisible){
                    return widget;
                }
            }
            widget = mainWidgets.next();
        }
        return null;
}

我以前的JupyterNotebook代码的一部分:

this.__notebook = Jupyter.notebook;

async executePythonCodeWithCell(pythonCode){
    
    var self=this;

    return new Promise(function(resolve, reject) {  
        
        var cell = self.__notebook.insert_cell_below();
        cell.element[0].style.display = 'none';
        cell.set_text(pythonCode);
        cell.events.on('finished_execute.CodeCell', (event, data) => self.__codeCellExecutionFinished(cell, data.cell, resolve));

        try{
            cell.execute();
        } catch(error){
            reject(error);
        } 
        
    });     
}

相关的:

JupyterLab: Run all cells below

https://github.com/jupyterlab/jupyterlab/issues/6563

https://github.com/CDAT/jupyter-vcdat/blob/master/src/CellUtilities.ts

https://github.com/stefaneidelloth/treezjs/blob/master/jupyter_lab_extension/jupyterLabTerminal.js

也许您可以为“运行上面的所有单元格”设置快捷方式并执行以下行:

import keyboard

keyboard.press_and_release('your_shorcut_here')

假设您已将快捷方式定义为shift+s。只需将其作为strig放在上面的代码中:

keyboard.press_and_release('shift+s')

对于最新的jupyter笔记本(版本5),您可以转到笔记本顶部的“帮助”选项卡,然后选择“编辑键盘快捷键”选项并添加您自己的自定义快捷键

也许jupyter实验室也有同样的选择

相关问题 更多 >

    热门问题