Python debugging tips

What are your best tips for debugging Python?

Please don't just list a particular debugger without saying what it can actually do.

Related

  • What are good ways to make my Python code run first time? - This discusses minimizing errors

  • PDB

    You can use the pdb module, insert pdb.set_trace() anywhere and it will function as a breakpoint.

    >>> import pdb
    >>> a="a string"
    >>> pdb.set_trace()
    --Return--
    > <stdin>(1)<module>()->None
    (Pdb) p a
    'a string'
    (Pdb)
    

    To continue execution use c (or cont or continue ).

    It is possible to execute arbitrary Python expressions using pdb. For example, if you find a mistake, you can correct the code, then type a type expression to have the same effect in the running code

    ipdb is a version of pdb for IPython. It allows the use of pdb with all the IPython features including tab completion.

    It is also possible to set pdb to automatically run on an uncaught exception.

    Pydb was written to be an enhanced version of Pdb. Benefits?


    http://pypi.python.org/pypi/pudb, a full-screen, console-based Python debugger.

    Its goal is to provide all the niceties of modern GUI-based debuggers in a more lightweight and keyboard-friendly package. PuDB allows you to debug code right where you write and test it – in a terminal. If you've worked with the excellent (but nowadays ancient) DOS-based Turbo Pascal or C tools, PuDB's UI might look familiar.

    pudb截图

    Nice for debugging standalone scripts, just run

    python -m pudb.run my-script.py
    

    If you are using pdb, you can define aliases for shortcuts. I use these:

    # Ned's .pdbrc
    
    # Print a dictionary, sorted. %1 is the dict, %2 is the prefix for the names.
    alias p_ for k in sorted(%1.keys()): print "%s%-15s= %-80.80s" % ("%2",k,repr(%1[k]))
    
    # Print the instance variables of a thing.
    alias pi p_ %1.__dict__ %1.
    
    # Print the instance variables of self.
    alias ps pi self
    
    # Print the locals.
    alias pl p_ locals() local:
    
    # Next and list, and step and list.
    alias nl n;;l
    alias sl s;;l
    
    # Short cuts for walking up and down the stack
    alias uu u;;u
    alias uuu u;;u;;u
    alias uuuu u;;u;;u;;u
    alias uuuuu u;;u;;u;;u;;u
    alias dd d;;d
    alias ddd d;;d;;d
    alias dddd d;;d;;d;;d
    alias ddddd d;;d;;d;;d;;d
    
    链接地址: http://www.djcxy.com/p/42814.html

    上一篇: Groovy的隐藏功能?

    下一篇: Python调试技巧