1.print,assert

# debug是開發程式的時候,必定會發生的事,但有的bug很複雜,所以需要一些方法來幫助我們debug
# (1)最簡單的就是print,我們可以把我們關心的變數都print出來,來觀察為何會出錯,但程式裡多了一堆print,會有一堆垃圾訊息...
# (2)這時候可以用assert來代替
# test.py
def test(s):
    n = int(s)
    # 如果是 True 的話,又正常運行,但如果 assert 錯誤的話,會拋出 AssertionError 和自定義的輸出
    assert n != 0, 'n is zero!'
    return 10 / n

def main():
    return test('0')
    # return test('2')

main()

# 但程式多出一堆 assert 跟 print 比好像也沒差多少...
# 可加一個 -O 參數 python -O test.py,這時等於會把 assert 當作 pass statement,所以原本該發生甚麼 error 都會忠實呈現

2.logging

# logging 的好處是,可以透過配置自定義要輸出哪個級別的訊息,或是輸出 log 到檔案裡
# 詳細文件可去官網查看 https://docs.python.org/3/library/logging.html
import logging
logging.basicConfig(level=logging.INFO)

def test(s):
    n = int(s)
    # 如果是 True 的話,又正常運行,但如果 assert 錯誤的話,會拋出 AssertionError
    logging.info('n = {}'.format(n))
    return 10 / n

def main():
    return test('0')
    # return test('2')
main()

3.pdb

# pdb 是 python 的 debug 工具,可以讓程式以單行的方式運行,並且可隨時監控狀態
# test.py
s = '0'
n = int(s)
print(10 / n)

# python -m pdb test.py
# > d:\pythontest\test.py(1)<module>()
# -> s = '0'
# (Pdb)
# 輸入 n 命令讓程式一行一行的執行下去
# 輸入 p 變數名 可察看當前變數狀態
# 輸入 q 離開 debug 模式

# 但如果程式有幾千行總不可能這樣從第一行一直看下去吧...
# 這時侯要使用 pdb module
# test.py,python test.py
import pdb

s = '0'
n = int(s)
pdb.set_trace() # 執行到這裡時暫停,並且進入 pdb debug 模式,可再用 c 命令讓程式繼續執行
print(10 / n)

4.IDE

# 常用的有 Visual Studio Code(需安裝plugin)、PyCharm
# vscode 的部分可參考 https://code.visualstudio.com/docs/python/debugging

results matching ""

    No results matching ""