提问人:Marc 提问时间:11/14/2023 更新时间:11/14/2023 访问量:5
threading.excepthook args.exc_traceback 为 None
threading.excepthook args.exc_traceback is None
问:
我正在尝试覆盖.它有点工作,但我的接收作为回溯。Python 文档说这是可能的。但是,为什么呢?我怎样才能得到真正的回溯?threading.excepthook
custom_hook()
None
custom_hook()
我的最终目标是为每个堆栈轨道打印一个时间戳(对于系统异常和我的自定义异常)。输出需要转到 。stderr
如果我运行以下代码:
from time import sleep
import threading
import traceback
# target function that raises an exception
def work():
print('Working...')
sleep(1)
# rise an exception
raise Exception('Something bad happened')
# custom exception hook
def custom_hook(args):
# report the failure
print('timestamp')
print(traceback.print_tb(args.exc_traceback))
def main():
# set the exception hook
threading.excepthook = custom_hook
# create a thread
thread = threading.Thread(target=work)
# run the thread
thread.start()
# wait for the thread to finish
thread.join()
# continue on
print('Continuing on...')
if __name__ == "__main__":
main()
我得到这个输出:
/Users/msarrel/PycharmProjects/pychansim/venv/bin/python /Users/msarrel/Library/Application Support/JetBrains/PyCharm2023.2/scratches/scratch_1.py
Working...
timestamp
None
Continuing on...
File "/usr/local/Cellar/[email protected]/3.9.18/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 980, in _bootstrap_inner
self.run()
File "/usr/local/Cellar/[email protected]/3.9.18/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 917, in run
self._target(*self._args, **self._kwargs)
File "/Users/msarrel/Library/Application Support/JetBrains/PyCharm2023.2/scratches/scratch_1.py", line 11, in work
raise Exception('Something bad happened')
Process finished with exit code 0
出于某种原因,回溯打印在 .thread.join()
如果我不尝试在以下位置打印回溯:custom_hook()
from time import sleep
import threading
# import traceback
# target function that raises an exception
def work():
print('Working...')
sleep(1)
# rise an exception
raise Exception('Something bad happened')
# custom exception hook
def custom_hook(args):
# report the failure
print('timestamp')
# print(traceback.print_tb(args.exc_traceback))
def main():
# set the exception hook
threading.excepthook = custom_hook
# create a thread
thread = threading.Thread(target=work)
# run the thread
thread.start()
# wait for the thread to finish
thread.join()
# continue on
print('Continuing on...')
if __name__ == "__main__":
main()
我得到以下输出:
/Users/msarrel/PycharmProjects/pychansim/venv/bin/python /Users/msarrel/Library/Application Support/JetBrains/PyCharm2023.2/scratches/scratch_1.py
Working...
timestamp
Continuing on...
Process finished with exit code 0
在这种情况下,根本不会打印回溯...
为什么?
答: 暂无答案
评论