2021年5月5日 星期三

[ Python 常見問題 ] Is it possible to automatically break into the debugger when a exception is thrown?

 Source From Here

Question
Is there a way to automatically start break into the debugger (import pdb; pdb.set_trace()) whenever a exception is thrown to inspect the local stack?

HowTo
I found what I was looking for in an answer to What is the simplest way of using Python pdb to in...use of an unhandled exception?:
- test.py
  1. #!/usr/bin/env python3  
  2. import pdb  
  3. import sys  
  4. import functools  
  5.   
  6.   
  7. def debug_on(*exceptions):  
  8.     if not exceptions:  
  9.         exceptions = (Exception, )  
  10.     def decorator(f):  
  11.         @functools.wraps(f)  
  12.         def wrapper(*args, **kwargs):  
  13.             try:  
  14.                 return f(*args, **kwargs)  
  15.             except exceptions:  
  16.                 pdb.post_mortem(sys.exc_info()[2])  
  17.         return wrapper  
  18.     return decorator  
  19.   
  20. @debug_on()  
  21. def buggy_function():  
  22.     print("About to cause exception!")  
  23.     raise Exception("Something wrong!")  
  24.     print("Unreachable...")  
  25.   
  26. if __name__ == '__main__':  
  27.     buggy_function()  
Let's test it:
# ./test.py
About to cause exception!
> /tmp/test.py(23)buggy_function()
-> raise Exception("Something wrong!")

(Pdb) list
  1. 18         return decorator  
  2. 19  
  3. 20     @debug_on()  
  4. 21     def buggy_function():  
  5. 22         print("About to cause exception!")  
  6. 23  ->     raise Exception("Something wrong!")  
  7. 24         print("Unreachable...")  
  8. 25  
  9. 26     if __name__ == '__main__':  
  10. 27         buggy_function()  
  11. [EOF]  
(Pdb) exit()


沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...