Contents

King of Python debugger @pysnooper

PySnooper

@pysnooper 是一個非常好用的裝飾器,當你在使用 print 或是 IDE 斷點 debug 時候,往往需要設置斷點或是許多 print 才能發現問題所在。

@pysnooper 可以幫你用知道哪些正在運行、哪些函數被使用,只需將裝飾器放置於 function 中,將會得到所有的步驟,包含使用哪些動作、函數與時間。

The best way to install @pysnooper is with Pip

pip install PySnooper

Example

This function that converts a number to binary,讓我們來利用 @pysnooper.snoop() 裝飾器來跟蹤此 function 的所有事情吧!

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)

Output:

Source path:... <stdin>
Starting var:.. number = 6
22:58:09.555171 call         1 SOURCE IS UNAVAILABLE
22:58:09.555982 line         3 SOURCE IS UNAVAILABLE
22:58:09.556162 line         4 SOURCE IS UNAVAILABLE
New var:....... bits = []
22:58:09.556287 line         5 SOURCE IS UNAVAILABLE
22:58:09.556463 line         6 SOURCE IS UNAVAILABLE
Modified var:.. number = 3
New var:....... remainder = 0
22:58:09.556575 line         7 SOURCE IS UNAVAILABLE
Modified var:.. bits = [0]
22:58:09.556801 line         5 SOURCE IS UNAVAILABLE
22:58:09.556950 line         6 SOURCE IS UNAVAILABLE
Modified var:.. number = 1
Modified var:.. remainder = 1
22:58:09.557837 line         7 SOURCE IS UNAVAILABLE
Modified var:.. bits = [1, 0]
22:58:09.558126 line         5 SOURCE IS UNAVAILABLE
22:58:09.558334 line         6 SOURCE IS UNAVAILABLE
Modified var:.. number = 0
22:58:09.558496 line         7 SOURCE IS UNAVAILABLE
Modified var:.. bits = [1, 1, 0]
22:58:09.558692 line         5 SOURCE IS UNAVAILABLE
22:58:09.558882 line         8 SOURCE IS UNAVAILABLE
22:58:09.570057 return       8 SOURCE IS UNAVAILABLE
Return value:.. [1, 1, 0]
Elapsed time: 00:00:00.015191
[1, 1, 0]

Output to the file:

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

Reference:

https://github.com/cool-RR/PySnooper