import sys
class ExceptionHook:
instance = None
def __call__(self, *args, **kwargs):
if self.instance is None:
from IPython.core import ultratb
self.instance = ultratb.FormattedTB(mode=‘Plain‘,
color_scheme=‘Linux‘, call_pdb=1)
return self.instance(*args, **kwargs)
sys.excepthook = ExceptionHook()

a = 1
b = 0
a / b
? python test.py
Traceback (most recent call last):
File "test.py", line 4, in <module>
a / b
ZeroDivisionError: integer division or modulo by zero
? ipython test.py --pdb
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
/Users/dongweiming/test/test.py in <module>()
2 b = 0
3
----> 4 a / b
ZeroDivisionError: integer division or modulo by zero
*** NameError: name ‘pdb‘ is not defined
> /Users/dongweiming/test/test.py(4)<module>()
1 a = 1
2 b = 0
3
----> 4 a / b
ipdb> p b # p是print的别名
0
ipdb> p a
1
ipdb>
ipdb> help
Documented commands (type help <topic>):
========================================
EOF bt cont enable jump pdef psource run unt
a c continue exit l pdoc q s until
alias cl d h list pfile quit step up
args clear debug help n pinfo r tbreak w
b commands disable ignore next pinfo2 restart u whatis
break condition down j p pp return unalias where
2. 在对应位置使用print和logging。这是最基础的玩法。我一般只会在已经心理有数,只是需要看看日志输出来确认的时候加临时的。平时的应用日志也会有常规的记录,并且会记录堆栈(当然,使用sentry之类的方式搜集日志是最好的),比如重要的上线过程中,出了问题但是开发环境又不好模拟出来的时候,「tail -f」日志文件们,这样出现问题一看就看到了。 说到这里再推荐一个很有意思的项目: GitHub - zestyping/q: Quick and dirty debugging output for tired programmers. ,它是在我看pycon2013演讲中发现的,有兴趣可以看看, PyVideo.org · Lightning Talks。我之前常用它。import sys
def get_cur_info():
print sys._getframe().f_code.co_filename # 当前文件名
print sys._getframe(0).f_code.co_name # 当前函数名
print sys._getframe(1).f_code.co_name # 调用该函数的函数的名字,如果没有被调用,则返回module
print sys._getframe().f_lineno # 当前行号
原文:http://www.cnblogs.com/zhizhan/p/6009573.html