如何在Jupyter Notebook或JupyterLab单元中执行一行?

时间:2019-06-05 12:50:17

标签: python jupyter-notebook jupyter jupyter-lab

在JupyterLab和Jupyter Notebook中,您都可以使用ctrl + Enter执行单元格:

代码:

print('line 1')
print('line 2')
print('line 3')

单元格和输出:

cell and output

但是如何只运行 line 2?甚至在不运行整个单元的情况下选择单元中的线?当然,您可以只插入带有单行或选择的行的单元格,但这确实非常麻烦并且很快。那么有更好的方法吗?

1 个答案:

答案 0 :(得分:3)

简短答案:

Jupyter笔记本

  1. qtconsole
  2. 便签本

JupyterLab:

  1. qtconsole
  2. Run > Run Selected Text or Current Line in Console,可以选择使用键盘快捷键

在答案的结尾处,通过编辑查看以下详细信息以及某些 特殊情况


详细信息:

Jupyter Notebook选项1: qtconsole

可以说,插入新单元格最灵活的选择是使用魔术函数打开IPython控制台

%qtconsole

要使用更多高级控制台,请使用

%qtconsole --style vim

在Jupyter Notebook中,在该控制台中执行的行结果也将可用,因为它仍与正在运行的内核相同。缺点之一是您必须复制并粘贴或在控制台中键入所需的行。

[qtconsole[1]

Jupyter Notebook选项2: Scratchpad Notebook Extension

安装成功后,您可以使用ctrl + B启动便签本:

enter image description here

JupyterLab选项1: %qtconsole

以与笔记本相同的方式工作

JupyterLab选项2: Run > Run Selected Text or Current Line in Console

为新版本的JupyterLab内置了与qtconsole类似的选项,但可以说更加优雅。现在,您可以将标记放在一行上,或突出显示一个选择,然后使用菜单选项Run > Run Selected Text or Current Line in Console

enter image description here

您仍将在IPython控制台中获得结果,但不必使用%qtconsole添加额外的行,并且在单元格中运行选择的行会更容易:

enter image description here

您可以通过分配键盘快捷键使事情变得更加轻松  进入菜单选项Run > Run Selected Text or Current Line in Console,如下所示:

1-转到Settings并选择Advanced Settings editor

2-Settings tab下,进行ctrl+F搜索run-in-console,找到以下部分:

// [missing schema title]
    // [missing schema description]
    "notebook:run-in-console": {
      "command": "notebook:run-in-console",
      "keys": [
        ""
      ],
      "selector": ".jp-Notebook.jp-mod-editMode",
      "title": "Run In Console",
      "category": "Notebook Cell Operations"
    }

3-复制该部分并将其粘贴在User Overrides下,然后在keys下键入所需的快捷方式,如下所示:

[...]
"keys": [
  "F9"
],
[...]

4-单击Save All下的File

5-如果过程顺利,您会看到菜单选项已更改:

enter image description here

6-您可能必须重新启动JupyterLab,但现在您可以使用所需的快捷方式轻松地运行一行或选择一行。

编辑:特殊情况

您首选的方法将取决于相关行的输出性质。以下是plotly的示例。可能会随时间增加更多示例。

1。-密谋

打印的图形不会直接显示在Jupyter QtConsole中(可能与this相关),但是Jupyter笔记本中的Scratchpad和使用Run > Run Selected Text or Current Line in Console的Juphyterlab中的集成控制台都将只处理打印的图形很好。

代码段:

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.graph_objs as go
init_notebook_mode(connected=True)

trace0 = go.Scatter(
    x=[1, 2, 3, 4],
    y=[10, 15, 13, 17]
)

fig = go.Figure([trace0])
iplot(fig)

1.1 -使用便签本

enter image description here

1.2 -使用突出显示的行和键盘快捷键在JupyterLab控制台上进行绘图:

enter image description here