4

一个 Python 调试函数

 4 years ago
source link: https://blog.lilydjwg.me/2012/1/9/a-python-debug-function.31673.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

一个 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)

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK