Created
May 25, 2023 04:34
-
-
Save jrfk/cc9f1288a81dba328be7881553d0981c to your computer and use it in GitHub Desktop.
interactive_exception_handling
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
""" | |
Description: | |
This script enhances the Python interactive console (REPL) by introducing | |
a custom exception handling mechanism. It leverages the built-in InteractiveConsole | |
and InteractiveInterpreter classes and overrides the 'showtraceback' method | |
for personalized exception handling. This enables more flexible control over | |
how exceptions are dealt with in the console, and can be particularly useful for | |
debugging or for enhancing console output in specific applications. | |
""" | |
import sys | |
import traceback | |
from code import InteractiveInterpreter, InteractiveConsole | |
class MyInterpreter(InteractiveInterpreter): | |
""" https://github.dev/python/cpython/blob/7f963bfc79a515dc9822ebddbfb1b5927d2dda09/Lib/code.py#L150-L150 | |
""" | |
def showtraceback(self): | |
"""Display the exception that just occurred. | |
We remove the first stack item because it is our own code. | |
The output is written by self.write(), below. | |
""" | |
print("here") | |
sys.last_type, sys.last_value, last_tb = ei = sys.exc_info() | |
sys.last_traceback = last_tb | |
sys.last_exc = ei[1] | |
try: | |
lines = traceback.format_exception(ei[0], ei[1], last_tb.tb_next) | |
if sys.excepthook is sys.__excepthook__: | |
print("here if") | |
self.write(''.join(lines)) | |
else: | |
# If someone has set sys.excepthook, we let that take precedence | |
# over self.write | |
print("here else") | |
sys.excepthook(ei[0], ei[1], last_tb) | |
finally: | |
last_tb = ei = None | |
class MyConsole(InteractiveConsole): | |
def __init__(self, locals=None, filename="<console>"): | |
self.interpreter = MyInterpreter() | |
super().__init__(locals, filename) | |
def showsyntaxerror(self, filename=None): | |
self.interpreter.showsyntaxerror(filename) | |
def showtraceback(self): | |
self.interpreter.showtraceback() | |
# def myhook(type, value, traceback): | |
# print('Hello, World!', file=sys.stderr) | |
if __name__ == "__main__": | |
# sys.excepthook = myhook | |
console = MyConsole() | |
console.interact() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment