配置 Thebe#

你可以通过放置在页面HTML某处的配置块来控制Thebe的行为。该配置块具有以下结构:

<script type="text/x-thebe-config">
   {
       a: collection
       of: key
       val: pairs
   }
</script>

例如,以下配置告诉Thebe使用BinderHub进行会话,并指定要与Binder一起使用的仓库:

<script type="text/x-thebe-config">
{
    requestKernel: true,
    binderOptions: {
        repo: "binder-examples/requirements",
        ref: "master",
    },
}
</script>

当在页面上启动Thebe时,将使用此配置来控制其行为。

请参阅下面的部分,了解可以使用Thebe配置进行控制的内容。

配置将要启动的内核#

要配置Thebe启动时请求的内核,请在Thebe配置中使用以下部分:

kernelOptions: {
  kernelName: "python3",
},

当Thebe启动时,它将为页面请求一个具有该名称的内核。请注意,目前每个页面只能有一个内核。

备注

您必须确保Thebe尝试启动的环境中存在 kernelName 的值。某些语言(如 python)的简写也可能有效。

配置启动内核的工作目录#

除了选择内核之外,您还可以选择启动内核的 path。这将相对于启动的Jupyter服务器的根目录(例如,如果使用BinderHub,则相对于仓库的根目录)。

要配置工作目录的路径,请使用以下配置:

kernelOptions: {
  kernelName: "python3",
  path: "path/to/directory"
}

自定义CodeMirror#

CodeMirror是将您的代码单元格转换为可编辑单元格的工具。它具有许多配置选项,例如主题和语法高亮显示。您可以使用以下Thebe配置在一个单元格中编辑所有这些属性:

// Additional options to pass to CodeMirror instances
codeMirrorConfig: {},

您可以使用任何可用的CodeMirror配置。例如,以下配置更改了CodeMirror的主题

codeMirrorConfig: {
    theme: "abcdef"
}

以下代码单元格演示了此主题:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
plt.ion()
fig, ax = plt.subplots()
ax.scatter(*np.random.randn(2, 100), c=np.random.randn(100))
ax.set(title="Wow, an interactive plot!")
[Text(0.5, 1.0, 'Wow, an interactive plot!')]
../../../../_images/60acdcf6b6fdecdd5916807c78a65bfa3f9b2a36edb1507bb905af5b213dde00.png

将代码单元格标记为只读#

如果您希望Thebe能够运行一个代码单元格,但不希望用户编辑它,您可以使用以下语法将其标记为“只读”:

<pre data-executable data-readonly>print("I cannot be modified")</pre>

一旦Thebe被激活,用户将无法修改代码,但他们仍然可以按下“运行”按钮来查看输出结果。

中文翻译结果是: 要将所有单元格默认设置为只读,请使用以下Thebe配置:

codeMirrorConfig: {
    readOnly: true
}

这使用CodeMirror将所有单元格标记为只读。如果您正在使用此设置,并希望手动将单个单元格标记为可编辑,可以使用 data-readonly="false" 来覆盖单元格的CodeMirror配置。例如:

<pre data-executable data-readonly="false">print("I still can be modified")</pre>
<pre data-executable>print("Due to codeMirrorConfig, I cannot be modified")</pre>