JupyterLabで、JavaScriptからドキュメントのコンテキスト内でPythonコードをどのように評価できますか?
Jupyterノートブックでは、セルを持つことができます
%%javascript IPython.notebook.kernel.execute('x = 42')
その後、文書の他の場所では、x を含む Python コードセルが予想どおり 42 にバインドされていることを示します。
私はJupyterLabで同様のものを作ろうとしています。アドホックなJSを使うのではなく、プラグインを書くべきだということは理解していますし、それでも問題ありませんが、ノートブックのグローバルなIPythonのようなカーネルへのインターフェースが見つかりません。
import { JupyerLab, JupyterLabPlugin } from '@jupyterlab/application';
const extension: JupyterLabPlugin<void> = {
// ...
requires: [],
activate: (app: JupyterLab) => {
// can I get to Python evaluation through app?
// by adding another class to `requires` above?
}
}
export default extension;
回答 #1
ここに「動く」ハッキーな試みがあります。もし誰かがカーネルが準備できているという公的な約束がどこにあるか、中間クラスを避ける方法、またはその他の一般的な改善点を知っていれば、アドバイスをもらえると助かります。
import { JupyterLab, JupyterLabPlugin } from '@jupyterlab/application';
import { DocumentRegistry } from '@jupyterlab/docregistry';
import { INotebookModel, NotebookPanel } from '@jupyterlab/notebook';
import { IDisposable, DisposableDelegate } from '@phosphor/disposable';
declare global {
interface Window {
'execPython': {
'readyState': string,
'exec': (code: string) => any,
'ready': Promise<void>
} | null
}
}
class ExecWidgetExtension implements DocumentRegistry.IWidgetExtension<NotebookPanel, INotebookModel> {
createNew(nb: NotebookPanel, context: DocumentRegistry.IContext<INotebookModel>): IDisposable {
if (window.execPython) {
return;
}
window.execPython = {
'readyState': 'waiting',
'exec': null,
'ready': new Promise((resolve) => {
const wait = setInterval(() => {
if (!context.session.kernel || window.execPython.readyState === 'ready') {
return;
}
clearInterval(wait);
window.execPython.readyState = 'ready';
window.execPython.exec = (code: string) =>
context.session.kernel.requestExecute({ code }, true);
resolve();
}, 50);
})
};
// Usage elsewhere: execPython.ready.then(() => execPython.exec('x = 42').done.then(console.log, console.error))
return new DisposableDelegate(() => {});
}
}
const extension: JupyterLabPlugin<void> = {
'id': 'jupyterlab_foo',
'autoStart': true,
'activate': (app: JupyterLab) => {
app.docRegistry.addWidgetExtension('Notebook', new ExecWidgetExtension())
}
};
export default extension;
