python:backtrace.hook 不适用于 backtrace.print_exc()

python: backtrace.hook does not work with backtrace.print_exc()

我不知道如何给自己打印的回溯着色。
这为我的回溯着色:

#!/bin/python3
import backtrace
backtrace.hook()
raise Exception('here')

但是如果我捕捉到异常并打印它...那么没有颜色:

#!/bin/python3
import backtrace
backtrace.hook()
import traceback
try:
    raise Exception('here')
except Exception:
    traceback.print_exc()

我知道这是两个不同的包,但它们应该可以一起工作。
如何捕获并打印彩色异常(和堆栈跟踪)?

backtrace 内部使用 sys.excepthook do the trick. When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In your first case, when you call backtrace.hook(), the backtrace library essentially set the sys.excepthook to a custom function 可以做各种魔术,除了实例(着色等....)

>>> def custom_hook(*args):
...     print(args)
...
>>>
>>> import sys
>>> sys.excepthook = custom_hook
>>>
>>> 1 / 0 # No exception raised, instead it calls `custom_hook`
(<class 'ZeroDivisionError'>, ZeroDivisionError('division by zero'), <traceback object at 0x000001FA502B98C0>)

如果引发并捕获异常(使用 except),excepthook 不会调用

>>> def custom_hook(*args):
...     print(args)
...
>>>
>>> import sys
>>> sys.excepthook = custom_hook
>>>
>>> try:
...     1 / 0 
... except: # Since the exception is caught here, it won't call `custom_hook`
...     pass
...

确切的情况发生在你的案例中。一旦捕获异常,您必须重新引发异常才能获得异常行为。