如何将pdb注入失败的Python脚本?

我正在研究一个django项目,它有一个大型夹具,不能加载:

$python manage.py loaddata apps/mainsite/fixtures/test_auctions.json 
/Users/cp/bidsite/.ve/lib/python2.6/site-packages/django/db/models/fields/subclassing.py:80: DeprecationWarning: A Field class whose get_db_prep_save method hasn't been updated to take a `connection` argument.
  new_class = super(SubfieldBase, cls).__new__(cls, name, bases, attrs)
/Users/cp/bidsite/.ve/lib/python2.6/site-packages/django/db/models/fields/subclassing.py:80: DeprecationWarning: A Field class whose get_db_prep_lookup method hasn't been updated to take `connection` and `prepared` arguments.
  new_class = super(SubfieldBase, cls).__new__(cls, name, bases, attrs)
/Users/cp/bidsite/.ve/lib/python2.6/site-packages/celery/task/schedules.py:5: DeprecationWarning: celery.task.schedules is deprecated and renamed to celery.schedules
  "celery.task.schedules is deprecated and renamed to celery.schedules"))
Problem installing fixture 'apps/mainsite/fixtures/test_auctions.json': Traceback (most recent call last):
  File "/Users/cp/bidsite/.ve/lib/python2.6/site-packages/django/core/management/commands/loaddata.py", line 174, in handle
    obj.save(using=using)
  File "/Users/cp/bidsite/.ve/lib/python2.6/site-packages/django/core/serializers/base.py", line 165, in save
    models.Model.save_base(self.object, using=using, raw=True)
  File "/Users/cp/bidsite/.ve/lib/python2.6/site-packages/django/db/models/base.py", line 570, in save_base
    created=(not record_exists), raw=raw, using=using)
  File "/Users/cp/bidsite/.ve/lib/python2.6/site-packages/django/dispatch/dispatcher.py", line 172, in send
    response = receiver(signal=self, sender=sender, **named)
  File "/Users/cp/bidsite/apps/mainsite/models.py", line 257, in update_auction_details
    auction_json = instance.as_json()
  File "/Users/cp/bidsite/apps/mainsite/models.py", line 1110, in as_json
    'product': self.product.as_json(),
  File "/Users/cp/bidsite/.ve/lib/python2.6/site-packages/django/db/models/fields/related.py", line 315, in __get__
    rel_obj = QuerySet(self.field.rel.to).using(db).get(**params)
  File "/Users/cp/bidsite/.ve/lib/python2.6/site-packages/django/db/models/query.py", line 349, in get
    % self.model._meta.object_name)
DoesNotExist: Product matching query does not exist.

问题是堆栈跟踪让我不知道灯具上的哪条线导致了这个错误.我该怎么调试呢?我唯一能想到的是ipythgon中有一个功能,每当你执行一些东西并引发一个异常时,ipython会自动注入一个pdb提示符,这样你就可以踩一下来弄清楚发生了什么.我怎么能这样做呢?是否有用于python的命令行开关?我可以在这做什么来调试这个?

解决方法:

这个Python配方将安装一个从未捕获的异常开始的调试器:

http://code.activestate.com/recipes/65287-automatically-start-the-debugger-on-an-exception/

它的要点是在sys.excepthook中安装一个异常挂钩,在调用时调用pdb.pm()(虽然它稍微复杂一些).

上一篇:CDB与PDB之间的切换方法


下一篇:「Python调试器」,快速定位各种疑难杂症!!!