Step-by-step debugging with IPython

后端 未结 15 2235
隐瞒了意图╮
隐瞒了意图╮ 2020-12-02 03:43

From what I have read, there are two ways to debug code in Python:

  • With a traditional debugger such as pdb or ipdb. This supports c

15条回答
  •  悲哀的现实
    2020-12-02 04:07

    You can start IPython from within ipdb!

    Induce the ipdb debugger1:

    import idpb; ipdb.set_trace()
    

    Enter IPython from within in the ipdb> console2:

    from IPython import embed; embed()
    

    Return to the ipdb> console from within IPython:

    exit
    

    If you're lucky enough to be using Emacs, things can be made even more convenient!

    This requires using M-x shell. Using yasnippet and bm, define the following snippet. This will replace the text ipdb in the editor with the set-trace line. After inserting the snippet, the line will be highlighted so that it is easily noticeable and navigable. Use M-x bm-next to navigate.

    # -*- mode: snippet -*-
    # name: ipdb
    # key: ipdb
    # expand-env: ((yas-after-exit-snippet-hook #'bm-toggle))
    # --
    import ipdb; ipdb.set_trace()
    

    1 All on one line for easy deletion. Since imports only happen once, this form ensures ipdb will be imported when you need it with no extra overhead.

    2 You can save yourself some typing by importing IPython within your .pdbrc file:

    try:
        from IPython import embed
    except:
        pass
    

    This allows you to simply call embed() from within ipdb (of course, only when IPython is installed).

提交回复
热议问题