调试和分析在Python开发中发挥着重要做用。 调试器可帮助程序员分析完整的代码。 调试器设置断点,而剖析器运行咱们的代码,并给咱们执行时间的详细信息。 分析器将识别程序中的瓶颈。咱们将了解pdb Python调试器,cProfile模块和timeit模块来计算Python代码的执行时间。html
涉及内容:python
调试是解决代码中出现阻止软件正常运行问题的过程。linux
Python调试器设置条件断点并可一次调试一行源代码。咱们将使用Python标准库中的pdb模块调试咱们的Python脚本。程序员
参考 http://www.javashuo.com/article/p-nnpskexe-c.htmlwindows
Python支持许多调试工具:bash
pdb模块用于调试Python程序。 Python程序使用pdb交互式源代码调试器来调试程序。 pdb设置断点并检查堆栈。微信
如今咱们将了解如何使用pdb调试器。有三种方法能够使用此调试器:ide
咱们将建立一个pdb_example.py脚本,并在该脚本中添加如下内容:工具
class Student:
def __init__(self, std):
self.count = std
def print_std(self):
for i in range(self.count):
print(i)
return
if __name__ == '__main__':
Student(5).print_std()复制代码
以此脚本为例学习Python调试,咱们将看到如何详细启动调试器。学习
$ python3
Python 3.6.7 |Anaconda, Inc.| (default, Oct 23 2018, 19:16:44)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb_example
>>> import pdb
>>> pdb.run('pdb_example.Student(5).print_std()')
> <string>(1)<module>()
(Pdb)
EOF b cl cont disable exit interact list next quit retval source unalias up
a break clear continue display h j ll p r run step undisplay w
alias bt commands d down help jump longlist pp restart rv tbreak unt whatis
args c condition debug enable ignore l n q return s u until where
(Pdb) continue
0
1
2
3
4复制代码
要继续调试,请在 ( Pdb )提示符后输入continue,而后按Enter键。若是你想知道咱们能够在这里使用的选项,那么在 ( Pdb )提示后按两次Tab键。注意windows下按键可能会无效。
$ python3 -m pdb pdb_example.py
> /home/andrew/code/meil/code/Mastering-Python-Scripting-for-System-Administrators-/Chapter02/pdb_example.py(1)<module>()
-> class Student:
(Pdb) continue
0
1
2
3
4
The program finished and will be restarted复制代码
import pdb
class Student:
def __init__(self, std):
self.count = std
def print_std(self):
for i in range(self.count):
pdb.set_trace()
print(i)
return
if __name__ == '__main__':
Student(5).print_std()复制代码
执行:
$ python3 pdb_example.py
> /home/andrew/code/meil/code/Mastering-Python-Scripting-for-System-Administrators-/Chapter02/pdb_example.py(10)print_std()
-> print(i)
(Pdb) continue
0
> /home/andrew/code/meil/code/Mastering-Python-Scripting-for-System-Administrators-/Chapter02/pdb_example.py(9)print_std()
-> pdb.set_trace()
(Pdb) continue
1
> /home/andrew/code/meil/code/Mastering-Python-Scripting-for-System-Administrators-/Chapter02/pdb_example.py(10)print_std()
-> print(i)
(Pdb) continue
2
...复制代码
扫码关注微信公众学习文章干货资料