如何在 Python 中调试:为什么 pdb 不下降到函数调用?

How to debug in Python: Why doesn't pdb descend into function call?

我找到了一个错误,在该错误中 io.open() 应该被传递 'utf-8' 而不是 'utf8'。下面的最小可执行代码。为什么 IPython 回溯不指示行号,为什么 pdb neither report that the error was with the io.open function call nor report anything from within the the io.open code? What could I have done with pdb or the IPython debugger or the Canopy debugger 层叠在它之上以便更轻松地调试这个行号?

检查我的 IPython 版本也很混乱。 Canopy 包管理器报告 ipython 4.0.0-3ipython4 4.0.0-9 都已安装,但 import IPython 后跟 IPython.version_info 的计算结果为 (2, 4, 1, '').

my_module.py 在 Canopy 代码编辑器中:

import io
def my_function(filename):
    with io.open(my_other_function(filename), u'r', u'utf8')
def my_other_function(text):
    return u'modified' + text

在 IPython 会话中:

In []: import pdb
In []: import my_module
In []: my_module.my_function(filename)

-------------------------------------------------------------------------
TypeError                 Traceback (most recent call last)
<ipython-input-5-4c50d9f6cb5c> in <module>()
----> 1 my_module.my_function(filename)

C:\my_module in my_function(filename)

TypeError: an integer is required 

In []: pdb.pm()
> c:\users\bbrown\documents\github\canvasapi-python\capi\my_module.py(3)my_function()
-> with io.open(my_other_function(filename), u'w', u'utf8') as filehandle:

(Pdb) up
> <ipython-input-14-f6d6cc2c1670>(1)<module>()
-> my_module.my_function('testjunk')

(Pdb) down
> c:\users\bbrown\documents\github\canvasapi-python\capi\my_module.py(3)my_function()
-> with io.open(my_other_function(filename), u'w', u'utf8') as filehandle:

(Pdb) args
filename = testjunk

(Pdb) down
*** Newest frame

鉴于 'utf-8' 作为参数工作正常,TypeError 令人惊讶,除非源自 open 的代码,但对 open 的调用不是放在堆栈上,至少不像 pdb 那样可导航。感谢您帮助我和其他人学习如何更有效地进行调试!

io.open 是内置函数:

In [8]: import io

In [9]: type(io.open)
Out[9]: builtin_function_or_method

Python里面没有写,调试器没有什么可调试的。您的错误是由于传递给 io.open:

的参数不正确造成的
open(file, mode='r', buffering=-1, encoding=None,
     errors=None, newline=None, closefd=True, opener=None) -> file object

您将 'utf-8' 作为第三个参数传递,但由于 buffering 应该是一个整数,该函数引发了一个描述性的 TypeError。您可以通过将 encoding 作为关键字参数来修复它:

io.open(filename, mode='r', encoding='utf8')

此外,您不需要显式导入 io 模块。 open 内置函数完全相同:

In [15]: open
Out[15]: <function io.open>