Python的调试器的逐步执行和自由运行模式遵循不同的执行路径

2024-09-30 08:34:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我运行脚本

import sys
if sys.gettrace():
    print 'OK'
else:
    assert False, 'good grief'

……像这样

^{pr2}$

…(Python v.2.7.8)我第一次看到这样的提示:

-> import sys
(Pdb)

如果在这一点上,我反复输入s来逐步执行脚本,我会看到如下所示:

> <path-to-script>/bugdemo.py(2)<module>()
-> if sys.gettrace():
(Pdb) s
> <path-to-script>/bugdemo.py(3)<module>()
-> print "OK"
(Pdb) s
OK
--Return--
> <path-to-script>/bugdemo.py(3)<module>()->None
-> print "OK"
(Pdb)

但是,如果不是单步执行代码,而是在第一个调试器提示符处输入c(缩写为cont,即继续),代码的执行遵循不同的路径

% python -mpdb bugdemo.py
> <path-to-script>/bugdemo.py(1)<module>()
-> import sys
(Pdb) c
Traceback (most recent call last):
  File "/Users/yt/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pdb.py", line 1314, in main
    pdb._runscript(mainpyfile)
  File "/Users/yt/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pdb.py", line 1233, in _runscript
    self.run(statement)
  File "/Users/yt/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/bdb.py", line 387, in run
    exec cmd in globals, locals
  File "<string>", line 1, in <module>
  File "bugdemo.py", line 1, in <module>
    import sys
AssertionError: good grief
Uncaught exception. Entering post mortem debugging
Running 'cont' or 'step' will restart the program
> <path-to-script>/bugdemo.py(1)<module>()
-> import sys
(Pdb)

有人知道这是怎么回事吗?这是不是我应该报告的bug1?还是有办法让它合理化?在


1如果这是一个bug,那么它就是一个bug的大杂烩:一个在逐步执行和自由运行中遵循不同执行路径的调试器比无用的更糟糕。


Tags: topathinpyimportsyslinescript
2条回答

documentation for settrace and gettrace非常清楚地说明它们将用于实现调试器。假设pdb正在使用settrace,当pdb没有事先运行时,我假设gettrace返回None。在

你以为会发生什么?pdb将建立一个环境,完全隐藏调试器存在的事实,甚至当您显式地使用作为调试器挂钩的函数时?我真的不认为这是个虫子。上面链接的文件甚至说:(强调我的)

CPython implementation detail: The settrace() function is intended only for implementing debuggers, profilers, coverage tools and the like. Its behavior is part of the implementation platform, rather than part of the language definition, and thus may not be available in all Python implementations.

gettrace和settrace是语言中用于“神奇”用途的奇怪的小角落,比如调试器。如果你不知道他们在做什么,就不要打电话给他们。在

lib\bdb.py:227

def set_continue(self):
    # Don't stop except at breakpoints or when finished
    self._set_stopinfo(self.botframe, None, -1)
    if not self.breaks:
        # no breakpoints; run without debugger overhead
        sys.settrace(None)
        frame = sys._getframe().f_back
        while frame and frame is not self.botframe:
            del frame.f_trace
            frame = frame.f_back

pdb在某些情况下删除跟踪功能,这是它的私有业务。你试图通过检查它的存在来比它聪明,这样你就会朝自己的脚开枪。恭喜你。在

相关问题 更多 >

    热门问题