Skip to Content
Python实用技能学习指南
book

Python实用技能学习指南

by Posts & Telecom Press, Robert Smallshire, Austin Bingham
February 2024
Intermediate to advanced
316 pages
3h 47m
Chinese
Packt Publishing
Content preview from Python实用技能学习指南

第11章 使用PDB进行调试

即使有了一个全面的自动化测试套件,我们仍然可能遇到某些情况,这时就需要使用调试器弄清楚发生了什么。幸运的是,Python标准库自带了一个强大的调试器:PDB。PDB是一个命令行调试器,如果你熟悉像GDB这样的工具,那么你可以很快地上手PDB。

与其他Python调试器相比,PDB的主要优势在于,它是Python的一部分,PDB几乎可以在任何有Python的地方使用,包括嵌入了Python语言的大型系统的专用环境,比如ESRI的ArcGIS地理信息系统。即便如此,若能使用图形调试器比如Jetbrains的PyCharm或微软的Python Tools for Visual Studio,你会感觉更容易一些。你可以跳过本章,但了解PDB非常有必要。

PDB与其他调试工具不同,它不是一个单独的程序,而是一个模块,就像任何其他的Python模块一样。你可以将PDB导入到任何程序中,并使用set_trace()函数调用启动调试器。这个函数在程序执行的任何时刻都可启动调试器。

首先看看PDB,在REPL中使用set_trace()启动调试器:

>>> import pdb
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb)

你会看到,在执行set_trace()之后,提示会从三箭头变成(Pdb)——通过这个可以知道已经进入了调试器。

要做的第一件事就是通过输入help来查看调试器中可用的命令:

(Pdb) help Documented commands (type help <topic>): ======================================== ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.

Read now

Unlock full access

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

人工智能技术与大数据

人工智能技术与大数据

Posts & Telecom Press, Anand Deshpande, Manish Kumar
Kafka权威指南(第2版)

Kafka权威指南(第2版)

Gwen Shapira, Todd Palino, Rajini Sivaram, Krit Petty

Publisher Resources

ISBN: 9781835889626