Python3 中的 `exit` 关键字在 Jupyter Notebook 中有什么作用?

What does `exit` keyword do in Python3 with Jupyter Notebook?

我目前在 Jupyter Notebook 中使用 Python3,我只是 运行 进入关键字 exit。这个关键字有什么作用?

with open("some_file.txt") as f:
    for lines in f:
        print(lines)
        exit

在我的简单测试中,
单元格 1
a = 3
单元格 2
exit
单元格 3
print(a)

导致

---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-3f786850e387> in <module>
----> 1 a

NameError: name 'a' is not defined

exit 只是杀死笔记本执行所依赖的内核。

然而,有趣的是,您似乎也可以传递一个参数来修改该行为。

测试 2: 单元格 1
a = 3
单元格 2
exit(keep_kernel=True)
单元格 3
print(a) 结果 3

编辑:看起来@user2357112 的回答填补了缺失的部分。
EDIT2:实际上,它似乎是 IPython.core.autocall.ZMQExitAutocall

的一个实例
 class IPython.core.autocall.ZMQExitAutocall(ip=None)

    Bases: IPython.core.autocall.ExitAutocall

    Exit IPython. Autocallable, so it needn’t be explicitly called.
    Parameters: keep_kernel (bool) – If True, leave the kernel alive. Otherwise, tell the kernel to exit too (default).

循环中的 exit 行什么都不做。不过,他们什么都不做的原因比 exit 在 Python 中什么都不做的通常原因要复杂一些。


通常,exit 单独一行不会退出 Python。至多,在交互模式下,它会打印一条消息告诉你如何退出 Python(消息在 _sitebuiltins.Quitter.__repr__ 中实现):

>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit

IPython 做了一些不同的事情。 IPython 有许多额外的系统,为了方便交互,有一个系统 autocall instances of a certain type, IPython.core.autocall.IPyAutocall. (This is similar to but distinct from the %autocall 很神奇。)

在 IPython 中,exitquit 被设置为 IPython.core.autocall.ExitAutocall 的实例,IPyAutocall 的子类。 IPython 识别这种类型的对象,因此当执行仅包含 exitquit 的行时,IPython 实际上退出。

In [1]: exit
[IPython dies here]

Jupyter notebook 的 IPython 内核将 exitquit 设置为非常密切相关的 IPython.core.autocall.ZMQExitAutocall 的实例,它有一些额外的功能来支持 keep_kernel 参数,但其他方面相同。

不过,此功能仅在引用可自动调用对象的行是单元格的全部内容时触发。在一个循环中,自动调用功能不会触发,所以我们回到了没有任何事情发生的状态。

事实上,发生的事情比正常交互模式下发生的还要少 - 在正常的非 IPython 交互会话中,此循环会在每次迭代时打印 "Use exit()..." 消息,由于IPython 和常规交互模式处理表达式自动打印的方式不同。

exit原文,不带括号)用于iPython 循环或条件分支statement,它什么都不做,因为它只是对 IPython.core.autocall.ExitAutocall:

的一个实例的引用
for i in range(10): 
    exit 
print(i)
# 9

if i==9: 
   exit 
   print(exit)    
# <IPython.core.autocall.ExitAutocall object at 0x7f76ad78a4a8>      

不重启内核:

print(i)
# 9

然而,当在命令行单独使用时,它被视为一种魔法(尽管没有%) 并终止内核。