2011-12-07 75 views
4

如果我運行的代碼啓用了ipython %pdb magic並且代碼拋出異常,是否有任何方法可以告訴代碼以後繼續執行?python pdb:捕獲異常後恢復代碼執行?

例如,例外情況是ValueError: x=0 not allowed。我可以在pdb中設置x=1並允許代碼繼續(恢復)執行嗎?

回答

5

我不認爲你可以恢復代碼驗屍(即異常實際上引發,觸發調試器的調用)。 可以做什麼,在您的代碼中放置了斷點,您可以在其中看到錯誤,並允許您更改值並繼續避免該錯誤。

給定一個腳本myscript.py

# myscript.py 
from IPython.core.debugger import Tracer 

# a callable to invoke the IPython debugger. debug_here() is like pdb.set_trace() 
debug_here = Tracer() 

def test(): 
    counter = 0 
    while True: 
     counter += 1 
     if counter % 4 == 0: 
      # invoke debugger here, so we can prevent the forbidden condition 
      debug_here() 
     if counter % 4 == 0: 
      raise ValueError("forbidden counter: %s" % counter) 

     print counter 

test() 

其中不斷遞增計數器,引發錯誤,如果它是由4以往整除但我們已經編輯它拖放到錯誤條件下的調試器,所以我們可能會能夠拯救我們自己。

運行從IPython的這個腳本:

In [5]: run myscript 
1 
2 
3 
> /Users/minrk/dev/ip/mine/myscript.py(14)test() 
    13    debug_here() 
---> 14   if counter % 4 == 0: 
    15    raise ValueError("forbidden counter: %s" % counter) 

# increment counter to prevent the error from raising: 
ipdb> counter += 1 
# continue the program: 
ipdb> continue 
5 
6 
7 
> /Users/minrk/dev/ip/mine/myscript.py(13)test() 
    12    # invoke debugger here, so we can prevent the forbidden condition 

---> 13    debug_here() 
    14   if counter % 4 == 0: 

# if we just let it continue, the error will raise 
ipdb> continue 
--------------------------------------------------------------------------- 
ValueError        Traceback (most recent call last) 
IPython/utils/py3compat.pyc in execfile(fname, *where) 
    173    else: 
    174     filename = fname 
--> 175    __builtin__.execfile(filename, *where) 

myscript.py in <module>() 
    17   print counter 
    18 
---> 19 test() 

myscript.py in test() 
    11   if counter % 4 == 0: 
    12    # invoke debugger here, so we can prevent the forbidden condition 

    13    debug_here() 
    14   if counter % 4 == 0: 
---> 15    raise ValueError("forbidden counter: %s" % counter) 

ValueError: forbidden counter: 8 

In [6]: