代码之家  ›  专栏  ›  技术社区  ›  Seungho Lee

在使用Jupyter笔记本的Python3中,“exit”关键字有什么作用?

  •  9
  • Seungho Lee  · 技术社区  · 7 年前

    我目前正在Jupyter笔记本中使用Python3,我刚刚遇到一个关键字 exit . 这个关键字有什么作用?

    with open("some_file.txt") as f:
        for lines in f:
            print(lines)
            exit
    
    3 回复  |  直到 7 年前
        1
  •  7
  •   user2357112    7 年前

    这个 exit 出口 但是,在Python中它什么也做不了。


    正常地 出口 _sitebuiltins.Quitter.__repr__ ):

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

    autocall 某一类型的实例, IPython.core.autocall.IPyAutocall . (这与 %autocall 魔术。)

    在伊皮顿, quit 设置为的实例 IPython.core.autocall.ExitAutocall IPyAutocall . IPython可以识别这种类型的对象,所以当一行只包含 出口 退出 执行时,IPython实际退出。

    In [1]: exit
    [IPython dies here]
    

    Jupyter笔记本的IPython内核 出口 退出 IPython.core.autocall.ZMQExitAutocall keep_kernel 参数,但在其他方面是相同的。

    但是,此功能仅在引用autocallable对象的行是单元格的整个内容时触发。在一个循环中,自动调用功能不会触发,所以我们回到了零状态。

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

        2
  •  4
  •   DYZ    7 年前

    exit ( 碳化硅 在循环或条件语句的分支中 ,它什么也不做,因为它只是对 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
    

    但是,在命令行上使用时 是的 (虽然没有 % )并终止内核。

        3
  •  3
  •   Paritosh Singh    7 年前

    在我的简单测试中,
    第1单元
    a = 3

    exit
    第三单元
    print(a)

    导致

    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-1-3f786850e387> in <module>
    ----> 1 a
    
    NameError: name 'a' is not defined
    

    出口

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

    测试2:
    a=3

    exit(keep_kernel=True)
    第三单元
    印刷品(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).
    
    推荐文章