【问题标题】:IPython Notebook - early exit from cellIPython Notebook - 提前退出单元格
【发布时间】:2023-12-27 17:14:01
【问题描述】:

我想在 IPython Notebook 的早期以编程方式退出一个单元格。但是,exit(0) 会杀死内核。

这样做的正确方法是什么?我不希望拆分单元格或手动停止执行。

【问题讨论】:

  • 你能解释一下为什么吗?如果您决定只运行单元格中的一半代码然后停止,我想您可能会引发异常,但我不确定这会起到什么作用。
  • @andi:这是不正确的。我的问题是关于停止执行单个单元格,而不是退出整个笔记本!
  • 对不起,我对您从单元格中退出的标题感到困惑。以为你是说笔记本。
  • @Marius:这是一种发展战略。我仍然喜欢在单个单元格内一次性运行大块代码,但经常想查询变量状态而不运行整个事情。我对 IPN 比较陌生,以前在通过命令行脚本开发时使用 exit(0) 来执行此操作。
  • @andi:你能取消标记副本吗?

标签: python ipython ipython-notebook


【解决方案1】:

稍微“正确”的选项:

这将使您摆脱最糟糕的尝试/除外障碍。

raise KeyboardInterrupt

你的更干净一点的版本:

assert(False)

或者简单地说:

raise

如果您想节省几次击键。

【讨论】:

  • 这个问题是它很乱,你会得到一个回溯。最好能找到一个安静地结束执行的解决方案。
【解决方案2】:

安静地停止当前和后续单元格:

class StopExecution(Exception):
    def _render_traceback_(self):
        pass

raise StopExecution

【讨论】:

  • 这完美!非常简单干净!
  • 非常干净,谢谢!现在我可以做def exit(): raise StopExecution
【解决方案3】:

我从here 重新发布我的答案,因为该解决方案也应该适用于您的问题。它会...

  • 退出时不杀死内核
  • 不显示完整的回溯(没有用于 IPython shell 的回溯)
  • 不要强迫您使用 try/excepts 来巩固代码
  • 使用或不使用 IPython,无需更改代码

只需将下面代码中的“exit”导入您的 jupyter notebook(IPython notebook)并调用“exit()”即可。它会退出并让您知道...

 An exception has occurred, use %tb to see the full traceback.

 IpyExit 

"""
# ipython_exit.py
Allows exit() to work if script is invoked with IPython without
raising NameError Exception. Keeps kernel alive.

Use: import variable 'exit' in target script with
     'from ipython_exit import exit'    
"""

import sys
from io import StringIO
from IPython import get_ipython


class IpyExit(SystemExit):
    """Exit Exception for IPython.

    Exception temporarily redirects stderr to buffer.
    """
    def __init__(self):
        # print("exiting")  # optionally print some message to stdout, too
        # ... or do other stuff before exit
        sys.stderr = StringIO()

    def __del__(self):
        sys.stderr.close()
        sys.stderr = sys.__stderr__  # restore from backup


def ipy_exit():
    raise IpyExit


if get_ipython():    # ...run with IPython
    exit = ipy_exit  # rebind to custom exit
else:
    exit = exit      # just make exit importable

【讨论】:

  • 如何在 Kaggle 内核 Notebook 中使用提前退出单元格?
  • @shauryaairi 抱歉,我还没用过 Kaggle,所以我不知道。
  • 什么没有内置的方法来做到这一点?
【解决方案4】:

这远非“正确”,但提前退出的一种方法是创建运行时错误。因此,与其使用 exit(0) 干净地从脚本中提前返回,不如使用类似的东西不干净地返回

print(variable_to_query)
() + 1

它将运行代码直到此时(完成打印语句)然后失败。

【讨论】:

  • 与插入一些不存在的变量或键入 0/0 等任何其他错误有什么区别?
  • 没有区别。任意