使用Python第三方库“Icecream”进行调试打印

文章转载至公众号:Python开发者,仅供个人学习。

Icecream是一个Python第三方库,可通过最少的代码使打印调试更清晰明了,使用pip安装Icecream库

pip install icecream

导入模块icecream

from icecream import ic
from datetime import datetime
import time

1、查看函数输出打印信息

# 1、查看函数输出打印信息
def plus_five(num):
    return num + 5
def plus_five(num):
    return num + 5
# 通过使用icecream,不仅可以看到函数输出,还可以看到函数及其参数情况。
ic(plus_five(5))
ic(plus_five(10))

输出结果:

ic| plus_five(5): 10
ic| plus_five(10): 15

2、检查执行情况

# 如果想要执行代码的位置,可以通过执行如下所示的操作,来查找执行了哪个语句
def hello(user:bool):
    if user:
        print("I'm user")
    else:
        print("i'm not user")

hello(user=True)

输出结果:

I'm user

使用icecream无须多余的文本信息,就可以轻松完成上述动作:

def hello(user:bool):
    if user:
        ic()
    else:
        ic()
# 使用icecream无须多余的文本信息,就可以轻松完成上述动作
hello(user=True)
hello(user=False)

输出结果:

ic| icecream_demo.py:32 in hello() at 07:30:29.492
ic| icecream_demo.py:34 in hello() at 07:30:29.494

3、自定义前缀

def time_flag():
    return f'{datetime.now()}|>'

ic.configureOutput(prefix=time_flag)
for i in range(3):
    time.sleep(2)
    ic("歪比巴卜")

可以看到代码的执行时间,就显示在输出的前面:

2021-02-03 15:09:58.104343|>'歪比巴卜'
2021-02-03 15:10:00.120383|>'歪比巴卜'
2021-02-03 15:10:02.121633|>'歪比巴卜'

4、获取更多的信息
在某些情况中,除了知道输出相关的代码之外,可能还想知道代码执行的行和代码文件,那么在ic.configureOutput()中,设置includecontext的参数值为True即可。

def ic_hi(hi):
    return hi + "!"
ic.configureOutput(includeContext=True)
ic(ic_hi("hi"))
ic(ic_hi("hello"))

输出结果如下:

ic| icecream_demo.py:57 in <module>- ic_hi("hi"): 'hi!'
ic| icecream_demo.py:58 in <module>- ic_hi("hello"): 'hello!'

通过输出结果可以知道,第一个输出是由函数ic_hi在文件icecream_demo.py的第57行执行的,第二个输出则是由函数ic_hi在代码文件的第58行执行的。
上述两个操作都用到了ic.configureOutput()函数,如下是configureOutput函数源码:

def configureOutput(self, prefix=_absent, outputFunction=_absent,
                    argToStringFunction=_absent, includeContext=_absent):
    if prefix is not _absent:
        self.prefix = prefix

    if outputFunction is not _absent:
        self.outputFunction = outputFunction

    if argToStringFunction is not _absent:
        self.argToStringFunction = argToStringFunction

    if includeContext is not _absent:
        self.includeContext = includeContext

通过查看源码,知道有四个可供设置的参数:

  • prefix,自定义输出前缀
  • outputFunction,更改输出函数
  • argToStringFunction,自定义参数序列化字符串
  • includeContext,显示文件名、代码行、函数信息

5、删除Icecream代码
最后可以将icecream仅用于调试,而将print用于其他目的(例如漂亮的打印)

def ic_hi(hi):
    return hi + "!"
ic.configureOutput(includeContext=True)
ic(ic_hi("hi"))
ic(ic_hi("hello"))
for i in range(10):
    print(f"--**--<{i}>--**--")

输出结果:

ic| icecream_demo.py:89 in <module>- ic_hi("hi"): 'hi!'
ic| icecream_demo.py:90 in <module>- ic_hi("hello"): 'hello!'
--**--<0>--**--
--**--<1>--**--
--**--<2>--**--
--**--<3>--**--
--**--<4>--**--
--**--<5>--**--
--**--<6>--**--
--**--<7>--**--
--**--<8>--**--
--**--<9>--**--

因为可以区分调试打印和print打印,因此搜索和删除所有ic调试语句非常轻松:
可以使用ctrl+f全局搜索:ic
或者使用一键选择、修改多个相同变量、符号、值:ctrl+shift+alt+j,全局选中对应的ic打印代码删除。

猜你喜欢

转载自blog.csdn.net/weixin_52385863/article/details/113607845
今日推荐