相信很多程序员在调试代码时,都用过 print。代码少还好说,如果是大型项目,面对众多 print 的输出结果,可能要头大了。

今天推荐一个 github 热门开源项目:pysnooper。该项目推出的第一天就收获 2000+ star,登上了 github 日榜第一位,如今有近 15k star。可见这是一款 python 开发者喜欢的工具。欢迎收藏学习、喜欢点赞支持,文末技术交流可以畅聊!

链接:https://github.com/cool-rr/pysnooper

pysnooper 是个什么东西?

如果你写的 python 代码不能按如期那样运行,你会绞尽脑汁想为啥出错了。虽然你希望有支持断点的成熟调试器,但或许你现在不想去设置这样的调试器。

你想知道哪些行代码是正常运行,哪些行不正常。据说大多数人会在可疑位置使用 print 输出语句。

其实 pysnooper 的作用有点类似,你不用小心翼翼地用 print 输出,只需在想调试的函数中引入一个装饰器。然后得到函数的详细日志,包括运行了哪些行、何时运行,以及何时更改了局部变量。

为什么 pysnooper 能从其他智能调试工具中脱颖而出?

因为你可以在不需要进行任何设置的情况下将其用于糟糕的、庞大的企业代码库中。只需打开装饰器(如下示例所示),并将输出重定向到一个专用的日志文件,将日志文件路径指定为第一个参数。

ps:如果无法访问 stderr,那可以将输出重定向到指定文件,比如 :@pysnooper.snoop('/my/log/file.log')

使用范例

范例是一个把数字转成二进制的函数。

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

如果你不想追踪整个函数,那可以用 with 块包装你想追踪的那部分,如下:

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()

输出结果

new var:……. i = 9
new var:……. lst = [681, 267, 74, 832, 284, 678, …]
09:37:35.881721 line 10 lower = min(lst)
new var:……. lower = 74
09:37:35.882137 line 11 upper = max(lst)
new var:……. upper = 832
09:37:35.882304 line 12 mid = (lower + upper) / 2
74 453.0 832
new var:……. mid = 453.0
09:37:35.882486 line 13 print(lower, mid, upper)
elapsed time: 00:00:00.000344

如何安装?

最佳方式:pip

$ pip install pysnooper

其他方式:

  • conda:$ conda install -c conda-forge pysnooper
  • arch linux:$ yay -s python-pysnooper
  • fedora linux:dnf install python3-pysnooper

技术交流

欢迎转载、收藏、有所收获点赞支持一下!

以上就是详解python调试神器之pysnooper的详细内容,更多关于python pysnooper的资料请关注www.887551.com其它相关文章!