2016-11-04 59 views
9

我在ipython中使用--pdb命令,因此當我在調試代碼時發生錯誤並顯示堆棧跟蹤。很多這些錯誤來自於調用numpy或pandas函數輸入錯誤。堆棧跟蹤從最新的框架開始,以這些庫的代碼開始。在後面的5-10次重複中,我實際上可以看到我做錯了什麼,其中90%的時間會立即顯現(例如,使用列表而不是數組調用)。發生異常後,在最早的堆棧幀中啓動python調試器

有什麼方法可以指定調試器最初啓動的是哪個堆棧幀?最初的堆棧幀或最初運行的python文件中的最新堆棧幀,或類似的。這對於調試將更有成效。

下面是一個簡單的例子

import pandas as pd 

def test(df): # (A) 
    df[:,0] = 4 #Bad indexing on dataframe, will cause error 
    return df 

df = test(pd.DataFrame(range(3))) # (B) 

所得回溯,(A),(B),(C)加入,爲了清楚起見

In [6]: --------------------------------------------------------------------------- 
TypeError         Traceback (most recent call last) 
<ipython-input-6-66730543fac0> in <module>() 
----> 1 import codecs, os;__pyfile = codecs.open('''/tmp/py29142W1d''', encoding='''utf-8''');__code = __pyfile.read().encode('''utf-8''');__pyfile.close();os.remove('''/tmp/py29142W1d''');exec(compile(__code, '''/test/stack_frames.py''', 'exec')); 

/test/stack_frames.py in <module>() 
     6 
     7 if __name__ == '__main__': 
(A)----> 8  df = test(pd.DataFrame(range(3))) 

/test/stack_frames.py in test(df) 
     2 
     3 def test(df): 
(B)----> 4  df[:,0] = 4 
     5  return df 
     6 

/usr/local/lib/python2.7/dist-packages/pandas/core/frame.pyc in __setitem__(self, key, value) 
    2355   else: 
    2356    # set column 
-> 2357    self._set_item(key, value) 
    2358 
    2359  def _setitem_slice(self, key, value): 

/usr/local/lib/python2.7/dist-packages/pandas/core/frame.pyc in _set_item(self, key, value) 
    2421 
    2422   self._ensure_valid_index(value) 
-> 2423   value = self._sanitize_column(key, value) 
    2424   NDFrame._set_item(self, key, value) 
    2425 

/usr/local/lib/python2.7/dist-packages/pandas/core/frame.pyc in _sanitize_column(self, key, value) 
    2602 
    2603   # broadcast across multiple columns if necessary 
-> 2604   if key in self.columns and value.ndim == 1: 
    2605    if (not self.columns.is_unique or 
    2606      isinstance(self.columns, MultiIndex)): 

/usr/local/lib/python2.7/dist-packages/pandas/indexes/base.pyc in __contains__(self, key) 
    1232 
    1233  def __contains__(self, key): 
-> 1234   hash(key) 
    1235   # work around some kind of odd cython bug 
    1236   try: 

TypeError: unhashable type 
> /usr/local/lib/python2.7/dist-packages/pandas/indexes/base.py(1234)__contains__() 
    1232 
    1233  def __contains__(self, key): 
(C)-> 1234   hash(key) 
    1235   # work around some kind of odd cython bug 
    1236   try: 

ipdb> 

現在理想情況下,我想在調試器開始在(B)的第二個最早的幀,或甚至在(A)。但絕對不在(C)默認情況下。

+1

http:// stackoverflow。com/questions/37069323/stop-at-at-my-not-library-code可能是相關的。 –

回答

2

爲自己記錄過程的長篇答案。底部半工作解決方案:

失敗的嘗試在這裏:

import sys 
import pdb 
import pandas as pd 

def test(df): # (A) 
    df[:,0] = 4 #Bad indexing on dataframe, will cause error 
    return df 

mypdb = pdb.Pdb(skip=['pandas.*']) 
mypdb.reset() 

df = test(pd.DataFrame(range(3))) # (B) # fails. 

mypdb.interaction(None, sys.last_traceback) # doesn't work. 

Pdb skip documentation:

跳躍的說法,如果有,一定要全域式的模塊名稱模式的迭代。調試器不會進入與匹配其中一種模式的模塊相關的幀。

Pdb source code:

class Pdb(bdb.Bdb, cmd.Cmd): 

    _previous_sigint_handler = None 

    def __init__(self, completekey='tab', stdin=None, stdout=None, skip=None, 
       nosigint=False, readrc=True): 
     bdb.Bdb.__init__(self, skip=skip) 
     [...] 

# Post-Mortem interface 

def post_mortem(t=None): 
    # handling the default 
    if t is None: 
     # sys.exc_info() returns (type, value, traceback) if an exception is 
     # being handled, otherwise it returns None 
     t = sys.exc_info()[2] 
    if t is None: 
     raise ValueError("A valid traceback must be passed if no " 
         "exception is being handled") 

    p = Pdb() 
    p.reset() 
    p.interaction(None, t) 

def pm(): 
    post_mortem(sys.last_traceback) 

Bdb source code:

class Bdb: 
    """Generic Python debugger base class. 
    This class takes care of details of the trace facility; 
    a derived class should implement user interaction. 
    The standard debugger class (pdb.Pdb) is an example. 
    """ 

    def __init__(self, skip=None): 
     self.skip = set(skip) if skip else None 
    [...] 
    def is_skipped_module(self, module_name): 
     for pattern in self.skip: 
      if fnmatch.fnmatch(module_name, pattern): 
       return True 
     return False 

    def stop_here(self, frame): 
     # (CT) stopframe may now also be None, see dispatch_call. 
     # (CT) the former test for None is therefore removed from here. 
     if self.skip and \ 
       self.is_skipped_module(frame.f_globals.get('__name__')): 
      return False 
     if frame is self.stopframe: 
      if self.stoplineno == -1: 
       return False 
      return frame.f_lineno >= self.stoplineno 
     if not self.stopframe: 
      return True 
     return False 

很顯然,不用於後驗屍跳躍列表。爲了解決這個問題,我創建了一個覆蓋安裝方法的自定義類。

import pdb 

class SkipPdb(pdb.Pdb): 
    def setup(self, f, tb): 
     # This is unchanged 
     self.forget() 
     self.stack, self.curindex = self.get_stack(f, tb) 
     while tb: 
      # when setting up post-mortem debugging with a traceback, save all 
      # the original line numbers to be displayed along the current line 
      # numbers (which can be different, e.g. due to finally clauses) 
      lineno = pdb.lasti2lineno(tb.tb_frame.f_code, tb.tb_lasti) 
      self.tb_lineno[tb.tb_frame] = lineno 
      tb = tb.tb_next 

     self.curframe = self.stack[self.curindex][0] 
     # This loop is new 
     while self.is_skipped_module(self.curframe.f_globals.get('__name__')): 
      self.curindex -= 1 
      self.stack.pop() 
      self.curframe = self.stack[self.curindex][0] 
     # The rest is unchanged. 
     # The f_locals dictionary is updated from the actual frame 
     # locals whenever the .f_locals accessor is called, so we 
     # cache it here to ensure that modifications are not overwritten. 
     self.curframe_locals = self.curframe.f_locals 
     return self.execRcLines() 

    def pm(self): 
     self.reset() 
     self.interaction(None, sys.last_traceback) 

如果以這個爲:

x = 42 
df = test(pd.DataFrame(range(3))) # (B) # fails. 
# fails. Then do: 
mypdb = SkipPdb(skip=['pandas.*']) 
mypdb.pm() 
>> <ipython-input-36-e420cf1b80b2>(2)<module>() 
>-> df = test(pd.DataFrame(range(3))) # (B) # fails. 
> (Pdb) l 
> 1 x = 42 
> 2 -> df = test(pd.DataFrame(range(3))) # (B) # fails. 
> [EOF] 

你落入右框。現在你只是需要弄清楚ipython如何調用他們的pdb pm/post_mortem函數,並創建一個類似的腳本。其中appears to be hard,所以我幾乎放棄在這裏。

此外這不是一個很好的實現。它假定你想跳過的幀位於堆棧的頂部,並且會產生奇怪的結果。例如。 df.apply的輸入函數中的錯誤會產生一些超級怪異的東西。

TLDR:不支持stdlib,但可以創建自己的調試器類,但使用IPythons調試器來處理它是不平凡的。

+0

在設置跳過列表時,它看起來像調用'set_trace'是正確的語法,例如, 'import pdb; pdb.Pdb(skip = ['django。*'])。set_trace()' – user2699

+0

這將在調用堆棧frame._處輸入調試器。但是我們想要把它出錯的最後一個堆棧跟蹤,並在那裏輸入調試器。 –

相關問題