IPython Notebook-提前退出单元 [英] IPython Notebook - early exit from cell

查看:106
本文介绍了IPython Notebook-提前退出单元的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

执行此操作的正确方法是什么?我不希望拆分单元格或手动停止执行.

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

推荐答案

我正在从

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

  • 不退出时终止内核
  • 不显示完整的回溯(在IPython shell中不使用回溯)
  • 不要强迫您使用try/excepts巩固代码
  • 在有或没有IPython的情况下工作,而无需更改代码

只需将下面的代码中的退出"导入到jupyter笔记本(IPython笔记本)中,然后调用"exit()"就可以了.它将退出并告知您...

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...

 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

这篇关于IPython Notebook-提前退出单元的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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