网络编程
位置:首页>> 网络编程>> Python编程>> 详解DeBug Python神级工具PySnooper

详解DeBug Python神级工具PySnooper

作者:今夜睡火星  发布时间:2022-12-14 15:44:31 

标签:Python,PySnooper

PySnooper 在 GitHub 上自嘲是一个“乞丐版”调试工具(poor man's debugger)。

一般情况下,在编写 Python 代码时,如果想弄清楚为什么 Python 代码没有按照预期执行、哪些代码在运行哪些没在运行、局部变量又是什么,我们会使用包含断点和观察模式等功能的调试器,或者直接使用 print 语句打印出来。

但上面的方法都比较麻烦,例如使用调试器需要进行繁琐的设置,使用 print 打印也要很仔细。与它们相比,使用 PySnooper 只需为要调试的函数添加一个装饰器即可,这样就能获得运行函数详细的 log,包括执行的代码行和执行时间,以及局部变量发生变化的确切时间。

之所以称为“乞丐版”,相信是因为 PySnooper 使用起来十分简单,开发者可以在任何庞大的代码库中使用它,而无需进行任何设置。只需添加装饰器,并为日志输出地址指定路径。

GitHub项目地址

安装


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 的各种张量信息,十分强大。妈妈再也不用担心我找不到bug啦!
(2019.5.7更新:有时会不起作用,不知是自己姿势不对还是其他原因。)

来源:https://blog.csdn.net/Hepburn_li/article/details/89497596

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com