Python 调试技巧
Python 调试
![](/data/attachment/album/201807/02/085733el0oe0s9adjsdz2j.jpg)


当进行调试时，你有很多选择，但是很难给出一直有效的通用建议（除了“你试过关闭再打开么？”以外）。


这里有一些我最喜欢的 Python 调试技巧。


### 建立一个分支


请相信我。即使你从来没有打算将修改提交回上游，你也会很乐意将你的实验被包含在它们自己的分支中。


不说别的，它会使清理更容易！


### 安装 pdb++


认真地说，如果你使用命令行，它会让你的生活更轻松。


pdb++ 所做的一切就是用更好的模块替换标准的 pdb 模块。以下是你在 `pip install pdbpp` 会看到的：


* 彩色提示！
* 制表符补全！（非常适合探索！）
* 支持切分！


好的，也许最后一个是有点多余……但是非常认真地说，安装 pdb++ 非常值得。


### 探索


有时候最好的办法就是胡乱试试，然后看看会发生什么。在“明显”的位置放置一个断点并确保它被命中。在代码中加入 `print()` 和/或 `logging.debug()` 语句，并查看代码执行的位置。


检查传递给你的函数的参数，检查库的版本（如果你已经非常绝望了）。


### 一次只能改变一件事


在你在探索了一下后，你将会对你可以做的事情有所了解。但在你开始摆弄代码之前，先退一步，考虑一下你可以改变什么，然后只改变一件事。


做出改变后，然后测试一下，看看你是否接近解决问题。如果没有，请将它改回来，然后尝试其他方法。


只更改一件事就可以让你知道什可以工作，哪些不工作。另外，一旦可以工作后，你的新提交将会小得多（因为将有更少的变化）。


这几乎是<ruby> 科学过程 <rt>  Scientific Process </rt></ruby>中所做的事情：一次只更改一个变量。通过让自己看到并衡量一次更改的结果，你可以节省你的理智，并更快地找到解决方案。


### 不要假设，提出问题


偶尔一个开发人员（当然不是你咯！）会匆忙提交一些有问题的代码。当你去调试这段代码时，你需要停下来，并确保你明白它想要完成什么。


不要做任何假设。仅仅因为代码在 `model.py` 文件中并不意味着它不会尝试渲染一些 HTML。


同样，在做任何破坏性的事情之前，仔细检查你的所有外部关联。要删除一些配置数据？**请确保你没有连接到你的生产系统。**


### 聪明，但不要聪明过头


有时候我们编写的代码神奇般地奏效，不知道它是如何做的。


当我们发布代码时，我们可能会觉得自己很聪明，但当代码崩溃时，我们往往会感到愚蠢，我们必须记住它是如何工作的，以便弄清楚它为什么不起作用。


留意任何看起来过于复杂、冗长或极短的代码段。这些可能是隐藏复杂并导致错误的地方。




---


via: <https://pythondebugging.com/articles/python-debugging-tips>


作者：[PythonDebugging.com](https://pythondebugging.com) 选题：[lujun9972](https://github.com/lujun9972) 译者：[geekpi](https://github.com/geekpi) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
When it comes to debugging, there’s a lot of choices that you can make. It is hard to give generic advice that always works (other than “Have you tried turning it off and back on?”).

Here are a few of my favorite Python Debugging tips.

## Make a branch

Trust me on this. Even if you never intend to commit the changes back upstream, you will be glad your experiments are contained within their own branch.

If nothing else, it makes cleanup a lot easier!

## Install pdb++

Seriously. It makes you life easier if you are on the command line.

All that pdb++ does is replace the standard pdb module with 100% PURE AWESOMENESS. Here’s what you get when you `pip install pdbpp`

:

- A Colorized prompt!
- tab completion!
*(perfect for poking around!)* - It slices! It dices!

Ok, maybe the last one is a little bit much… But in all seriousness, installing pdb++ is well worth your time.

## Poke around

Sometimes the best approach is to just mess around and see what happens. Put a break point in an “obvious” spot and make sure it gets hit. Pepper the code with `print()`

and/or `logging.debug()`

statements and see where the code execution goes.

Examine the arguments being passed into your functions. Check the versions of the libraries (if things are getting really desperate).

## Only change one thing at a time

Once you are poking around a bit you are going to get ideas on things you could do. But before you start slinging code, take a step back and think about what you could change, and then only change 1 thing.

Once you’ve made the change, then test and see if you are closer to resolving the issue. If not, change the thing back, and try something else.

Changing only one thing allows you to know what does and doesn’t work. Plus once you do get it working, your new commit is going to be much smaller (because there will be less changes).

This is pretty much what one does in the Scientific Process: only change one variable at a time. By allowing yourself to see and measure the results of one change you will save your sanity and arrive at a working solution faster.

## Assume nothing, ask questions

Occasionally a developer (not you of course!) will be in a hurry and whip out some questionable code. When you go through to debug this code you need to stop and make sure you understand what it is trying to accomplish.

Make no assumptions. Just because the code is in the `model.py`

file doesn’t mean it won’t try to render some HTML.

Likewise, double check all of your external connections before you do anything destructive! Going to delete some configuration data? MAKE SURE YOU ARE NOT CONNECTED TO YOUR PRODUCTION SYSTEM.

## Be clever, but not too clever

Sometimes we write code that is so amazingly awesome it is not obvious how it does what it does.

While we might feel smart when we publish that code, more often than not we will wind up feeling dumb later on when the code breaks and we have to remember how it works to figure out why it isn’t working.

Keep an eye out for any sections of code that look either overly complicated and long, or extremely short. These could be places where complexity is hiding and causing your bugs.