Python调试技巧

2024-04-26 10:08:15 发布

您现在位置:Python中文网/ 问答频道 /正文

调试Python的最佳技巧是什么?

请不要只列出一个特定的调试器,而不说明它实际能做什么。

相关


Tags: andthetopicisthisarebutits
3条回答

PDB

您可以使用pdb模块,在任何地方插入pdb.set_trace(),它将充当断点。

>>> import pdb
>>> a="a string"
>>> pdb.set_trace()
--Return--
> <stdin>(1)<module>()->None
(Pdb) p a
'a string'
(Pdb)

要继续执行,请使用c(或contcontinue)。

可以使用pdb执行任意Python表达式。例如,如果发现错误,可以更正代码,然后键入类型表达式以在运行的代码中具有相同的效果

ipdb是IPython的pdb版本。它允许pdb与所有IPython特性一起使用,包括tab completion。

也可以set pdb to automatically run处理未捕获的异常。

Pydb被编写为Pdb的增强版本。福利?

http://pypi.python.org/pypi/pudb,一个全屏的、基于控制台的Python调试器。

Its goal is to provide all the niceties of modern GUI-based debuggers in a more lightweight and keyboard-friendly package. PuDB allows you to debug code right where you write and test it – in a terminal. If you've worked with the excellent (but nowadays ancient) DOS-based Turbo Pascal or C tools, PuDB's UI might look familiar.

pudb screenshot

很适合调试独立脚本,只需运行

python -m pudb.run my-script.py

如果使用pdb,则可以为快捷方式定义别名。我使用这些:

# Ned's .pdbrc

# Print a dictionary, sorted. %1 is the dict, %2 is the prefix for the names.
alias p_ for k in sorted(%1.keys()): print "%s%-15s= %-80.80s" % ("%2",k,repr(%1[k]))

# Print the instance variables of a thing.
alias pi p_ %1.__dict__ %1.

# Print the instance variables of self.
alias ps pi self

# Print the locals.
alias pl p_ locals() local:

# Next and list, and step and list.
alias nl n;;l
alias sl s;;l

# Short cuts for walking up and down the stack
alias uu u;;u
alias uuu u;;u;;u
alias uuuu u;;u;;u;;u
alias uuuuu u;;u;;u;;u;;u
alias dd d;;d
alias ddd d;;d;;d
alias dddd d;;d;;d;;d
alias ddddd d;;d;;d;;d;;d

相关问题 更多 >