python pdb: возобновить выполнение кода после исключения? - PullRequest
4 голосов
/ 08 декабря 2011

Если я запускаю код с включенной магией ipython %pdb и код выдает исключение, есть ли какой-нибудь способ заставить код продолжить выполнение после этого?

например, скажем, исключение составляет ValueError: x=0 not allowed. Могу ли я в pdb установить x=1 и позволить коду продолжить (возобновить) выполнение?

1 Ответ

5 голосов
/ 08 декабря 2011

Я не думаю, что вы можете возобновить код посмертно (т. Е. На самом деле возникла исключительная ситуация, вызвавшая вызов отладчика).То, что вы можете сделать, - это установить точки останова в вашем коде, где вы видели ошибки, и это позволяет вам изменять значения и продолжать программу, избегая ошибок.

При наличии сценария 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]:
...