python pdb not giving correct trace on exceptions

时间:2017-10-12 09:56:46

标签: python debugging

On my iMac, the debugger, running a faulty python script (on MAC OS Sierra), always points to the first active line of code as cause of an exception, while when launching without debugger the correct line is identified. Does anybody have an idea why this may occur and how to fix it?

Here's a simple example with a "File not found" exception:

The script exception_test.py:

1  # Some dummy lines...
2  a=1
3  b=2
4  c=a+b
5  # Lines casuing the exception:
6  with open("filename","r") as fid:
7      lines=fid.readlines()

When run without debugger, as in python exception_test.py it yields

Traceback (most recent call last):
  File "exception_test.py", line 6, in <module>
    with open("filename","r") as fid:
IOError: [Errno 2] No such file or directory: 'filename'

identifying the correct line, i.e. line6, while python -m pdb exception_test.py and successive c to continue yields

Traceback (most recent call last):
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pdb.py", line 1314, in main
    pdb._runscript(mainpyfile)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pdb.py", line 1233, in _runscript
    self.run(statement)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/bdb.py", line 400, in run
    exec cmd in globals, locals
  File "<string>", line 1, in <module>
  File "exception_test.py", line 2, in <module>
    a=1
IOError: [Errno 2] No such file or directory: 'filename'
Uncaught exception. Entering post mortem debugging

indicating the first active line of code, i.e. line 2.

1 个答案:

答案 0 :(得分:0)

更有可能是cpython和pdb的问题,而不是你的代码,pypy可以打印正确的追溯行号。

发生例外的line_no的{​​{1}}不在frame下。

经过一些猜测和追踪,我可以缩小到this path

-m pdb

真正的根本原因仍然不明确。