How can I make ipdb show more lines of context while debugging?

前端 未结 6 1877
慢半拍i
慢半拍i 2021-02-01 13:08

By default, during debugging in IPython, ipdb shows one line above and one line below the current position in code.

Is there an easy way to make the area shown a bit b

6条回答
  •  抹茶落季
    2021-02-01 13:58

    Here's a patch to permanently set context for your program:

    (works across set_trace and post_mortem)

    def ipdb_patch(context = 11):
        import ipdb
        ipdbmain = ipdb.__main__
        def _init_pdb(context=context, commands=[]):
            try              : p = ipdbmain.debugger_cls(context=context)
            except TypeError : p = ipdbmain.debugger_cls()
            p.rcLines.extend(commands)
            return p
        def set_trace(frame=None, context=context):
            ipdbmain.wrap_sys_excepthook()
            if frame is None : frame = ipdbmain.sys._getframe().f_back
            p = ipdbmain._init_pdb(context).set_trace(frame)
            if p and hasattr(p, 'shell') : p.shell.restore_sys_module_state()
        ipdbmain._init_pdb = _init_pdb
        ipdb.set_trace = set_trace
        return ipdb
    ipdb = ipdb_patch()
    

    to add breakpoint() functionality simply add:

    import sys
    sys.breakpointhook = ipdb.set_trace
    

    With that all the following commands have the right context size:

    ipdb.set_trace()
    breakpoint()
    ipdb.post_mortem()
    ipdb.pm()
    %debug
    

    It does not however work with this:

    In [1]: %run -d file.py
    

    If you know how to adjust that, please feel free to drop in comments

提交回复
热议问题