在Jupyter Notebook中Python3中的`exit`关键字有什么作用? [英] What does `exit` keyword do in Python3 with Jupyter Notebook?

查看:545
本文介绍了在Jupyter Notebook中Python3中的`exit`关键字有什么作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在Jupyter Notebook中使用Python3,而我刚遇到了关键字exit.此关键字的作用是什么?

I am currently using Python3 in Jupyter Notebook and I just ran into a keyword exit. What does this keyword do ?

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

推荐答案

循环中的exit行无效.为什么它们什么都不做比exit在Python中什么都不做的通常原因要复杂一些.

The exit lines in your loop do nothing. Why they do nothing is a bit more complicated than the usual reason exit would do nothing in Python, though.

通常,单独一行上的exit不会退出Python.最多在交互模式下,它将显示一条消息,告诉您如何退出Python(在

Normally, exit on a line by its own wouldn't exit Python. At most, in interactive mode, it would print a message telling you how to quit Python (message implemented in _sitebuiltins.Quitter.__repr__):

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

IPython做一些不同的事情. IPython具有许多其他方便交互的系统,其中一个系统自动调用实例. (这类似于 %autocall 魔术.)

IPython does something different. Among the many extra systems IPython has for interactive convenience is a system to autocall instances of a certain type, IPython.core.autocall.IPyAutocall. (This is similar to but distinct from the %autocall magic.)

在IPython中,将exitquit设置为

In IPython, exit and quit are set to instances of IPython.core.autocall.ExitAutocall, a subclass of IPyAutocall. IPython recognizes objects of this type, so when a line containing just exit or quit is executed, IPython actually exits.

In [1]: exit
[IPython dies here]

Jupyter笔记本的IPython内核已将exitquit设置为与

A Jupyter notebook's IPython kernel has exit and quit set to instances of the very closely related IPython.core.autocall.ZMQExitAutocall, which has some extra functionality to support a keep_kernel argument, but is otherwise the same.

但是,仅当引用自动调用对象的行是单元格的全部内容时,才触发此功能.在循环内部,自动调用功能不会触发,因此我们什么也没做.

This functionality only triggers when a line referring to the autocallable object is the entire content of the cell, though. Inside a loop, the autocall functionality doesn't trigger, so we're back to nothing happening.

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

In fact, even less happens than what would happen in normal interactive mode - in a normal, non-IPython interactive session, this loop would print the "Use exit()..." message on each iteration, due to differences in how IPython and the regular interactive mode handle expression auto-printing.

这篇关于在Jupyter Notebook中Python3中的`exit`关键字有什么作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆