Debug

我们需要知道出错时,哪些变量的值是正确的,哪些变量的值是错误的,因此,需要一整套调试程序的手段来修复bug。

print()

you ahve to delete them after, so it's kinda messy

assert()

print() can be replaced by assert()

def foo(s):
    n = int(s)
    ##assert to replace print out n
    assert n != 0, 'n is zero!'
    return 10 / n

def main():
    foo('0')

如果断言失败,assert语句本身就会抛出AssertionError:

$ python3 err.py
Traceback (most recent call last):
  ...
AssertionError: n is zero!

程序中如果到处充斥着assert,和print()相比也好不到哪去。不过,启动Python解释器时可以用-O参数来关闭assert:

$ python3 -O err.py
Traceback (most recent call last):
  ...
ZeroDivisionError: division by zero

logging

won't raise error, can also output to file

import logging
logging.basicConfig(level=logging.INFO)

s = '0'
n = int(s)
logging.info('n = %d' % n)
print(10 / n)

这就是logging的好处,它允许你指定记录信息的级别,有

  • debug
  • info
  • warning
  • error 当我们指定level=INFO时,logging.debug就不起作用了。同理,指定level=WARNING后,debug和info就不起作用了。这样一来,你可以放心地输出不同级别的信息,也不用删除,最后统一控制输出哪个级别的信息。

logging的另一个好处是通过简单的配置,一条语句可以同时输出到不同的地方,比如console和文件。

pdb

python debugger pdb, single-step run

pdb.set_trace()

IDE

  • pycharm
  • eclipse with pydev