What is the simplest way of using Python pdb to inspect the cause of an unhandled exception?

*爱你&永不变心* 提交于 2019-12-07 07:49:37

问题


I just converted all my unit test data from JSON to YAML, and now an exception is raised somewhere in my code. More specifically, this is printed traceback:

Traceback (most recent call last):
  File "tests/test_addrtools.py", line 95, in test_validate_correctable_addresses
    self.assertTrue(self.validator(addr), msg)
  File "/Users/tomas/Dropbox/Broadnet/broadpy/lib/broadpy/addrtools.py", line 608, in __call__
    self.validate(addr)
  File "/Users/tomas/Dropbox/Broadnet/broadpy/lib/broadpy/addrtools.py", line 692, in validate
    if self._correction_citytypo(addr): return
  File "/Users/tomas/Dropbox/Broadnet/broadpy/lib/broadpy/addrtools.py", line 943, in _correction_citytypo
    ratio = lev_ratio(old_city, city)
TypeError: ratio expected two Strings or two Unicodes

Now, the file "addrtools.py" on line 943 contains the answer to my problem. I want to see the type and values of old_city and city in the scope where the exception is raised. I have this sort of issue all the time, and a quick and painless method of using pdb to inspect the locals in the scope where the exception is raised would save me tons of time in the future.


I did try the solution posted in the answer to this question, but the post-mortem function places me in python2.7/unittest/main.py(231)runTests() which doesn't help me a whole lot. I guess this is because the exception is caught and re-raised from the unittest code.


回答1:


Wrap it with that:

def debug_on(*exceptions):
    if not exceptions:
        exceptions = (AssertionError, )
    def decorator(f):
        @functools.wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except exceptions:
                pdb.post_mortem(sys.exc_info()[2])
        return wrapper
    return decorator

Example:

@debug_on(TypeError)
def buggy_function()
    ....
    raise TypeError



回答2:


The unittest superset nose has an option that drops you to pdb when a test fails, if it's okay for you to use nose as your test runner:

--pdb                 Drop into debugger on errors
--pdb-failures        Drop into debugger on failures


来源:https://stackoverflow.com/questions/12689985/what-is-the-simplest-way-of-using-python-pdb-to-inspect-the-cause-of-an-unhandle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!