Master Python system management debugging and analysis script 3-2019 new artifact pysnooper: peeping is more convenient than print

PySnooper - don't use print for debugging anymore

Although breakpoints and other debugging methods are powerful, they are cumbersome to set. For this reason, print has become the favorite of many people.

PySnooper allows you to do print, but you don't need to add many statements. You just need to add a decorator to get the running log, including the line running and the value of the corresponding variable.

Reference material

Example

import pysnooper

@pysnooper.snoop()
def number_to_bits(number):
    if number:
        bits = []
        while number:
            number, remainder = divmod(number, 2)
            bits.insert(0, remainder)
        return bits
    else:
        return [0]

number_to_bits(6)

Implementation:

Starting var:.. number = 6
21:14:32.099769 call         3 @pysnooper.snoop()
21:14:32.099769 line         5     if number:
21:14:32.099769 line         6         bits = []
New var:....... bits = []
21:14:32.099769 line         7         while number:
21:14:32.099769 line         8             number, remainder = divmod(number, 2)
New var:....... remainder = 0
Modified var:.. number = 3
21:14:32.099769 line         9             bits.insert(0, remainder)
Modified var:.. bits = [0]
21:14:32.099769 line         7         while number:
21:14:32.099769 line         8             number, remainder = divmod(number, 2)
Modified var:.. number = 1
Modified var:.. remainder = 1
21:14:32.099769 line         9             bits.insert(0, remainder)
Modified var:.. bits = [1, 0]
21:14:32.099769 line         7         while number:
21:14:32.099769 line         8             number, remainder = divmod(number, 2)
Modified var:.. number = 0
21:14:32.099769 line         9             bits.insert(0, remainder)
Modified var:.. bits = [1, 1, 0]
21:14:32.099769 line         7         while number:
21:14:32.099769 line        10         return bits
21:14:32.099769 return      10         return bits

Features

If access to stderr is not convenient, you can redirect to a file:

@pysnooper.snoop('/my/log/file.log')

To view the value of a nonlocal variable:

@pysnooper.snoop(variables=('foo.bar', 'self.whatever'))

Show the snoop line of the function call:

@pysnooper.snoop(depth=2)

Peek at the line with the specified prefix:

@pysnooper.snoop(prefix ='ZZZ')

install

pip install pysnooper

Keywords: Python pip

Added by cueball2000uk on Sat, 23 Nov 2019 23:39:20 +0200