1
9
2012
5

一个 Python 调试函数

本文来自依云's Blog,转载请注明。

Python 有个code模块,可以在程序中开个 REPL 交互命令行,就像 Python 解释器的交互执行一样,调试时非常方便。为了偷懒,我又把它包装了下,写下了repl函数(on github):

def repl(local, histfile=None, banner=None):
  import readline
  import rlcompleter
  readline.parse_and_bind('tab: complete')
  if histfile is not None and os.path.exists(histfile):
    # avoid duplicate reading
    readline.clear_history()
    readline.set_history_length(10000)
    readline.read_history_file(histfile)
  import code
  readline.set_completer(rlcompleter.Completer(local).complete)
  code.interact(local=local, banner=banner)
  if histfile is not None:
    readline.write_history_file(histfile)

之所以要现在把这个函数拿出来,是因为我终于解决了一件让我郁闷很久的问题——补全。历史记录是早就弄好了的,可是补全却经常不给力,补不出东西来,只有少数时候比较正常。这个和 Python 解释器自己的 REPL 不一样。最近在开发 XMPP 群,经常要用到,于是终于去读了rlcompleter.py的代码。还好不长,很快就搞定了:默认使用的是__main__.__dict__这个里边的对象进行补全,而不是globals()。给readline重新设置下补全函数就好了:

readline.set_completer(rlcompleter.Completer(local).complete)
Category: python | Tags: python | Read Count: 13200
Iven 说:
Jan 09, 2012 09:50:24 AM

这个和 pdb 有啥区别……

Avatar_small
依云 说:
Jan 09, 2012 12:58:26 PM

这个我会用,pdb 我不会用。。。。

Iven 说:
Jan 09, 2012 01:31:57 PM

在想调试的地方加上:

import pdb

pdb.set_trace()

就可以了……

Avatar_small
依云 说:
Jan 09, 2012 01:41:42 PM

这个不一样啊。。。

Fermat618 说:
Mar 26, 2012 05:04:33 PM

我最近也才看到怎么开补全。以前都是dir()后记住名字再打的。


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter

| Theme: Aeros 2.0 by TheBuckmaker.com