利用icecream調試python代碼


來源:調試Python代碼,不要再用print了

github:https://github.com/gruns/icecream

一、直接顯示參數、函數及結果

from icecream import ic
def plus_five(num):
    return num + 5
ic(plus_five(4))
ic(plus_five(5))

OUT:

ic| plus_five(4): 9
ic| plus_five(5): 10


二、檢查執行的情況
如果你想要找到執行代碼的位置,可以通過執行如下所示的操作,來查找執行了哪個語句。
def hello(user:bool):
    if user:
        ic()
    else:
        ic()

hello(user=True)
hello(user=False)

out:顯示執行的行數

ic| <ipython-input-7-c7eae3f4cba5>:3 in hello() at 08:57:13.181
ic| <ipython-input-7-c7eae3f4cba5>:5 in hello() at 08:57:13.215

三、執行加前綴

1)如果您想在打印語句中插入自定義前綴(例如代碼執行時間),icecream也是能實現的

from datetime import datetime
from icecream import ic 
import time
from datetime import datetime

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

ic.configureOutput(prefix=time_format)

for _ in range(3):
    time.sleep(1)
    ic('Hello')

OUT:

2021-02-19 16:57:59.528296|> 'Hello'
2021-02-19 16:58:00.557745|> 'Hello'
2021-02-19 16:58:01.581405|> 'Hello'

2)除了知道和輸出相關的代碼之外,你可能還想知道代碼執行的行和代碼文件。
from icecream import ic 

def plus_five(num):
    return num + 5

ic.configureOutput(includeContext=True)
ic(plus_five(4))
ic(plus_five(5))

OUT:

2021-02-19 16:59:09.005509|> <ipython-input-11-826dd3392d51>:7 in <module>
                             plus_five(4): 9
2021-02-19 16:59:09.052417|> <ipython-input-11-826dd3392d51>:8 in <module>
                             plus_five(5): 10


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM