从 index.ts 触发导出可执行脚本命令

时间:2021-06-01 19:27:42

标签: python jupyter-notebook jupyter jupyter-lab

我正在努力创建一个 JupyterLab 扩展,最终让用户测试其代码的功耗,第一步是创建一个按钮,将 Notebook 的内容下载为可执行脚本。

这已经可以通过 File > Export Notebook As... > Executable Script 或通过带有 Export Notebook: Executable Script 的命令面板完成,所以我怀疑它应该相当简单。但是,我无法从我的 index.ts 文件中运行此命令;任何帮助将不胜感激。我相信我的主要问题是不知道如何将正确的参数传递给 notebook:export-to-format 但我也可能做错了其他事情。

我使用此命令和扩展教程中的 cookiecutter 设置了环境(扩展教程 — JupyterLab 3.0.16 文档):

conda create -n greencode-ext3 --override-channels --strict-channel-priority -c conda-forge -c anaconda jupyterlab=3 cookiecutter nodejs jupyter-packaging git

cookiecutter GitHub - jupyterlab/extension-cookiecutter-ts: Typescript 中 JupyterLab 扩展的 cookiecutter 配方

这是我的 index.ts 文件:

import {
  JupyterLab,
  JupyterFrontEnd,
  JupyterFrontEndPlugin,
} from '@jupyterlab/application';

import { ITranslator } from '@jupyterlab/translation';

import { ToolbarButton } from "@jupyterlab/apputils";
import { DocumentRegistry } from "@jupyterlab/docregistry";
import { INotebookModel, NotebookPanel, INotebookTracker } from "@jupyterlab/notebook";

import { IDisposable } from "@lumino/disposable";

export class ButtonExtension implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel> {
    
  constructor(app: JupyterLab) {
      this.app = app;
  }
    
  readonly app: JupyterLab;

  createNew(panel: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): IDisposable {
     const { commands } = this.app;
     const command = 'notebook:export-to-format'

     // Create the toolbar button
     let mybutton = new ToolbarButton({
         label: 'Measure Power Usage',
         onClick: () => { 
             alert('You did it');
             commands.execute(command, {formatLabel: 'script'});
          }
       });

    // Add the toolbar button to the notebook toolbar
    panel.toolbar.insertItem(10, 'MeasurePowerUsage', mybutton);
    console.log("MeasPowerUsage activated");

    // The ToolbarButton class implements `IDisposable`, so the
    // button *is* the extension for the purposes of this method.
    return mybutton;
  }
}

/**
 * Initialization data for the greencode-ext3 extension.
 */
const yourPlugin: JupyterFrontEndPlugin<void> = {
  id: '@your-org/plugin-name',
  autoStart: true,
  requires: [ITranslator, INotebookTracker],
  activate: (app: JupyterFrontEnd) => {
    const your_button = new ButtonExtension(new JupyterLab);
    app.docRegistry.addWidgetExtension('Notebook', your_button);
  }
}

export default yourPlugin;

0 个答案:

没有答案
相关问题