一、简介
调试程序时,很多人喜欢直接用print来代替断点调试,而pysnooper模块比print更方便,以装饰器的形式存在
二、实验环境
操作系统:win10
python版本:python3.6
三、安装pysnooper模块
pip3 install pysnooper
四、简单实例
需求:屏幕打印每个变量的值
import pysnooper @pysnooper.snoop() def test(): a = 100*1 sum=0 for i in range(10): sum +=i sum2 = sum +a return sum2 if __name__ == '__main__': test()
结果输出:
17:07:38.982924 call 4 def test(): 17:07:38.982924 line 5 a = 100*1 New var:....... a = 100 17:07:38.982924 line 6 sum=0 New var:....... sum = 0 17:07:38.982924 line 7 for i in range(10): New var:....... i = 0 17:07:38.982924 line 8 sum +=i 17:07:38.982924 line 7 for i in range(10): Modified var:.. i = 1 17:07:38.982924 line 8 sum +=i Modified var:.. sum = 1 17:07:38.983889 line 7 for i in range(10): Modified var:.. i = 2 17:07:38.983889 line 8 sum +=i Modified var:.. sum = 3 17:07:38.983889 line 7 for i in range(10): Modified var:.. i = 3 17:07:38.983889 line 8 sum +=i Modified var:.. sum = 6 17:07:38.983889 line 7 for i in range(10): Modified var:.. i = 4 17:07:38.983889 line 8 sum +=i Modified var:.. sum = 10 17:07:38.983889 line 7 for i in range(10): Modified var:.. i = 5 17:07:38.983889 line 8 sum +=i Modified var:.. sum = 15 17:07:38.983889 line 7 for i in range(10): Modified var:.. i = 6 17:07:38.983889 line 8 sum +=i Modified var:.. sum = 21 17:07:38.983889 line 7 for i in range(10): Modified var:.. i = 7 17:07:38.983889 line 8 sum +=i Modified var:.. sum = 28 17:07:38.983889 line 7 for i in range(10): Modified var:.. i = 8 17:07:38.983889 line 8 sum +=i Modified var:.. sum = 36 17:07:38.983889 line 7 for i in range(10): Modified var:.. i = 9 17:07:38.983889 line 8 sum +=i Modified var:.. sum = 45 17:07:38.983889 line 7 for i in range(10): 17:07:38.983889 line 9 sum2 = sum +a New var:....... sum2 = 145 17:07:38.983889 line 10 return sum2 17:07:38.983889 return 10 return sum2 Return value:.. 145
五、pysnooper.snoop传参介绍
output='a.txt' #将结果保存到文件a.txt variables=('a') #打印非局部变量a的值 depth=1 #Show snoop lines for functions that your function calls prefix='hello' #在每一行打印信息前添加hello