diff --git a/Lib/site.py b/Lib/site.py index ad1146332b..0e3c198e46 100644 --- a/Lib/site.py +++ b/Lib/site.py @@ -638,3 +638,41 @@ def _script(): if __name__ == '__main__': _script() + +import traceback + +def myhook(exc_type, exc_value, exc_tb, obj, + # local copies of functions to attempt to get them + # during Python finalization + print_tb=traceback.print_tb, + _getframe=sys._getframe, + extract_stack=traceback.extract_stack, + print_list=traceback.print_list): + try: + file = sys.stderr + except AttributeError: + # lost sys.stderr + return + if file is None: + return + + if obj is not None: + print(f"Exception ignored in: {obj!r}", file=file) + + if exc_tb is not None: + try: + print_tb(exc_tb) + except Exception: + # Continue even if printing the traceback fails: + # always try to display the exception type and value + pass + + print(f"{exc_type.__name__}: {exc_value}", file=file) + + stack = extract_stack(_getframe(1)) + if stack: + print('Traceback (most recent call last):', file=file) + print_list(stack, file=file) + +if hasattr(sys, 'unraisablehook'): + sys.unraisablehook = myhook