IPython Notebook - early exit from cell

前端 未结 4 1374
旧巷少年郎
旧巷少年郎 2020-12-13 08:14

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 n

相关标签:
4条回答
  • 2020-12-13 08:56

    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

    print(variable_to_query)
    () + 1
    

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

    0 讨论(0)
  • 2020-12-13 08:59

    Slightly more "proper" options:

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

    raise KeyboardInterrupt
    

    A little cleaner version of yours:

    assert(False)
    

    or simply:

    raise
    

    if you want to save a couple keystrokes.

    0 讨论(0)
  • 2020-12-13 09:04

    I'm reposting my answer from here because 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

    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
    
    0 讨论(0)
  • 2020-12-13 09:05

    To stop current and subsequent cells quietly:

    class StopExecution(Exception):
        def _render_traceback_(self):
            pass
    
    raise StopExecution
    
    0 讨论(0)
提交回复
热议问题