DeBug Python神级工具PySnooper
安装
pip3 install pysnooper
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)
返回日志
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
PySnooper特征
如果标准错误输出难以获得,或者太长了,那么可以将输出定位到本地文件:
@pysnooper.snoop('/my/log/file.log')
查看一些非本地变量的值:
@pysnooper.snoop(variables=('foo.bar', 'self.whatever'))
展示我们函数中调用函数的 snoop 行:
@pysnooper.snoop(depth=2)
将所有 snoop 行以某个前缀开始,更容易定位和找到:
@pysnooper.snoop(prefix='ZZZ ')
更可以用来获取TensorFlow 的各种张量信息,十分强大