Skip to main content
 首页 » 编程设计

python之使用 IPython 对象在 ipdb 中

2024年10月25日9kevingrace

IPython 提供方便的对象检查工具,通过将 object? 写入 REPL。

这可以在 ipdb 中访问吗? ?它似乎不能作为内置命令使用。

目前我看到的帮助只是标准的 pdb 帮助:

ipdb> help 
 
Documented commands (type help <topic>): 
======================================== 
EOF    bt         cont      enable  jump  pdef    psource  run      unt 
a      c          continue  exit    l     pdoc    q        s        until 
alias  cl         d         h       list  pfile   quit     step     up 
args   clear      debug     help    n     pinfo   r        tbreak   w 
b      commands   disable   ignore  next  pinfo2  restart  u        whatis 
break  condition  down      j       p     pp      return   unalias  where 

请您参考如下方法:

IPython shell 中的对象检查会打印文档字符串和其他信息。 ipdb 调试器可以打印文档字符串,这是 IPython 对象检查正在执行的操作的一部分。只需输入

ipdb> print(object.__doc__) 

例如,检查内置的sum函数

ipdb> print(sum.__doc__) 
sum(iterable[, start]) -> value 
 
Return the sum of an iterable of numbers (NOT strings) plus the value 
of parameter 'start' (which defaults to 0).  When the iterable is 
empty, return start. 
ipdb> 

这是 IPython shell 中发生的事情的大部分方式

In [5]: sum? 
Docstring: 
sum(iterable[, start]) -> value 
 
Return the sum of an iterable of numbers (NOT strings) plus the value 
of parameter 'start' (which defaults to 0).  When the iterable is 
empty, return start. 
Type:      builtin_function_or_method 
 
In [6]: 

另一种选择是嵌入一个 IPython shell 作为调试断点。这很好,但我还没有找到一种方法来在循环中嵌入这样的调试断点时干净地退出。

from IPython import embed 
embed()  # debug breakpoint 

我刚刚了解到的一个更好的方法是在 ipdb 中使用 !,然后一切都像在 IPython shell 中一样工作。

ipdb> !help(sum) 
Help on built-in function sum in module builtins: 
 
sum(iterable, start=0, /) 
  Return the sum of a 'start' value (default: 0) plus an iterable of numbers 
 
  When the iterable is empty, return the start value. 
  This function is intended specifically for use with numeric values and may 
  reject non-numeric types. 
 
ipdb>