当Thebe启动时运行单元格#

有时在Thebe启动时自动运行一些单元格是有帮助的。例如,如果您想预定义一些变量或导入稍后将使用的功能。这使您可以专注于传达给用户的代码中的想法。

在初始化后,可以通过Javascript控制Thebe。以下是两种配置Javascript以在幕后运行代码的方法。

在Thebe初始化时运行单元格#

一种简单的运行代码的方法是模拟点击启动Thebe时创建的按钮。通过选择Thebe按钮并调用click()方法,当Thebe内核准备就绪后,该单元格中的代码将被运行(并将显示输出)。

以下是选择带有thebelab-init标签的所有单元格并模拟点击按钮的代码示例。

thebelab.events.on("request-kernel")(() => {
    // Find any cells with an initialization tag and ask Thebe to run them when ready
    var thebeInitCells = document.querySelectorAll('.thebelab-init');
    thebeInitCells.forEach((cell) => {
        console.log("Initializing Thebe with cell: " + cell.id);
        const initButton = cell.querySelector('.thebelab-run-button');
        initButton.click();
    });
});

使用Thebe运行自定义代码#

此外,您可以使用Javascript和requestExecute方法从Thebe对象运行自己的自定义代码。以下是使用相同事件触发器的代码片段,但在这种情况下,一旦内核准备就绪,就会针对内核运行一些自定义代码。

thebelab.events.on("request-kernel")((kernel) => {
    // Find any cells with an initialization tag and ask Thebe to run them when ready
    kernel.requestExecute({code: "import numpy"})
});

在上面的两种情况下,您可能需要根据代码的结构以及希望用户在访问页面时的行为来自定义Javascript调用。