为什么 IPython 不为我编写的模块提供完整的追溯?

dbl*_*iss 7 python ipython traceback

我很困惑为什么当我编写的模块中的函数出现错误时,IPython 没有向我显示函数中导致错误的行的完整回溯。

注意:我对这个特定错误的原因并不感到困惑,而是对为什么 IPython 没有向我展示原因感到困惑。

我的模块被调用module.py,它包含函数function,在它下面写了一个if __name__ == '__main__'块。(模块和函数名称已更改以保护无辜者的身份——或者可能不是那么无辜。)

这是引发错误时我得到的回溯。(注意缺少关于哪一行function导致错误的信息。)

In [1]: import module as m

In [2]: call = m.function('hello')
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-2-ec0c1e40ec8c> in <module>()
----> 1 call = m.function('hello')

/home/module.py in function(greeting)

TypeError: join() takes exactly one argument (2 given)
Run Code Online (Sandbox Code Playgroud)

Mat*_*att 5

你试过%xmode吗?

In [2]: %xmode?
Type:       Magic function
Definition: %xmode(self, parameter_s='')
Docstring:
Switch modes for the exception handlers.

Valid modes: Plain, Context and Verbose.

If called without arguments, acts as a toggle.
Run Code Online (Sandbox Code Playgroud)

如果您仔细观察,以下 2 个示例是不同的,但是在长回溯中差异更加明显:

In [8]: raise ValueError('Foo')
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-8-05e81bf5c607> in <module>()
----> 1 raise ValueError('Foo')
        global ValueError = undefined

ValueError: Foo
Run Code Online (Sandbox Code Playgroud)

普通模式

In [9]: xmode
Exception reporting mode: Plain

In [10]: raise ValueError('Foo')
Traceback (most recent call last):
  File "<ipython-input-10-05e81bf5c607>", line 1, in <module>
    raise ValueError('Foo')
ValueError: Foo
Run Code Online (Sandbox Code Playgroud)