调试 iPDB是一个极好的工具,我已经用它查出了很多匪夷所思的bug。pip install ipdb 安装该工具,然后在你的代码中import ipdb; ipdb.set_trace() ,然后你会在你的程序运行时,获得一个很好的交互式提示。它每次执行程序的一行并且检查变量。

python内置了一个很好的追踪模块,帮助我搞清楚发生了什么。这里有一个没什么用的python程序:
这里是对这个程序的追踪结果: 1 2 3 4 5 6 7 | ( test )jhaddad@jons-mac-pro ~VIRTUAL_ENV /src $ python -m trace --trace tracing.py 1 ↵
--- modulename: tracing, funcname: <module>
tracing.py(1): a = 1
tracing.py(2): b = 2
tracing.py(3): a = b
--- modulename: trace, funcname: _unsettrace
trace.py(80): sys.settrace(None)
|
当你想要搞清楚其他程序的内部构造的时候,这个功能非常有用。如果你以前用过strace,它们的工作方式很相像

最后,objgraph对于查找内存泄露非常有用。这里有一篇关于如何使用它查找内存泄露的好文。
Gevent Gevent是一个很好的库,封装了Greenlets,使得Python具备了异步调用的功能。是的,非常棒。我最爱的功能是Pool,它抽象了异步调用部分,给我们提供了可以简单使用的途径,一个异步的map()函数:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | from gevent import monkey
monkey.patch_all()
from time import sleep, time
def fetch_url(url):
print "Fetching %s" % url
sleep( 10 )
print "Done fetching %s" % url
from gevent.pool import Pool
urls = [ "http://test.com" , "http://bacon.com" , "http://eggs.com" ]
p = Pool( 10 )
start = time()
p. map (fetch_url, urls)
print time() - start
|
非常重要的是,需要注意这段代码顶部对gevent monkey进行的补丁,如果没有它的话,就不能正确的运行。如果我们让Python连续调用 fetch_url 3次,通常我们期望这个过程花费30秒时间。使用gevent: 1 2 3 4 5 6 7 8 | (test)jhaddad@jons - mac - pro ~VIRTUAL_ENV / src$ python g.py
Fetching http: / / test.com
Fetching http: / / bacon.com
Fetching http: / / eggs.com
Done fetching http: / / test.com
Done fetching http: / / bacon.com
Done fetching http: / / eggs.com
10.001791954
|
如果你有很多数据库调用或是从远程URLs获取,这是非常有用的。我并不是很喜欢回调函数,所以这一抽象对我来说效果很好。
结论 好吧,如果你看到这里了,那么你很可能已经学到了一些新东西。这些工具,在过去的一年里对我影响重大。找打它们花费了不少时间,所以希望本文能够减少其他人想要很好利用这门语言需要付出的努力。 |