2019年10月29日 星期二

[ Python 常見問題 ] How to enter PDB on a specific stack frame

Source From Here
Question
I've written a function to enter PDB when an exception is raised (let's call it trace_on_error). Right now when I call pdb.set_trace()pdb reasonably enters into the stack frame of trace_on_error, requiring me to have to type the up command before being able to look at the frame of the calling function.

I am trying to make trace_on_error not require users to know how its implemented to use, and thus i would like to have pdb enter into the callers stack frame. As I looked for documentation, i was hoping to find something similar to pdb.set_trace(frame_up=1), but I have not found anything.

Example Code:
  1. def trace_on_error(f, errors):  
  2.     try:  
  3.         return f()  
  4.     except errors as e:  
  5.         pdb.set_trace()  
How-To
This should do the trick (I've tested it but not sure it works in every possible case):
  1. def trace_on_error(f, errors):  
  2.     try:  
  3.         return f()  
  4.     except errors as e:  
  5.         import sys  
  6.         from pdb import Pdb  
  7.         Pdb().set_trace(sys._getframe().f_back)  
For sys._getframe([depth])
Return a frame object from the call stack. If optional integer depth is given, return the frame object that many calls below the top of the stack. If that is deeper than the call stack, ValueError is raised. The default for depth is zero, returning the frame at the top of the call stack.

Supplement
Python standard library: inspect — Inspect live objects

沒有留言:

張貼留言

[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...