除非设置了详细或调试标志,否则隐藏回溯错误的惯用python方法是什么?
示例代码:
their_md5 = 'c38f03d2b7160f891fc36ec776ca4685'
my_md5 = 'c64e53bbb108a1c65e31eb4d1bb8e3b7'
if their_md5 != my_md5:
raise ValueError('md5 sum does not match!')
Run Code Online (Sandbox Code Playgroud)
现在输出,但只有在调用时才需要foo.py --debug:
Traceback (most recent call last):
File "b:\code\apt\apt.py", line 1647, in <module>
__main__.__dict__[command] (packages)
File "b:\code\apt\apt.py", line 399, in md5
raise ValueError('md5 sum does not match!')
ValueError: md5 sum does not match!
Run Code Online (Sandbox Code Playgroud)
期望的正常输出:
ValueError: md5 sum does not match!
Run Code Online (Sandbox Code Playgroud)
这是一个测试脚本:https://gist.github.com/maphew/e3a75c147cca98019cd8
我正在使用Python 2.5并尝试excepthook在我的程序中使用自定义.在主线程中,它完美地运行.但是在一个以线程模块开始的线程中,通常excepthook会调用它.
这是一个显示问题的示例.取消注释注释会显示所需的行为.
import threading, sys
def myexcepthook(type, value, tb):
print 'myexcepthook'
class A(threading.Thread, object):
def __init__(self):
threading.Thread.__init__(self, verbose=True)
# raise Exception('in main')
self.start()
def run(self):
print 'A'
raise Exception('in thread')
if __name__ == "__main__":
sys.excepthook = myexcepthook
A()
Run Code Online (Sandbox Code Playgroud)
那么,我如何excepthook在一个线程中使用自己的?
我经常与大型图书馆(例如pandas或matplotlib)合作。
这意味着异常通常会产生较长的堆栈跟踪。
由于该错误很少出现在库中,而错误经常出现在我自己的代码中,因此在大多数情况下,我不需要查看库的详细信息。
几个常见的例子:
>>> import pandas as pd
>>> df = pd.DataFrame(dict(a=[1,2,3]))
>>> df['b'] # Hint: there _is_ no 'b'
Run Code Online (Sandbox Code Playgroud)
在这里,我尝试访问未知密钥。这个简单的错误产生一个包含28行的stacktrace:
Traceback (most recent call last):
File "an_arbitrary_python\lib\site-packages\pandas\core\indexes\base.py", line 2393, in get_loc
return self._engine.get_loc(key)
File "pandas\_libs\index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5239)
File "pandas\_libs\index.pyx", line 154, in pandas._libs.index.IndexEngine.get_loc (pandas\_libs\index.c:5085)
File "pandas\_libs\hashtable_class_helper.pxi", line 1207, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20405)
File "pandas\_libs\hashtable_class_helper.pxi", line 1215, in pandas._libs.hashtable.PyObjectHashTable.get_item (pandas\_libs\hashtable.c:20359)
KeyError: 'b'
During handling of the above exception, another exception occurred:
Traceback …Run Code Online (Sandbox Code Playgroud) 我正在编写一些使用该multiprocessing模块的代码.但是,由于我是新手,经常发生的是弹出一些错误,停止主应用程序.
但是,应用程序的子项仍然在运行,我pythonw在任务管理器列表中获得了很长的运行进程列表.
发生错误后,我还能做些什么来确保所有子进程都被杀死?