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

4 投票
1 回答
888 浏览
提问于 2025-04-16 11:10

我正在做一个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.

问题是,错误信息并没有告诉我数据文件的哪一行出了问题。我该怎么调试呢?我能想到的就是在ipython中有一个功能,当你执行某个操作时,如果出现了错误,ipython会自动让你进入一个调试模式,这样你就可以逐步查看发生了什么。我该怎么在这个情况下做到呢?有没有什么命令行选项可以让python也这样做?我该怎么做才能调试这个问题呢?

1 个回答

6

这个Python小技巧可以安装一个调试工具,当程序出现未处理的错误时,它会自动启动:

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

简单来说,就是在系统的错误处理机制中添加一个钩子,当发生错误时,它会调用pdb.pm()来启动调试器(虽然实际操作比这稍微复杂一些)。

撰写回答