PySnooper是一款适合菜鸟用的代码调试工具。
如果Python代码哪儿输出不对劲了,之前一般都是利用print函数结合pdb.setTrace()来找问题,如果使用pysnooper的话,那事情就变得简单了!
你可以通过使用这个工具,清楚的看见每一行代码的执行结果以及所有的局部变量的值。只要在函数上添加一个装饰行(类似于装饰器的使用),就可以打印出该函数每一行执行的结果,支持将结果输出到日志或者命令行。
pysnooper的强大之处在于只需添加decorator就可以,不用加到处加print函数,调试完之后还得一个个删除。那么我们开始吧!
首先安装:
pip install pysnooper
conda install -c conda-forge pysnooper
其大致使用方法如下面代码示例
import pysnooper
@pysnooper.snoop("test.log")
def main():
a = 1
b = 5
while a < b:
a += 1
if __name__ == '__main__':
main()
@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)
Source path:...
Starting var:.. number = 6
22:17:12.013064 call 2 def number_to_bits(number):
22:17:12.013569 line 3 if number:
22:17:12.013658 line 4 bits = []
New var:....... bits = []
22:17:12.013749 line 5 while number:
22:17:12.013862 line 6 number, remainder = divmod(number, 2)
Modified var:.. number = 3
New var:....... remainder = 0
22:17:12.013948 line 7 bits.insert(0, remainder)
Modified var:.. bits = [0]
22:17:12.014084 line 5 while number:
22:17:12.014198 line 6 number, remainder = divmod(number, 2)
Modified var:.. number = 1
Modified var:.. remainder = 1
22:17:12.014282 line 7 bits.insert(0, remainder)
Modified var:.. bits = [1, 0]
22:17:12.014412 line 5 while number:
22:17:12.014519 line 6 number, remainder = divmod(number, 2)
Modified var:.. number = 0
22:17:12.014669 line 7 bits.insert(0, remainder)
Modified var:.. bits = [1, 1, 0]
22:17:12.014791 line 5 while number:
22:17:12.014900 line 8 return bits
22:17:12.014982 return 8 return bits
Return value:.. [1, 1, 0]
[1, 1, 0]
import pysnooper
import random
def foo():
lst = []
for i in range(10):
lst.append(random.randrange(1, 1000))
with pysnooper.snoop():
lower = min(lst)
upper = max(lst)
mid = (lower + upper) / 2
print(lower, mid, upper)
foo()
1 422.0 843
Source path:...
New var:....... lst = [787, 799, 1, 458, 375, 75, 496, 843, 726, 570]
New var:....... i = 9
22:18:51.357818 line 10 lower = min(lst)
New var:....... lower = 1
22:18:51.358333 line 11 upper = max(lst)
New var:....... upper = 843
22:18:51.358460 line 12 mid = (lower + upper) / 2
New var:....... mid = 422.0
22:18:51.358582 line 13 print(lower, mid, upper)
## 查看某些非局部变量
@pysnooper.snoop(watch=('foo.bar', 'self.x["whatever"]'))
#查看对象的所有属性
@pysnooper.snoop(watch_explode=('foo', 'self'))
##展示我们函数中调用函数的 snoop 行:
@pysnooper.snoop(depth=2)
##将所有用snoop的代码行加前缀,更好找
@pysnooper.snoop(prefix='ZZZ ')
##在多线程下查看实际的线程id
@pysnooper.snoop(thread_info=True)