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

查看:29
本文介绍了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,无需更改代码

只需将下面代码中的exit"导入您的 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天全站免登陆