Python调试

Python中可以使用断言assert,logging等来进行调试

断言

def fun(s):
    n = int(s)
    assert n != 0, 'n is zero!'
    return 10 / n

def main():
    fun('0')

assert后面的语句不为True,则assert会抛出异常AssertionError,并显示后一句'n is zero':

Traceback (most recent call last):
  File "hello.py", line 12, in <module>
    main()
  File "hello.py", line 9, in main
    fun('0')
  File "hello.py", line 4, in fun
    assert n != 0, 'n is zero!'
AssertionError: n is zero!

在我们不需要使用assert时可以在启动Python解释器时,添加-O(大写字母O)参数来关闭断言:

..path:> python -O hello.py
Traceback (most recent call last):
  File "hello.py", line 12, in <module>
    main()
  File "hello.py", line 9, in main
    fun('0')
  File "hello.py", line 5, in fun
    return 10 / n
ZeroDivisionError: division by zero

关闭后,解释器将忽略assert,可以把它看作pass

logging

assert相比,logging不会抛出错误,允许指定要输出错误的级别(debug,info,warning,error等)

import logging
# 指定输出错误级别为INFO
logging.basicConfig(level=logging.INFO)

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

print(10/n)

运行结果:

INFO:root:n=0
Traceback (most recent call last):
  File "hello.py", line 9, in <module>
    print(10/n)
ZeroDivisionError: division by zero

在指定输出等级后,其余等级就不起作用,方便控制

此外,logging可以将语句输出到不同地方,如console和文件

pdb

pdb(The Python Debugger)是Python内置的调试器,可以让程序单步运行

控制台中使用

在启动Python解释器时附带参数-m pdb,程序会开始单步运行,等待下一指令:

..path:> python -m pdb hello.py
> c:\users\1\documents\c\python\hello.py(2)<module>()
-> import logging #定位下一步要执行的代码
(Pdb) #等待指令

常用指令:

|h(elp) [command] 无参数时打印所有操作,有则打印相应操作帮助

|l(ist) 查看所有代码

|n(ext) 单步执行代码

|p 变量名 查看变量

|c(ont(inue)) 继续执行,直到遇到断点

|q(uit) 结束调试

更多见官方文档

pdb.set_trace()

首先import pdb,在代码可能出错的地方放置pdb.set_trace()即可设置断点

import pdb

s = '0'
n = int(s)
pdb.set_trace() # 运行到这里会自动暂停
print(10 / n)
Licensed under CC BY-NC-SA 4.0
comments powered by Disqus
蜀ICP备19030250号
Built with Hugo
Theme Stack designed by Jimmy