Google Collab 如何显示作业的价值?

Google Collab How to show value of assignments?

我正在 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 上的笔记本显示作业输出?

嗯,最简单的方法就是将您的值包装在打印语句中,例如:

print(meter)
print(second)
print(a)

但是,如果你想用 jupyter 的方式来做,看起来答案是

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

从这个 link 中找到以上内容:

简短的回答是:您无法在 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']。如果您 select all,上述单元格的结果将为

Out[]:
57

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

meter = UNITS.meter
second = UNITS.second
a = 9.8 * meter / second**2
a

Google Colab 尚未升级到最新的 IPython 版本 - 如果您使用

明确升级
!pip install -U ipython 

那么 last_expr_or_assign 就可以了。

正如其他人所提到的,它不起作用,因为 last_expr_or_assign 是在 juptyer v6.1 中引入的,而 colab 使用的是 v5.x。在 colab 上升级 jupyter 版本可能会导致一些不稳定(colab 显示的警告):

WARNING: Upgrading ipython, ipykernel, tornado, prompt-toolkit or pyzmq can
cause your runtime to repeatedly crash or behave in unexpected ways and is not
recommended

另一种解决方案是使用诸如 ipydex 之类的扩展,它提供神奇的注释(如 ##:##:T##:S),这会导致return 值或右手边显示一行的分配。

!pip install ipydex
%load_ext ipydex.displaytools

例如

a = 4
c = 5 ##:

输出

c := 5

---