如何单步调试 Python 代码以帮助调试问题?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4929251/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:11:18  来源:igfitidea点击:

How to step through Python code to help debug issues?

pythondebugging

提问by Blankman

In Java/C# you can easily step through code to trace what might be going wrong, and IDE's make this process very user friendly.

在 Java/C# 中,您可以轻松地单步执行代码以跟踪可能出错的地方,而 IDE 使此过程非常用户友好。

Can you trace through python code in a similar fashion?

你能用类似的方式跟踪 python 代码吗?

采纳答案by Senthil Kumaran

Yes! There's a Python debugger called pdbjust for doing that!

是的!有一个 Python 调试器pdb就是为了这样做!

You can launch a Python program through pdbby using pdb myscript.pyor python -m pdb myscript.py.

您可以通过pdb使用pdb myscript.py或来启动 Python 程序python -m pdb myscript.py

There are a few commands you can then issue, which are documented on the pdbpage.

然后您可以发出一些命令,这些命令记录在pdb页面上。

Some useful ones to remember are:

要记住的一些有用的是:

  • b: set a breakpoint
  • c: continue debugging until you hit a breakpoint
  • s: step through the code
  • n: to go to next line of code
  • l: list source code for the current file (default: 11 lines including the line being executed)
  • u: navigate up a stack frame
  • d: navigate down a stack frame
  • p: to print the value of an expression in the current context
  • b: 设置断点
  • c: 继续调试直到遇到断点
  • s: 单步执行代码
  • n: 转到下一行代码
  • l: 列出当前文件的源代码(默认:11 行,包括正在执行的行)
  • u: 向上导航堆栈帧
  • d: 向下导航堆栈帧
  • p: 在当前上下文中打印表达式的值

If you don't want to use a command line debugger, some IDEs like Pydev, Wing IDEor PyCharmhave a GUI debugger. Wing and PyCharm are commercial products, but Wing has a free "Personal" edition, and PyCharm has a free community edition.

如果您不想使用命令行调试器,一些 IDE 像PydevWing IDEPyCharm有一个 GUI 调试器。Wing 和 PyCharm 是商业产品,但 Wing 有免费的“个人”版,而 PyCharm 有免费的社区版。

回答by Senthil Kumaran

There is a module called 'pdb' in python. At the top of your python script you do

python中有一个名为“pdb”的模块。在你的python脚本的顶部,你做

import pdb
pdb.set_trace()

and you will enter into debugging mode. You can use 's' to step, 'n' to follow next line similar to what you would do with 'gdb' debugger.

您将进入调试模式。您可以使用 's' 进行步进,使用 'n' 跟随下一行,类似于您使用 'gdb' 调试器所做的操作。

回答by kindall

If you want an IDE with integrated debugger, try PyScripter.

如果您想要带有集成调试器的 IDE,请尝试PyScripter

回答by Liorsion

If you come from Java/C# background I guess your best bet would be to use Eclipsewith Pydev. This gives you a fully functional IDE with debugger built in. I use it with django as well.

如果您来自 Java/C# 背景,我想您最好的选择是将EclipsePydev一起使用。这为您提供了一个内置调试器的全功能 IDE。我也将它与 django 一起使用。

回答by Autodidact

Programmatically stepping and tracing through python code is possible too (and its easy!). Look at the sys.settrace()documentation for more details. Also hereis a tutorial to get you started.

以编程方式单步执行和跟踪 Python 代码也是可能的(而且很容易!)。查看sys.settrace()文档以获取更多详细信息。另外这里是让你开始的教程。

回答by Aaron Hoffman

回答by Neil

https://wiki.python.org/moin/PythonDebuggingTools

https://wiki.python.org/moin/PythonDebuggingTools

pudb is a good drop-in replacement for pdb

pudb 是 pdb 的一个很好的替代品

回答by akD

By using Python Interactive Debugger 'pdb'

通过使用 Python 交互式调试器“pdb”

First step is to make the Python interpreter to enter into the debugging mode.

第一步是让Python解释器进入调试模式。

A. From the Command Line

A. 从​​命令行

Most straight forward way, running from command line, of python interpreter

最直接的方式,从命令行运行,python 解释器

$ python -m pdb scriptName.py
> .../pdb_script.py(7)<module>()
-> """
(Pdb)

B. Within the Interpreter

B. 在口译员内

While developing early versions of modules and to experiment it more iteratively.

在开发模块的早期版本并进行更多迭代试验时。

$ python
Python 2.7 (r27:82508, Jul  3 2010, 21:12:11)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pdb_script
>>> import pdb
>>> pdb.run('pdb_script.MyObj(5).go()')
> <string>(1)<module>()
(Pdb)

C. From Within Your Program

C. 从你的程序中

For a big project and long-running module, can start the debugging from inside the program using import pdband set_trace()like this :

对于大型项目和长时间运行的模块,可以使用import pdbset_trace()从程序内部开始调试, 如下所示:

#!/usr/bin/env python
# encoding: utf-8
#

import pdb

class MyObj(object):
    count = 5
    def __init__(self):
        self.count= 9

    def go(self):
        for i in range(self.count):
            pdb.set_trace()
            print i
        return

if __name__ == '__main__':
    MyObj(5).go()

Step-by-Step debugging to go into more internal

逐步调试以进入更多内部

  1. Execute the next statement… with “n”(next)

  2. Repeating the last debugging command… with ENTER

  3. Quitting it all… with “q”(quit)

  4. Printing the value of variables… with “p” (print)

    a) p a

  5. Turning off the (Pdb) prompt… with “c”(continue)

  6. Seeing where you are… with “l”(list)

  7. Stepping into subroutines… with “s”(step into)

  8. Continuing… but just to the end of the current subroutine… with “r”(return)

  9. Assign a new value

    a) !b = "B"

  10. Set a breakpoint

    a) break linenumber

    b) break functionname

    c) break filename:linenumber

  11. Temporary breakpoint

    a) tbreak linenumber

  12. Conditional breakpoint

    a) break linenumber, condition

  1. 执行下一条语句……用“n”(下一个)

  2. 重复上一个调试命令……使用ENTER

  3. 退出这一切......用“q”(退出)

  4. 打印变量的值……用“p”(打印)

    a) pa

  5. 关闭 (Pdb) 提示……用“c”(继续)

  6. 看到你在哪里......用“l”(列表)

  7. 步入子程序……用“s”(步入)

  8. 继续……但只是到当前子程序的结尾……用“r”(返回)

  9. 分配一个新值

    a) !b = "B"

  10. 设置断点

    a) 断行号

    b) 中断函数名

    c) 中断文件名:行号

  11. 临时断点

    a) tbreak 行号

  12. 条件断点

    a) 中断行号、条件

Note:**All these commands should be execute from **pdb

注意:**所有这些命令都应该从 **pdb 执行

For in-depth knowledge, refer:-

如需深入了解,请参阅:-

https://pymotw.com/2/pdb/

https://pymotw.com/2/pdb/

https://pythonconquerstheuniverse.wordpress.com/2009/09/10/debugging-in-python/

https://pythonconquerstheuniverse.wordpress.com/2009/09/10/debugging-in-python/

回答by jim

PyCharm is an IDE for Python that includes a debugger. Watch this YouTube video for an introduction on using PyCharm's debugger to step through code.

PyCharm 是一个包含调试器的 Python IDE。观看此 YouTube 视频,了解如何使用 PyCharm 的调试器单步调试代码。

PyCharm Tutorial - Debug python code using PyCharm

PyCharm 教程 - 使用 PyCharm 调试 python 代码

Note: This is not intended to be an endorsement or review. PyCharm is a commercial product that one needs to pay for, but the company does provide a free license to students and teachers, as well as a "lightweight" Community version that is free and open-source.

注意:这不是一种认可或评论。PyCharm 是一种需要付费购买的商业产品,但该公司确实向学生和教师提供免费许可证,以及免费和开源的“轻量级”社区版本。

Screenshot

截屏

回答by Eugene Yarmash

Starting in Python 3.7, you can use the breakpoint()built-in function to enter the debugger:

从 Python 3.7 开始,您可以使用breakpoint()内置函数进入调试器:

foo()
breakpoint()  # drop into the debugger at this point
bar()

By default, breakpoint()will import pdband call pdb.set_trace(). However, you can control debugging behavior via sys.breakpointhook()and use of the environment variable PYTHONBREAKPOINT.

默认情况下,breakpoint()将导入pdb并调用pdb.set_trace(). 但是,您可以通过sys.breakpointhook()和使用环境变量来控制调试行为PYTHONBREAKPOINT

See PEP 553for more information.

有关更多信息,请参阅PEP 553