簡単で使いやすいpython神級デバッグツールPySnooper

2467 ワード

github:https://github.com/cool-RR/PySnooper
Example
We're writing a function that converts a number to binary, by returning a list of bits. Let's snoop on it by adding the  @pysnooper.snoop()  decorator:
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)

The output to stderr is:
Starting var:.. number = 6
15:29:11.327032 call         4 def number_to_bits(number):
15:29:11.327032 line         5     if number:
15:29:11.327032 line         6         bits = []
New var:....... bits = []
15:29:11.327032 line         7         while number:
15:29:11.327032 line         8             number, remainder = divmod(number, 2)
New var:....... remainder = 0
Modified var:.. number = 3
15:29:11.327032 line         9             bits.insert(0, remainder)
Modified var:.. bits = [0]
15:29:11.327032 line         7         while number:
15:29:11.327032 line         8             number, remainder = divmod(number, 2)
Modified var:.. number = 1
Modified var:.. remainder = 1
15:29:11.327032 line         9             bits.insert(0, remainder)
Modified var:.. bits = [1, 0]
15:29:11.327032 line         7         while number:
15:29:11.327032 line         8             number, remainder = divmod(number, 2)
Modified var:.. number = 0
15:29:11.327032 line         9             bits.insert(0, remainder)
Modified var:.. bits = [1, 1, 0]
15:29:11.327032 line         7         while number:
15:29:11.327032 line        10         return bits
15:29:11.327032 return      10         return bits
Return value:.. [1, 1, 0]

Features
If stderr is not easily accessible for you, you can redirect the output to a file:
@pysnooper.snoop('/my/log/file.log')

See values of some variables that aren't local variables:
@pysnooper.snoop(variables=('foo.bar', 'self.whatever'))

Show snoop lines for functions that your function calls:
@pysnooper.snoop(depth=2)

Start all snoop lines with a prefix, to grep for them easily:
@pysnooper.snoop(prefix='ZZZ ')

Installation
$ pip install pysnooper