← 学习库 Think Python (2e) · 中英对照 目录

Appendix A  Debugging 附录 A 调试

本页译自 Think Python 2e(Allen B. Downey)· Appendix A Debugging。代码块保留英文原文不翻译;正文段段对照,中文块可用右下角按钮隐藏。

Different kinds of errors can occur in a program, and it is useful to distinguish among them in order to track them down more quickly:

程序中会出现不同类型的错误,学会区分它们有助于更快地定位问题:

The first step in debugging is to figure out which kind of error you are dealing with. Although the following sections are organized by error type, some techniques are applicable in more than one situation.

调试的第一步是弄清你面对的是哪一类错误。尽管下面按错误类型分节,但有些技巧对多种情况都适用。

A.1 Syntax errors A.1 语法错误

Syntax errors are usually easy to fix once you figure out what they are. Unfortunately, the error messages are often not helpful. The most common messages are def000008 and def000009, neither of which is very informative.

语法错误只要弄清原因,通常很容易修。可惜的是,报错信息往往没什么帮助。最常见的两条是 def000010(语法无效)和 def000011(字符无效),都说不到点子上。

On the other hand, the message does tell you where in the program the problem occurred. Actually, it tells you where Python noticed a problem, which is not necessarily where the error is. Sometimes the error is prior to the location of the error message, often on the preceding line.

不过,报错信息至少会告诉你问题出在程序的什么位置。准确地说,它告诉你的是 Python「注意到」问题之处,不一定就是真正的错误所在。有时错误在报错位置之前,常在上一行。

If you are building the program incrementally, you should have a good idea about where the error is. It will be in the last line you added.

如果你是增量式地写程序,应该对错误位置心里有数——它就在你最后加的那一行。

If you are copying code from a book, start by comparing your code to the book’s code very carefully. Check every character. At the same time, remember that the book might be wrong, so if you see something that looks like a syntax error, it might be.

如果你是从书上抄代码,先逐字比对你的代码和书上的代码,一个字符都别放过。同时也要记住,书也可能印错;所以看到像语法错误的东西,它很可能真是语法错误。

Here are some ways to avoid the most common syntax errors:

下面几条能帮你避开最常见的语法错误:
  1. Make sure you are not using a Python keyword for a variable name.
  2. Check that you have a colon at the end of the header of every compound statement, including def, def00, if, and def statements.
  3. Make sure that any strings in the code have matching quotation marks.
  4. If you have multiline strings with triple quotes (single or double), make sure you have terminated the string properly. An unterminated string may cause an def000016 error at the end of your program, or it may treat the following part of the program as a string until it comes to the next string. In the second case, it might not produce an error message at all!
  5. An unclosed opening operator—(, (, or (—makes Python continue with the next line as part of the current statement. Generally, an error occurs almost immediately in the next line.
  6. Check for the classic ( instead of if inside a conditional.
  7. Check the indentation to make sure it lines up the way it is supposed to. Python can handle space and tabs, but if you mix them it can cause problems. The best way to avoid this problem is to use a text editor that knows about Python and generates consistent indentation.
  1. 确认没有拿 Python 关键字当变量名。
  2. 检查每个复合语句的头部末尾都有冒号,包括 defdef00、ifdef 语句。
  3. 确认代码里的字符串都有成对的引号。
  4. 如果你用了三引号(单或双)的多行字符串,确认字符串正确闭合。未闭合的字符串可能在程序末尾引发 def000026 错误,也可能把后面一段程序当字符串处理,直到遇见下一个字符串。第二种情况下,它可能根本不报错!
  5. 没闭合的左括号——(((——会让 Python 把下一行继续当作当前语句的一部分。通常下一行就会立刻报错。
  6. 检查条件判断里有没有把经典的 if 误写成 (
  7. 检查缩进,确保对齐正确。Python 空格和制表符都能处理,但混用会出问题。最好的办法是用一个懂 Python 的编辑器,由它生成一致的缩进。

If nothing works, move on to the next section...

如果都没用,就翻到下一节……

A.1.1 I keep making changes and it makes no difference. A.1.1 我不断改代码,却毫无变化

If the interpreter says there is an error and you don’t see it, that might be because you and the interpreter are not looking at the same code. Check your programming environment to make sure that the program you are editing is the one Python is trying to run.

如果解释器说有错,你却看不出来,也许是因为你和解释器看的不是同一份代码。检查你的开发环境,确认你正在编辑的程序就是 Python 试图运行的那一份。

If you are not sure, try putting an obvious and deliberate syntax error at the beginning of the program. Now run it again. If the interpreter doesn’t find the new error, you are not running the new code.

如果不确定,可以在程序开头故意放一个明显的语法错误,再运行一遍。如果解释器没发现这个新错误,说明你跑的根本不是新代码。

There are a few likely culprits:

以下几处常是罪魁祸首:

If you get stuck and you can’t figure out what is going on, one approach is to start again with a new program like “Hello, World!,” and make sure you can get a known program to run. Then gradually add the pieces of the original program to the new one.

如果卡住、怎么也想不通,有个办法:从一个像「Hello, World!」这样的新程序重新开始,先确认这个已知能跑的程序确实能跑起来,再把原程序的各个部分逐步加进去。

A.2 Runtime errors A.2 运行时错误

Once your program is syntactically correct, Python can compile it and at least start running it. What could possibly go wrong?

程序语法过关后,Python 就能编译它,至少能开始运行。还能出什么岔子呢?

A.2.1 My program does absolutely nothing. A.2.1 我的程序什么都没做

This problem is most common when your file consists of functions and classes but does not actually invoke anything to start execution. This may be intentional if you only plan to import this module to supply classes and functions.

这个问题最常见于:你的文件里全是要函数有函数、要类有类,却没有任何东西真正去启动执行。如果你本来就只想把这个模块 import 进去提供类和函数,那是有意为之。

If it is not intentional, make sure that you are invoking a function to start execution, or execute one from the interactive prompt. Also see the “Flow of Execution” section below.

若非有意为之,确认你调用了某个函数来启动执行,或者在交互提示符下执行一个。另见下面的「执行流程(flow of execution)」一节。

A.2.2 My program hangs. A.2.2 我的程序卡死了

If a program stops and seems to be doing nothing, it is “hanging.” Often that means that it is caught in an infinite loop or infinite recursion.

如果程序停住、像是在发呆,那就是「卡死(hanging)」了。这通常意味着它陷进了无限循环(infinite loop)或无限递归(infinite recursion)。

Infinite Loop 无限循环

If you think you have an infinite loop and you think you know what loop is causing the problem, add a def00 statement at the end of the loop that prints the values of the variables in the condition and the value of the condition.

如果你觉得有无限循环,且知道是哪个循环惹的祸,就在循环末尾加一条 def00 语句,打印出条件中各变量的值以及条件本身的值。

For example:

例如:
def000042

Now when you run the program, you will see three lines of output for each time through the loop. The last time through the loop, the condition should be def00. If the loop keeps going, you will be able to see the values of ( and (, and you might figure out why they are not being updated correctly.

运行程序后,每走一遍循环你会看到三行输出。循环最后一次时,条件应当为 def00。如果循环还在继续,你就能看到 (( 的值,也许能想通为什么它们没被正确更新。

Infinite Recursion 无限递归

Most of the time, an infinite recursion will cause the program to run for a while and then produce a def000049 error.

多数情况下,无限递归会让程序跑一阵子,然后抛出 def000050(超出最大递归深度)错误。

If you suspect that a function or method is causing an infinite recursion, start by checking to make sure that there is a base case. In other words, there should be some condition that will cause the function or method to return without making a recursive invocation. If not, then you need to rethink the algorithm and identify a base case.

如果你怀疑某个函数或方法引发了无限递归,先检查是否设有基础情形(base case)。也就是说,应当存在某个条件,能让函数或方法在不做递归调用的情况下返回。如果没有,你就需要重新思考算法,找出一个基础情形。

If there is a base case but the program doesn’t seem to be reaching it, add a def00 statement at the beginning of the function or method that prints the parameters. Now when you run the program, you will see a few lines of output every time the function or method is invoked, and you will see the parameters. If the parameters are not moving toward the base case, you will get some ideas about why not.

如果有基础情形、程序却似乎到不了,就在函数或方法开头加一条打印参数的 def00 语句。运行后,函数或方法每次被调用你都会看到几行输出,也能看到参数。如果参数没有朝基础情形推进,你就能琢磨出原因了。

Flow of Execution 执行流程

If you are not sure how the flow of execution is moving through your program, add def00 statements to the beginning of each function with a message like “entering function def,” where def is the name of the function.

如果你拿不准执行流程(flow of execution)是怎么在程序里流动的,就在每个函数开头加 def00 语句,打印诸如 “entering function def”(进入函数 foo)之类的信息,其中 def 是函数名。

Now when you run the program, it will print a trace of each function as it is invoked.

运行后,程序会在每个函数被调用时打印出一条轨迹。

A.2.3 When I run the program I get an exception. A.2.3 一运行程序就出现异常

If something goes wrong during runtime, Python prints a message that includes the name of the exception, the line of the program where the problem occurred, and a traceback.

运行时一旦出错,Python 会打印一条消息,包含异常的名称、出错的程序行号,以及一份回溯(traceback)。

The traceback identifies the function that is currently running, and then the function that invoked it, and then the function that invoked that, and so on. In other words, it traces the sequence of function invocations that got you to where you are. It also includes the line number in your file where each of these calls occurs.

回溯先标出当前正在运行的函数,再标出调用它的函数,然后是调用那个函数的函数,依此类推。换句话说,它把把你带到当前位置的这一系列函数调用都追踪了出来。它还会给出你文件里每次调用所在的行号。

The first step is to examine the place in the program where the error occurred and see if you can figure out what happened. These are some of the most common runtime errors:

第一步是查看出错的位置,看看能不能想明白发生了什么。下面是最常见的一些运行时错误:
NameError:
You are trying to use a variable that doesn’t exist in the current environment. Remember that local variables are local. You cannot refer to them from outside the function where they are defined.
TypeError:
There are several possible causes:
  • You are trying to use a value improperly. Example: indexing a string, list, or tuple with something other than an integer.
  • There is a mismatch between the items in a format string and the items passed for conversion. This can happen if either the number of items does not match or an invalid conversion is called for.
  • You are passing the wrong number of arguments to a function or method. For methods, look at the method definition and check that the first parameter is def0. Then look at the method invocation; make sure you are invoking the method on an object with the right type and providing the other arguments correctly.
KeyError:
You are trying to access an element of a dictionary using a key that the dictionary does not contain.
AttributeError:
You are trying to access an attribute or method that does not exist. Check the spelling! You can use def to list the attributes that do exist. If an AttributeError indicates that an object has def00006, that means that it is def0. One common cause is forgetting to return a value from a function; if you get to the end of a function without hitting a def000 statement, it returns def0. Another common cause is using the result from a list method, like def0, that returns def0.
IndexError:
The index you are using to access a list, string, or tuple is greater than its length minus one. Immediately before the site of the error, add a def00 statement to display the value of the index and the length of the array. Is the array the right size? Is the index the right value?
NameError(名称错误):
你想使用一个在当前环境里不存在的变量。记住局部变量就是局部的,不能在定义它的函数之外引用。
TypeError(类型错误):
可能的原因有好几种:
  • 你用值的方式不对。例如:用非整数去给字符串、列表或元组做索引。
  • 格式化字符串里的项和传入用于转换的项对不上。项的数量不匹配,或要求的转换方式不合法,都会这样。
  • 你传给函数或方法的实参数量不对。对于方法,去看方法定义,确认第一个形参是 def0;再看方法调用,确认你是在类型正确的对象上调用该方法,并且正确地提供了其他实参。
KeyError(键错误):
你想用字典里没有的键去访问字典元素。
AttributeError(属性错误):
你想访问一个不存在的属性或方法。检查拼写!你可以用 def 列出确实存在的属性。如果 AttributeError 提示某个对象是 def00007,意思是它就是 def0。一个常见原因是忘了从函数返回值:如果函数一路走到结尾都没碰上 def000 语句,它就会返回 def0。另一个常见原因是用了列表方法(如 def0)的返回值,而它返回的是 def0。
IndexError(索引错误):
你用来访问列表、字符串或元组的索引,大于其长度减一。在出错位置前紧挨着加一条 def00 语句,显示出索引的值和数组的长度。数组大小对吗?索引值对吗?

The Python debugger (def) is useful for tracking down Exceptions because it allows you to examine the state of the program immediately before the error. You can read about def at def000079.

Python 调试器(def)对追查异常很有用,因为它能让你在出错前一刻查看程序状态。关于 def 的资料见 def000082。

A.2.4 I added so many def00 statements I get inundated with output. A.2.4 我加了太多 print 语句,被输出淹没了

One of the problems with using def00 statements for debugging is that you can end up buried in output. There are two ways to proceed: simplify the output or simplify the program.

def00 语句调试的一大问题是,你最终会被输出淹没。两条出路:简化输出,或简化程序。

To simplify the output, you can remove or comment out def00 statements that aren’t helping, or combine them, or format the output so it is easier to understand.

要简化输出,可以把没用的 def00 语句删掉或注释掉,或者合并它们,或者把输出格式化得更好懂。

To simplify the program, there are several things you can do. First, scale down the problem the program is working on. For example, if you are searching a list, search a small list. If the program takes input from the user, give it the simplest input that causes the problem.

要简化程序,有几种做法。首先,把程序要处理的问题缩小。例如:你若要搜一个列表,就搜一个列表;程序若从用户处取输入,就给它能触发问题的最简单输入。

Second, clean up the program. Remove dead code and reorganize the program to make it as easy to read as possible. For example, if you suspect that the problem is in a deeply nested part of the program, try rewriting that part with simpler structure. If you suspect a large function, try splitting it into smaller functions and testing them separately.

其次,清理程序。删掉没用的死代码,重新组织程序,让它尽量好读。例如:若怀疑问题出在嵌套很深的地方,试着用更简单的结构重写那部分;若怀疑某个大函数,试着把它拆成小函数,分别测试。

Often the process of finding the minimal test case leads you to the bug. If you find that a program works in one situation but not in another, that gives you a clue about what is going on.

常常,找出最小测试用例的过程就把你领到了缺陷(bug)面前。如果你发现程序在一种情况下正常、另一种情况下却不行,这就给了你一条线索。

Similarly, rewriting a piece of code can help you find subtle bugs. If you make a change that you think shouldn’t affect the program, and it does, that can tip you off.

同样,重写一段代码也能帮你揪出隐蔽的缺陷。如果你做了自以为不影响程序的改动,它却影响了,这就可能让你警觉。

A.3 Semantic errors A.3 语义错误

In some ways, semantic errors are the hardest to debug, because the interpreter provides no information about what is wrong. Only you know what the program is supposed to do.

从某些方面说,语义错误最难调试,因为解释器不会告诉你哪里错了——只有你自己知道程序本该做什么。

The first step is to make a connection between the program text and the behavior you are seeing. You need a hypothesis about what the program is actually doing. One of the things that makes that hard is that computers run so fast.

第一步,是把程序文本和你看到的行为联系起来。你需要对程序实际在做什么提出一个假设。难就难在:计算机跑得太快了。

You will often wish that you could slow the program down to human speed, and with some debuggers you can. But the time it takes to insert a few well-placed def00 statements is often short compared to setting up the debugger, inserting and removing breakpoints, and “stepping” the program to where the error is occurring.

你常常希望能让程序慢到人的速度,某些调试器确实可以。不过,插入几条位置得当的 def00 语句,往往比搭好调试器、增删断点、再一步步「step」到出错位置要快得多。

A.3.1 My program doesn’t work. A.3.1 我的程序不工作

You should ask yourself these questions:

你该问自己这几个问题:

In order to program, you need to have a mental model of how programs work. If you write a program that doesn’t do what you expect, very often the problem is not in the program; it’s in your mental model.

要写程序,你得在心里有一套程序如何运作的心智模型。如果你写的程序没按预期工作,问题往往不在程序,而在你的心智模型。

The best way to correct your mental model is to break the program into its components (usually the functions and methods) and test each component independently. Once you find the discrepancy between your model and reality, you can solve the problem.

纠正心智模型最好的办法,是把程序拆成各个组件(通常是函数和方法),分别独立测试。一旦找出模型和现实之间的出入,问题就解决了。

Of course, you should be building and testing components as you develop the program. If you encounter a problem, there should be only a small amount of new code that is not known to be correct.

当然,开发程序时你就该边写边测各组件。如果碰到问题,不应该有太多未经证实正确的新代码。

A.3.2 I’ve got a big hairy expression and it doesn’t do what I expect. A.3.2 我有个又大又乱的表达式,却没按预期工作

Writing complex expressions is fine as long as they are readable, but they can be hard to debug. It is often a good idea to break a complex expression into a series of assignments to temporary variables.

只要够可读,写复杂表达式也没问题;但它们不好调试。把复杂表达式拆成一连串临时变量的赋值,常常是好主意。

For example:

例如:
def000090

This can be rewritten as:

它可以改写成:
def000091

The explicit version is easier to read because the variable names provide additional documentation, and it is easier to debug because you can check the types of the intermediate variables and display their values.

显式版本更好读,因为变量名本身就是额外的文档;也更好调试,因为你能检查中间变量的类型、显示它们的值。

Another problem that can occur with big expressions is that the order of evaluation may not be what you expect. For example, if you are translating the expression x/2 π into Python, you might write:

大表达式还有个问题:求值顺序可能和你预期的不一样。例如,你要把表达式 x/2 π 翻成 Python,可能会写成:
def000092

That is not correct because multiplication and division have the same precedence and are evaluated from left to right. So this expression computes x π / 2.

这不对,因为乘除优先级相同、从左到右求值。所以这个式子算的是 x π / 2。

A good way to debug expressions is to add parentheses to make the order of evaluation explicit:

调试表达式的好办法是加括号,把求值顺序显式写出来:
def000093

Whenever you are not sure of the order of evaluation, use parentheses. Not only will the program be correct (in the sense of doing what you intended), it will also be more readable for other people who haven’t memorized the rules of precedence.

只要拿不准求值顺序,就用括号。这样程序不仅正确(即按你本意运行),对那些没背下优先级规则的人也更易读。

A.3.3 I’ve got a function or method that doesn’t return what I expect. A.3.3 我有个函数或方法,返回值不是我预期的

If you have a def000 statement with a complex expression, you don’t have a chance to print the def000 value before returning. Again, you can use a temporary variable. For example, instead of:

如果你的 def000 语句带的是一个复杂表达式,你就没机会在返回前打印 def000 值。这时照样可以用临时变量。例如,不要写:
def000098

you could write:

你可以写成:
def000099

Now you have the opportunity to display the value of def00 before returning.

这样你就有机会在返回前显示 def00 的值了。

A.3.4 I’m really, really stuck and I need help. A.3.4 我真的、真的卡住了,需要帮忙

First, try getting away from the computer for a few minutes. Computers emit waves that affect the brain, causing these symptoms:

首先,试着离开电脑几分钟。计算机发出的电波会影响大脑,导致下面这些症状:

If you find yourself suffering from any of these symptoms, get up and go for a walk. When you are calm, think about the program. What is it doing? What are some possible causes of that behavior? When was the last time you had a working program, and what did you do next?

如果你发现自己中了上面任何一条,站起来去走一走。等心静了,想想这个程序:它在做什么?这种行为可能由什么引起?你上一次程序还能跑是什么时候,之后又做了什么?

Sometimes it just takes time to find a bug. I often find bugs when I am away from the computer and let my mind wander. Some of the best places to find bugs are trains, showers, and in bed, just before you fall asleep.

有时候找缺陷就是需要时间。我常在离开电脑、让思绪游荡时找到缺陷。火车上、淋浴时、还有临睡前躺在床上的时刻,都是找缺陷的好地方。

A.3.5 No, I really need help. A.3.5 不,我真的需要帮忙

It happens. Even the best programmers occasionally get stuck. Sometimes you work on a program so long that you can’t see the error. A fresh pair of eyes is just the thing.

这种事谁都会碰上。哪怕最厉害的程序员偶尔也会卡住。有时你盯着一个程序太久,反而看不见错误了。这时候就需要一双新鲜的眼睛。

Before you bring someone else in, make sure you are prepared. Your program should be as simple as possible, and you should be working on the smallest input that causes the error. You should have def00 statements in the appropriate places (and the output they produce should be comprehensible). You should understand the problem well enough to describe it concisely.

找人帮忙前,先确保自己准备好了。程序要尽量简化,你要在能触发错误的最小输入上工作。该加 def00 的地方要加上(而且它产生的输出要能看得懂)。你要对问题理解到能简洁描述它的程度。

When you bring someone in to help, be sure to give them the information they need:

找人帮忙时,务必把需要的信息提供给对方:

When you find the bug, take a second to think about what you could have done to find it faster. Next time you see something similar, you will be able to find the bug more quickly.

找到缺陷后,花一秒钟想想:之前本可以怎么做才能更快找到它。下次再见到类似情形,你就能更快定位。

Remember, the goal is not just to make the program work. The goal is to learn how to make the program work.

记住,目标不只是让程序跑起来,而是学会如何让程序跑起来。