IPython Notebook - 提前退出单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24005221/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:49:18  来源:igfitidea点击:

IPython Notebook - early exit from cell

pythonipythonipython-notebook

提问by watsonic

I'd like to programmatically exit a cell early in IPython Notebook. exit(0), however, kills the kernel.

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

Whats the proper way to do this? I'd prefer not to split the cell or manually halt execution.

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

采纳答案by Darkonaut

I'm reposting my answer from herebecause the solution should apply to your question as well. It will...

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

  • not kill the kernel on exit
  • not display a full traceback (no traceback for use in IPython shell)
  • not force you to entrench code with try/excepts
  • work with or without IPython, without changes in code
  • 退出时不杀死内核
  • 不显示完整的回溯(没有在 IPython shell 中使用的回溯)
  • 不要强迫你用 try/excepts 来巩固代码
  • 使用或不使用 IPython,无需更改代码

Just import 'exit' from the code beneath into your jupyter notebook (IPython notebook) and calling 'exit()' should work. It will exit and letting you know that...

只需将下面代码中的“exit”导入您的 jupyter 笔记本(IPython 笔记本),然后调用“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

回答by watsonic

This is far from "proper" but one way to exit early is to create a runtime error. So instead of returning early from a script cleanly with exit(0)one can return uncleanly with something like

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

print(variable_to_query)
() + 1

which will run the code up until this point (completing the print statement) and then fail.

这将运行代码直到这一点(完成打印语句)然后失败。

回答by Paul

Slightly more "proper" options:

稍微“适当”的选项:

This will get you out of all but the worst try/except blocks.

这将使您摆脱最糟糕的 try/except 块。

raise KeyboardInterrupt

A little cleaner version of yours:

你的一个更干净的版本:

assert(False)

or simply:

或者干脆:

raise

if you want to save a couple keystrokes.

如果你想保存几次击键。

回答by Samuel Rizzo

To stop current and subsequent cells quietly:

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

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

raise StopExecution