Created
August 10, 2018 14:37
-
-
Save davegreenwood/33f294b2cfc60e4de811b6aba6e2a89b to your computer and use it in GitHub Desktop.
python exit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
from : https://stackoverflow.com/a/48000614