「printf 大法」大概是最先期學到的 debug 方式?不一樣語言有不一樣的指令,在 Python 裏對應的是 print
指令 (加上%
或是.format
)。工具
剛剛看到「 cool-RR/pysnooper 」這個 Python 上的工具,只要增長 @pysnooper.snoop
這組 decorator,就能夠自動幫你把變量的值打印出來。網站上的範例是這樣,能夠看到就只是加了一行 decorator:oop
import pysnooper
網站
@pysnooper.snoop
debug
def number_to_bits(number):
code
if number:
orm
bits =
rem
while number:
it
number, remainder = divmod(number, 2)
form
bits.insert(0, remainder)
import
return bits
else:
return [0]
number_to_bits(6)
而後對應的 stderr 就有滿滿的資訊能夠看:
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
另外還能夠寫到檔案裏裏,能夠指定容許的深度,或是直接指定要打印哪些變量。另外輸出時,也能夠指定 prefix 避免混淆(一般會用在 stderr,也只有 pysnooper 在輸出時)