IPython Notebook - 提前退出单元格

wat*_*nic 47 python ipython ipython-notebook

我想以编程方式在IPython Notebook早期退出单元格.exit(0)然而,杀死了内核.

什么是正确的方法来做到这一点?我不想拆分单元格或手动停止执行.

Sam*_*zzo 28

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

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

raise StopExecution
Run Code Online (Sandbox Code Playgroud)

  • 根据 https://github.com/ipython/ipython/blob/4f6e132d2fc56feabd9d87cac98906d3e5806d6a/IPython/core/interactiveshell.py#L1994 `_render_traceback_` 旨在返回字符串列表。因此该方法可能应该执行“return []”而不是“pass”。通过“pass”,我在使用 nbconvert 时遇到了异常。 (4认同)
  • 这完美!非常简单干净! (2认同)

Pau*_*aul 24

略微更"适当"的选择:

除了最差的try/except块之外,这将使你除外.

raise KeyboardInterrupt
Run Code Online (Sandbox Code Playgroud)

你的一个更干净的版本:

assert(False)
Run Code Online (Sandbox Code Playgroud)

或者干脆:

raise
Run Code Online (Sandbox Code Playgroud)

如果你想节省一些按键.

  • 这个问题是它很乱,你得到追溯.找到一个能够安静地结束执行的解决方案会很高兴. (11认同)

Dar*_*aut 15

我在这里重新发布我的答案,因为解决方案也适用于你的问题.它会...

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

只需从下面的代码中导入"退出"到您的jupyter笔记本(IPython笔记本)中,并调用'exit()'即可.它会退出并让你知道......

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

 IpyExit 
Run Code Online (Sandbox Code Playgroud)
"""
# 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
Run Code Online (Sandbox Code Playgroud)

  • 什么没有内置的方法来做到这一点? (6认同)