Python學習筆記__8.2章 調試

來源:互聯網
上載者:User

標籤:程式設計語言   Python   

# 這是學習廖雪峰老師python教程的學習筆記

1、概覽

如何在程式出錯時,知道哪些變數的值是正確的,哪些變數的值是錯誤的。

1.1、print()

用print()把可能有問題的變數列印出來

def foo(s):

    n = int(s)

    print('>>> n = %d' % n)

    return 10 / n

 

1.2、斷言

凡是用print()來輔助查看的地方,都可以用斷言(assert)來替代:

def foo(s):

    n = int(s)

    assert n != 0, 'n is zero!' # n!=0,才能繼續向後執行。n=0,就會輸出‘n is zero’

    return 10 / n

如果宣告失敗,assert語句本身就會拋出AssertionError。

為了執行程式的美觀,啟動Python解譯器時可以用-O參數來關閉assert

$ python -O err.py

 

1.3、logging

把print()替換為logging是第3種方式,和assert比,logging不會拋出錯誤,而且可以輸出到檔案。

import logging

 

# 指定記錄資訊的層級,有debug,info,warning,error等幾個層級。

# 後面的層級,會使前面的層級失效。如info會使debug失效

logging.basicConfig(level=logging.INFO) 

 

s = '0'

n = int(s)

logging.info('n = %d' % n)

print(10 / n)

 

1.4、pdb

啟動Python的調試器pdb,讓程式以單步方式運行,可以隨時查看運行狀態

$ python -m pdb err.py

> /Users/michael/Github/learn-python3/samples/debug/err.py(2)<module>()

-> s = '0'  #自動將第一行列印出來

(Pdb)    # 變為等待輸入指令的偵錯模式

常用指令有:

1:查看代碼

n:逐步執行

p:接變數名,查看變數

q:退出

 

1.5、pdb.set_trace()

這個方法也是用pdb,但是不需要逐步執行。我們需要import pdb,然後,在可能出錯的地方放一個pdb.set_trace(),就可以設定一個斷點。

# err.py

import pdb

 

s = '0'

n = int(s)

pdb.set_trace() # 運行到這裡會自動暫停

print(10 / n)

暫停後,會進入Pdb偵錯模式。p 查看變數,c 繼續運行

 

1.6、IDE(Integration Environment)

目前比較好的Python IDE有:

  • Visual Studio      Code:https://code.visualstudio.com/,需要安裝Python外掛程式。

  • PyCharm:http://www.jetbrains.com/pycharm/

 

2、擴充文檔

python logging模組 (http://www.cnblogs.com/dahu-daqing/p/7040764.html)


Python學習筆記__8.2章 調試

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.