How to make pdb recognize that the source has changed between runs?

只谈情不闲聊 提交于 2019-12-05 00:19:43

What do you mean by "rerun the program in pdb?" If you've imported a module, Python won't reread it unless you explicitly ask to do so, i.e. with reload(module). However, reload is far from bulletproof (see xreload for another strategy).

There are plenty of pitfalls in Python code reloading. To more robustly solve your problem, you could wrap pdb with a class that records your breakpoint info to a file on disk, for example, and plays them back on command.

(Sorry, ignore the first version of this answer; it's early and I didn't read your question carefully enough.)

The following mini-module may help. If you import it in your pdb session, then you can use:

pdb> pdbs.r()

at any time to force-reload all non-system modules except main. The code skips that because it throws an ImportError('Cannot re-init internal module main') exception.

# pdbs.py - PDB support

from __future__ import print_function

def r():
    """Reload all non-system modules, so a pdb restart
    will reload anything new
    """
    import sys
    # This is likely to be OS-specific
    SYS_PREFIX = '/usr/lib'

    for k, v in sys.modules.items():
        if not hasattr(v, '__file__'):
            continue
        if v.__file__.startswith(SYS_PREFIX):
            continue
        if k == '__main__':
            continue
        print('reloading %s [%s]' % (k, v.__file__))
        reload(v)

ipdb %autoreload extension

6.2.0 docs document http://ipython.readthedocs.io/en/stable/config/extensions/autoreload.html#module-IPython.extensions.autoreload :

In [1]: %load_ext autoreload

In [2]: %autoreload 2

In [3]: from foo import some_function

In [4]: some_function()
Out[4]: 42

In [5]: # open foo.py in an editor and change some_function to return 43

In [6]: some_function()
Out[6]: 43

I decided to comment some lines in my input script, and after

(Pdb) run

I got pdb to recognize that change. The bad thing: it runs the script from the beginning. The good things below.

(Pdb) help run
run [args...]
        Restart the debugged python program. If a string is supplied
        it is split with "shlex", and the result is used as the new
        sys.argv.  History, breakpoints, actions and debugger options
        are preserved.  "restart" is an alias for "run".
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!