欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python实用模块(十六)pysnooper

实用模块 迷途小书童 4年前 (2020-01-27) 3228次浏览 0个评论

软硬件环境

  • windows 10 64bit
  • anaconda3 with python 3.7.4
  • pysnooper

视频看这里

此处是youtube的播放链接,需要科学上网。喜欢我的分享,记得订阅我的频道,点赞并分享,谢谢。

pysnooper简介

PySnooper是一个用于代码调试的一个第三方库,源码地址是 https://github.com/cool-RR/PySnooper,项目简介中只有一句话,Never use print for debugging again。相信很多人,特别是新手都是用print来进行代码调试的,那这个项目就能让你摆脱print语句,让你的代码调试更加高效。

安装

我们还是使用pip安装

pip install pysnooper

代码实践

这里简单写个函数double,在函数double加上装饰器@pysnooper.snoop()

import pysnooper

@pysnooper.snoop()
def double(a):
    return 2 * a

if __name__ == '__main__':

    for x in range(5):
        double(x)

执行结果如下

C:\Users\admin\Anaconda3\python.exe D:/xugaoxiang/blog/py_snooper.py
Source path:... D:/xugaoxiang/blog/py_snooper.py
Starting var:.. a = 0
22:33:48.473690 call        18 def double(a):
22:33:48.474685 line        19  return 2 * a
22:33:48.474685 return      19  return 2 * a
Return value:.. 0
Starting var:.. a = 1
22:33:48.474685 call        18 def double(a):
22:33:48.474685 line        19  return 2 * a
22:33:48.474685 return      19  return 2 * a
Return value:.. 2
Starting var:.. a = 2
22:33:48.474685 call        18 def double(a):
22:33:48.474685 line        19  return 2 * a
22:33:48.474685 return      19  return 2 * a
Return value:.. 4
Starting var:.. a = 3
22:33:48.474685 call        18 def double(a):
22:33:48.474685 line        19  return 2 * a
22:33:48.474685 return      19  return 2 * a
Return value:.. 6
Starting var:.. a = 4
22:33:48.474685 call        18 def double(a):
22:33:48.474685 line        19  return 2 * a
22:33:48.474685 return      19  return 2 * a
Return value:.. 8

Process finished with exit code 0

可以看到,for循环执行的每一步及其double函数的返回值。如果没有使用pysnooper的话,那可能就是在for循环中加入print,然后打印出对应的xdouble(x)了。

如果希望将标准输出的内容重定向到文件,可以修改

@pysnooper.snoop('log.txt')
def double(a):

    return 2 * a

更多pysnooper用法,请参考其官网文档。

参考资料

喜欢 (0)

您必须 登录 才能发表评论!

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

请关闭 Adblock 等类似浏览器插件,然后刷新页面访问,感谢您的支持!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.