PySnooper - 不要再使用print进行调试
断点等调试方法虽然强大,但是设置比较麻烦。为此print成了很多人的最爱。
PySnooper让你做print的事情,但不需要麻烦地添加很多语句,你只需要添加装饰器就可以得到运行日志,包括线运行,及对应变量的值。
参考资料
- 书籍:掌握Python脚本系统管理 Mastering Python Scripting for System Administrators - 2019.pdf
- 讨论qq群630011153 144081101
- 本文最新版本地址
- 本文涉及的python测试开发库 谢谢点赞!
- 本文相关海量书籍下载
- 2018最佳人工智能机器学习工具书及下载(持续更新)
- https://github.com/cool-RR/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
特征
如果不方便访问stderr,则可以重定向到文件:
@pysnooper.snoop('/my/log/file.log')
查看非局部变量的值:
@pysnooper.snoop(variables=('foo.bar', 'self.whatever'))
显示函数调用的snoop行:
@pysnooper.snoop(depth=2)
窥探指定前缀的行:
@pysnooper.snoop(prefix ='ZZZ')
安装
pip install pysnooper
网友评论