python - Google Collab 如何显示作业的值(value)?

标签 python jupyter-notebook ipython

我正在 Google 协作中处理这个 python 笔记本:
https://github.com/AllenDowney/ModSimPy/blob/master/notebooks/chap01.ipynb

我不得不更改配置行,因为原始中所述的配置行出错:

# Configure Jupyter to display the assigned value after an assignment

# Line commented below because errors out
# %config InteractiveShell.ast_node_interactivity='last_expr_or_assign'

# Edit solution given below
%config InteractiveShell.ast_node_interactivity='last_expr'

但是,我认为原始语句是为了显示赋值的值(如果我没记错的话),所以当我在笔记本中运行以下单元格时,我应该看到一个输出:
meter = UNITS.meter
second = UNITS.second
a = 9.8 * meter / second**2

如果是这样,我怎样才能让 google collab 上的笔记本显示作业的输出?

最佳答案

简短的回答是:您不能在 Colab 中显示作业的输出。

您的困惑来自于 Google Colab 的工作方式。原始脚本旨在在 IPython 中运行。但是 Colab 不是普通的 IPython。当您运行 IPython shell 时,您的 %config InteractiveShell.ast_node_interactivity选项是(引用 documentation)

‘all’, ‘last’, ‘last_expr’ , ‘last_expr_or_assign’ or ‘none’, specifying which nodes should be run interactively (displaying output from expressions). ‘last_expr’ will run the last node interactively only if it is an expression (i.e. expressions in loops or other blocks are not displayed) ‘last_expr_or_assign’ will run the last expression or the last assignment. Other values for this parameter will raise a ValueError.


all将显示所有变量,但不显示赋值,例如
x = 5
x
y = 7
y

Out[]:
5
7

当您想要在循环中显示变量时,选项之间的差异变得更加重要。

在 Colab 中,您的选项仅限于 ['all', 'last', 'last_expr', 'none']。如果您选择 all ,上述单元格的结果将是
Out[]:
57

综上所述,在 Colab 中无法显示分配结果。您唯一的选择(AFAIK)是将您想要查看的变量添加到分配它的单元格中(类似于常规 print ):
meter = UNITS.meter
second = UNITS.second
a = 9.8 * meter / second**2
a

关于python - Google Collab 如何显示作业的值(value)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62229579/

相关文章:

python - 交互式 IPython 终端中连续运行的 Tensorflow Op 命名

python - C++ 排序代码到 python 排序

python - 为什么 Python 不能在 Atom 中运行?

python - 在 NumPy 中使用 2 个维度进行索引时出错

python - Windows Tensorflow 无法恢复检查点。 "Access is denied."

python - 将 pypy3 设置为 Jupyter Notebook 的内核时出现问题

apache-spark - 将 PySpark 与 Jupyter Notebook 集成

python - 在 python Flask 中上传后文件显示零 kb

Python:tqdm 进度条停留在 0%

python - 如何在 Windows 上的 IPython 中启用输出文本突出显示?