Skip to Content
Python入门指南, 3rd Edition
book

Python入门指南, 3rd Edition

by Bill Lubanovic
September 2025
Intermediate to advanced
660 pages
7h 15m
Chinese
O'Reilly Media, Inc.
Content preview from Python入门指南, 3rd Edition

第 16 章 调试 调试

本作品已使用人工智能进行翻译。欢迎您提供反馈和意见:translation-feedback@oreilly.com

每个人都知道,调试程序的难度是编写程序难度的两倍。 所以,如果你在编写程序时尽可能聪明,你又怎么会调试它呢?

布莱恩-克尼根

调试就像在犯罪电影中扮演侦探,而你同时也是凶手。

菲利佩-福特斯

如果一个孩子问雨从哪里来,我觉得告诉他 "上帝在哭 "很可爱。 如果他问上帝为什么哭,我觉得告诉他 "可能是因为你做了什么 "也很可爱。

杰克-汉迪

首先进行测试(第 15 章)。,测试做得越好,以后需要修复的问题就越少。然而,错误是会发生的,当以后发现它们时就需要修复。

当代码出现问题时,通常是因为你刚刚做了什么,所以你通常会 "自下而上 "地进行调试,从最近的修改开始。1

但有时,原因并不在这里,而是在你信任并认为有效的地方。 你会认为,如果很多人都在使用的地方出现了问题,现在应该已经有人注意到了。 但事实并非总是如此。 我遇到过的最棘手的 bug,每次都花了一个多星期才修复,而这些 bug 都是由我认为很好的外部代码引起的。 因此,在责怪镜子里的人之后,请质疑你的假设。 这是一种 "自上而下 "的方法,需要更长的时间。

当你修复了隐藏着另一个潜在错误的代码时,特别隐蔽的错误就会出现。

在 Python 中,与 C 和 C++ 等语言不同,不会出现 整类的内存安全bug,因为你不是在手动地弄乱内存。但你仍然可能遇到其他语言的噩梦,比如线程安全(参见第 23 章)。

下面是一些调试技巧,有些很快,有些则比较复杂。

断言

使用assert 来 声明某些事情必须为真,否则就会当场引发异常。断言通常在编码的早期阶段非常有用,因为你还在摸索阶段,还缺少以后会出现的检查和测试。通常,你会使用断言来检查会引发异常的 "不可能 "数据,比如除以零,或None,而在这里预期的是一个有效值。

你可以断言某些事情为真,如果不是,就会引发一个AssertionError ,并详细说明失败的原因:

>>> x = 5
>>> assert x == 5
>>> assert x > 4
>>> assert x == 0
Traceback (most recent call last):
  File "<python-input-3>", line 1, in <module>
    assert x == 0
           ^^^^^^
AssertionError

您可以在测试表达式后加入一个字符串,如果断言失败,也会打印出该字符串:

>>> x = 5
>>> assert x == 0, "I thought x was zero!"
Traceback (most recent call last):
  File "<python-input-5>", line 1, in <module>
    assert x == 0, "I thought x was zero!"
           ^^^^^^
AssertionError: I thought x was zero!

通过向 Python解释器传递-O选项,可以禁用断言检查。

打印

在 Python 中,最简单的调试方法就是打印字符串。一些有用的打印内容包括vars() ,它可以提取局部变量的值,包括函数参数:

>>> def func(*args, **kwargs):
...     print(vars())
...
>>> func(1, 2, 3)
{'args': (1, 2, 3), ...
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

生成式人工智能设计模式

生成式人工智能设计模式

Valliappa Lakshmanan, Hannes Hapke

Publisher Resources

ISBN: 9798341668898