Skip to content

Instantly share code, notes, and snippets.

@davegreenwood
Created August 10, 2018 14:37
Show Gist options
  • Save davegreenwood/33f294b2cfc60e4de811b6aba6e2a89b to your computer and use it in GitHub Desktop.
Save davegreenwood/33f294b2cfc60e4de811b6aba6e2a89b to your computer and use it in GitHub Desktop.
python exit
"""
# 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
@davegreenwood
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment