search
HomeBackend DevelopmentPython TutorialHow to use the python debugging module ipdb

1. Debugging python

ipdb is a module used for interactive debugging in python. It can be installed directly using pip;

its function is similar to the python console in pycharm,
The advantage of using ipdb is to debug directly in the code,
avoiding the need to go to the python console or reset some simple variables.

How to use the python debugging module ipdb

pip install ipdb

1.1 Using ipdb

When the program runs to ipdb.set_trace(), it will automatically enter debug mode.

for i in range(5):
    print(i)
    ipdb.set_trace()

1.2 Common commands

n→ \to→next
ENTER→ \to→Repeat the last command
q→ \to→Exit
pc→ \to→Continue
l→ \to→Find where you are currently located
s→ \to→Enter subroutine
r→ \to→Run until End of subroutine

命令式
上面的方法很方便,但是也有不灵活的缺点。对于一段比较棘手的代码,我们可能需要按步执行,边运行边跟踪代码流并进行调试,这时候使用交互式的命令式调试方法更加有效。启动IPDB调试环境的方法也很简单:

python -m ipdb your_code.py
常用命令
IPDB调试环境提供的常见命令有:

帮助
使用h即可调出IPDB的帮助。可以使用help command的方法查询特定命令的具体用法。

下一条语句
使用n(next)执行下一条语句。注意一个函数调用也是一个语句。如何能够实现类似“进入函数内部”的功能呢?

进入函数内部
使用s(step into)进入函数调用的内部。

打断点
使用b line_number(break)的方式给指定的行号位置加上断点。使用b file_name:line_number的方法给指定的文件(还没执行到的代码可能在外部文件中)中指定行号位置打上断点。

另外,打断点还支持指定条件下进入,可以查询帮助文档。

一直执行直到遇到下一个断点
使用c(continue)执行代码直到遇到某个断点或程序执行完毕。

一直执行直到返回
使用r(return)执行代码直到当前所在的这个函数返回。

跳过某段代码
使用j line_number(jump)可以跳过某段代码,直接执行指定行号所在的代码。

更多上下文
在IPDB调试环境中,默认只显示当前执行的代码行,以及其上下各一行的代码。如果想要看到更多的上下文代码,可以使用l first[, second](list)命令。

其中first指示向上最多显示的行号,second指示向下最多显示的行号(可以省略)。当second小于first时,second指的是从first开始的向下的行数(相对值vs绝对值)。

根据SO上的这个问题,你还可以修改IPDB的源码,一劳永逸地改变上下文的行数。

我在哪里
调试兴起,可能你会忘了自己目前所在的行号。例如在打印了若干变量值后,屏幕完全被这些值占据。使用w或者where可以打印出目前所在的行号位置以及上下文信息。

这是啥
我们可以使用whatis variable_name的方法,查看变量的类别(感觉有点鸡肋,用type也可以办到)。

列出当前函数的全部参数
当你身处一个函数内部的时候,可以使用a(argument)打印出传入函数的所有参数的值。

打印
使用p(print)和pp(pretty print)可以打印表达式的值。

清除断点
使用cl或者clear file:line_number清除断点。如果没有参数,则清除所有断点。

再来一次
使用restart重新启动调试器,断点等信息都会保留。restart实际是run的别名,使用run args的方式传入参数。

退出
使用q退出调试,并清除所有信息。

当然,这并不是IPDB的全部。其他的命令还请参照帮助文档。文档在手,天下我有!

The above is the detailed content of How to use the python debugging module ipdb. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do you append elements to a Python array?How do you append elements to a Python array?Apr 30, 2025 am 12:19 AM

InPython,youappendelementstoalistusingtheappend()method.1)Useappend()forsingleelements:my_list.append(4).2)Useextend()or =formultipleelements:my_list.extend(another_list)ormy_list =[4,5,6].3)Useinsert()forspecificpositions:my_list.insert(1,5).Beaware

How do you debug shebang-related issues?How do you debug shebang-related issues?Apr 30, 2025 am 12:17 AM

The methods to debug the shebang problem include: 1. Check the shebang line to make sure it is the first line of the script and there are no prefixed spaces; 2. Verify whether the interpreter path is correct; 3. Call the interpreter directly to run the script to isolate the shebang problem; 4. Use strace or trusts to track the system calls; 5. Check the impact of environment variables on shebang.

How do you remove elements from a Python array?How do you remove elements from a Python array?Apr 30, 2025 am 12:16 AM

Pythonlistscanbemanipulatedusingseveralmethodstoremoveelements:1)Theremove()methodremovesthefirstoccurrenceofaspecifiedvalue.2)Thepop()methodremovesandreturnsanelementatagivenindex.3)Thedelstatementcanremoveanitemorslicebyindex.4)Listcomprehensionscr

What data types can be stored in a Python list?What data types can be stored in a Python list?Apr 30, 2025 am 12:07 AM

Pythonlistscanstoreanydatatype,includingintegers,strings,floats,booleans,otherlists,anddictionaries.Thisversatilityallowsformixed-typelists,whichcanbemanagedeffectivelyusingtypechecks,typehints,andspecializedlibrarieslikenumpyforperformance.Documenti

What are some common operations that can be performed on Python lists?What are some common operations that can be performed on Python lists?Apr 30, 2025 am 12:01 AM

Pythonlistssupportnumerousoperations:1)Addingelementswithappend(),extend(),andinsert().2)Removingitemsusingremove(),pop(),andclear().3)Accessingandmodifyingwithindexingandslicing.4)Searchingandsortingwithindex(),sort(),andreverse().5)Advancedoperatio

How do you create multi-dimensional arrays using NumPy?How do you create multi-dimensional arrays using NumPy?Apr 29, 2025 am 12:27 AM

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

Explain the concept of 'broadcasting' in NumPy arrays.Explain the concept of 'broadcasting' in NumPy arrays.Apr 29, 2025 am 12:23 AM

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

Explain how to choose between lists, array.array, and NumPy arrays for data storage.Explain how to choose between lists, array.array, and NumPy arrays for data storage.Apr 29, 2025 am 12:20 AM

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function