Python调试神器icecream

Python调试神器icecream

1、安装

pip install icecream

2、测试程序

from icecream import ic
from datetime import datetime


my_dict = {
    'name': 'John',
    'age': 32,
    'gender':'male'
}

class my_class():
    name = 'Dog',
    num_legs = 4,
    tail = True

def now():
    return f'[{datetime.now()}] '


def square2 (n):
    s = n * n
    return s

def cube3 (n):
    c = n * n * n
    return c

def whoisit (name):
    if name == 'John' :
        ic()
    elif name == 'Dog' :
        ic()
    else :
        ic()
        
if __name__ == "__main__" :

    #初始化调试环境,启用调试,无前缀
    ic.enable()
    ic.configureOutput(prefix='')
    
    #调用平方函数
    ic(square2(3))    
    
    #调用字典信息
    ic(my_dict['name'])
    ic(my_dict)
    
    #调用类信息
    pet = my_class()
    ic(pet.name)
    
    #调试判断条件
    whoisit (str(pet.name[0]))
    pet.name='Cat'
    whoisit (str(pet.name[0]))
    
    whoisit (my_dict['name'])
    whoisit (cube3 (3))
    
    #设置前缀文字描述
    ic.configureOutput(prefix='Debug show : ')
    ic(cube3 (2))
    
    #设置前缀时间描述
    ic.configureOutput(prefix=now)
    ic(cube3 (5))
    
    #关闭调试信息
    ic.disable()
    ic(cube3 (5))

3、基本应用说明
以下是输出结果:

square2(3): 9
my_dict[‘name’]: ‘John’
my_dict: {‘age’: 32, ‘gender’: ‘male’, ‘name’: ‘John’}
pet.name: (‘Dog’,)
< ipython-input-30-c56b454918c5>:32 in whoisit() at 22:11:16.669
< ipython-input-30-c56b454918c5>:34 in whoisit() at 22:11:16.734
< ipython-input-30-c56b454918c5>:30 in whoisit() at 22:11:16.797
< ipython-input-30-c56b454918c5>:34 in whoisit() at 22:11:16.863

Debug show : cube3 (2): 8
[2021-06-27 20:32:15.369213] cube3 (5): 125

  1. 函数调试信息:

square2(3): 9
显示调用的函数,以及函数结果值。

my_dict[‘name’]: ‘John’

显示字典的制定键、值。

my_dict: {‘age’: 32, ‘gender’: ‘male’, ‘name’: ‘John’}

显示字典的所有键、值。

  1. 类的调试信息:

pet.name: (‘Dog’,)

显示类的属性,以及属性值。

4、设置调试信息

在这里插入图片描述
< ipython-input-30-c56b454918c5>:32 in whoisit() at 22:11:16.669
< ipython-input-30-c56b454918c5>:34 in whoisit() at 22:11:16.734
< ipython-input-30-c56b454918c5>:30 in whoisit() at 22:11:16.797
< ipython-input-30-c56b454918c5>:34 in whoisit() at 22:11:16.863

在Python Notebooks运行。
如果它在一个“.py”文件中运行,还会显示调用它的文件名。
可以看到32 、34、30 、34分别是行号,对于判断语句执行的ic()位置 ,也就是符合条件的情况,可以用于分析判断程序的条件执行情况。

5、调试信息设置

Debug show : cube3 (2): 8
[2021-06-27 20:32:15.369213] cube3 (5): 125

可以通过配置前缀输出字符串,作为调试提示信息:
ic.configureOutput(prefix='Debug show : ')
同理,可以配置显示执行的时间提调试信息。

6、调试开关

当程序调试稳定后,可以直接关闭调试信息,而不用一条条加注释,非常方便。

ic.disable()
ic(cube3 (5))

设置关闭后,不再显示调试信息,非常方便。

比使用print临时调试程序的方法,少敲好多字,灵活方便,编程更快更爽!

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值