1. 程式人生 > 其它 >Python程式碼除錯

Python程式碼除錯

參考

https://www.jb51.net/article/64181.htm

使用 pdb 進行除錯

pdb 是 python 自帶的一個包,為 python 程式提供了一種互動的原始碼除錯功能,主要特性包括設定斷點、單步除錯、進入函式除錯、檢視當前程式碼、檢視棧片段、動態改變變數的值等。pdb 提供了一些常用的除錯命令,詳情見表 1。
表 1. pdb 常用命令

下面結合具體的例項講述如何使用 pdb 進行除錯。
清單 1. 測試程式碼示例

1 2 3 4 5 6 7 import pdb a = "aaa" pdb.set_trace() b = "bbb" c =
"ccc" final = a + b + c print final

開始除錯:直接執行指令碼,會停留在 pdb.set_trace() 處,選擇 n+enter 可以執行當前的 statement。在第一次按下了 n+enter 之後可以直接按 enter 表示重複執行上一條 debug 命令。
清單 2. 利用 pdb 除錯

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 [root@rcc-pok-idg-2255 ~]# python epdb1.py
> /root/epdb1.py(4)?() -> b = "bbb" (Pdb) n > /root/epdb1.py(5)?() -> c = "ccc" (Pdb) > /root/epdb1.py(6)?() -> final = a + b + c (Pdb) list 1 import pdb 2 a = "aaa" 3 pdb.set_trace() 4 b = "bbb" 5 c = "ccc" 6 -> final = a + b + c 7 print final [EOF] (Pdb) [EOF] (Pdb) n
> /root/epdb1.py(7)?() -> print final (Pdb)

退出 debug:使用 quit 或者 q 可以退出當前的 debug,但是 quit 會以一種非常粗魯的方式退出程式,其結果是直接 crash。
清單 3. 退出 debug

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 [root@rcc-pok-idg-2255 ~]# python epdb1.py > /root/epdb1.py(4)?() -> b = "bbb" (Pdb) n > /root/epdb1.py(5)?() -> c = "ccc" (Pdb) q Traceback (most recent call last): File "epdb1.py", line 5, in ? c = "ccc" File "epdb1.py", line 5, in ? c = "ccc" File "/usr/lib64/python2.4/bdb.py", line 48, in trace_dispatch return self.dispatch_line(frame) File "/usr/lib64/python2.4/bdb.py", line 67, in dispatch_line if self.quitting: raise BdbQuit bdb.BdbQuit

列印變數的值:如果需要在除錯過程中列印變數的值,可以直接使用 p 加上變數名,但是需要注意的是列印僅僅在當前的 statement 已經被執行了之後才能看到具體的值,否則會報 NameError: < exceptions.NameError … ....> 錯誤。
清單 4. debug 過程中列印變數

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 [root@rcc-pok-idg-2255 ~]# python epdb1.py > /root/epdb1.py(4)?() -> b = "bbb" (Pdb) n > /root/epdb1.py(5)?() -> c = "ccc" (Pdb) p b 'bbb' (Pdb) 'bbb' (Pdb) n > /root/epdb1.py(6)?() -> final = a + b + c (Pdb) p c 'ccc' (Pdb) p final *** NameError: <exceptions.NameError instance at 0x1551b710 > (Pdb) n > /root/epdb1.py(7)?() -> print final (Pdb) p final 'aaabbbccc' (Pdb)

使用 c 可以停止當前的 debug 使程式繼續執行。如果在下面的程式中繼續有 set_statement() 的申明,則又會重新進入到 debug 的狀態,讀者可以在程式碼 print final 之前再加上 set_trace() 驗證。
清單 5. 停止 debug 繼續執行程式

1 2 3 4 5 6 7 8 [root@rcc-pok-idg-2255 ~]# python epdb1.py > /root/epdb1.py(4)?() -> b = "bbb" (Pdb) n > /root/epdb1.py(5)?() -> c = "ccc" (Pdb) c aaabbbccc

顯示程式碼:在 debug 的時候不一定能記住當前的程式碼塊,如要要檢視具體的程式碼塊,則可以通過使用 list 或者 l 命令顯示。list 會用箭頭 -> 指向當前 debug 的語句。
清單 6. debug 過程中顯示程式碼

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 [root@rcc-pok-idg-2255 ~]# python epdb1.py > /root/epdb1.py(4)?() -> b = "bbb" (Pdb) list 1 import pdb 2 a = "aaa" 3 pdb.set_trace() 4 -> b = "bbb" 5 c = "ccc" 6 final = a + b + c 7 pdb.set_trace() 8 print final [EOF] (Pdb) c > /root/epdb1.py(8)?() -> print final (Pdb) list 3 pdb.set_trace() 4 b = "bbb" 5 c = "ccc" 6 final = a + b + c 7 pdb.set_trace() 8 -> print final [EOF] (Pdb)

在使用函式的情況下進行 debug
清單 7. 使用函式的例子

1 2 3 4 5 6 7 8 9 10 11 import pdb def combine(s1,s2): # define subroutine combine, which... s3 = s1 + s2 + s1 # sandwiches s2 between copies of s1, ... s3 = '"' + s3 +'"' # encloses it in double quotes,... return s3 # and returns it. a = "aaa" pdb.set_trace() b = "bbb" c = "ccc" final = combine(a,b) print final

如果直接使用 n 進行 debug 則到 final=combine(a,b) 這句的時候會將其當做普通的賦值語句處理,進入到 print final。如果想要對函式進行 debug 如何處理呢 ? 可以直接使用 s 進入函式塊。函式裡面的單步除錯與上面的介紹類似。如果不想在函式裡單步除錯可以在斷點處直接按 r 退出到呼叫的地方。
清單 8. 對函式進行 debug

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 [root@rcc-pok-idg-2255 ~]# python epdb2.py > /root/epdb2.py(10)?() -> b = "bbb" (Pdb) n > /root/epdb2.py(11)?() -> c = "ccc" (Pdb) n > /root/epdb2.py(12)?() -> final = combine(a,b) (Pdb) s --Call-- > /root/epdb2.py(3)combine() -> def combine(s1,s2): # define subroutine combine, which... (Pdb) n > /root/epdb2.py(4)combine() -> s3 = s1 + s2 + s1 # sandwiches s2 between copies of s1, ... (Pdb) list 1 import pdb 2 3 def combine(s1,s2): # define subroutine combine, which... 4 -> s3 = s1 + s2 + s1 # sandwiches s2 between copies of s1, ... 5 s3 = '"' + s3 +'"' # encloses it in double quotes,... 6 return s3 # and returns it. 7 8 a = "aaa" 9 pdb.set_trace() 10 b = "bbb" 11 c = "ccc" (Pdb) n > /root/epdb2.py(5)combine() -> s3 = '"' + s3 +'"' # encloses it in double quotes,... (Pdb) n > /root/epdb2.py(6)combine() -> return s3 # and returns it. (Pdb) n --Return-- > /root/epdb2.py(6)combine()->'"aaabbbaaa"' -> return s3 # and returns it. (Pdb) n > /root/epdb2.py(13)?() -> print final (Pdb)

在除錯的時候動態改變值 。在除錯的時候可以動態改變變數的值,具體如下例項。需要注意的是下面有個錯誤,原因是 b 已經被賦值了,如果想重新改變 b 的賦值,則應該使用! B。
清單 9. 在除錯的時候動態改變值

1 2 3 4 5 6 7 8 9 [root@rcc-pok-idg-2255 ~]# python epdb2.py > /root/epdb2.py(10)?() -> b = "bbb" (Pdb) var = "1234" (Pdb) b = "avfe" *** The specified object '= "avfe"' is not a function or was not found along sys.path. (Pdb) !b="afdfd" (Pdb)

pdb 除錯有個明顯的缺陷就是對於多執行緒,遠端除錯等支援得不夠好,同時沒有較為直觀的介面顯示,不太適合大型的 python 專案。而在較大的 python 專案中,這些除錯需求比較常見,因此需要使用更為高階的除錯工具。接下來將介紹 PyCharm IDE 的除錯方法 .
使用 PyCharm 進行除錯

PyCharm 是由 JetBrains 打造的一款 Python IDE,具有語法高亮、Project 管理、程式碼跳轉、智慧提示、自動完成、單元測試、版本控制等功能,同時提供了對 Django 開發以及 Google App Engine 的支援。分為個人獨立版和商業版,需要 license 支援,也可以獲取免費的 30 天試用。試用版本的 Pycharm 可以在官網上下載,下載地址為:http://www.jetbrains.com/pycharm/download/index.html。 PyCharm 同時提供了較為完善的除錯功能,支援多執行緒,遠端除錯等,可以支援斷點設定,單步模式,表示式求值,變數檢視等一系列功能。PyCharm IDE 的除錯窗口布局如圖 1 所示。
圖 1. PyCharm IDE 窗口布局

下面結合例項講述如何利用 PyCharm 進行多執行緒除錯。具體除錯所用的程式碼例項見清單 10。
清單 10. PyCharm 除錯程式碼例項

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 __author__ = 'zhangying' #!/usr/bin/python import thread import time # Define a function for the thread def print_time( threadName, delay): count = 0 while count < 5: count += 1 print "%s: %s" % ( threadName, time.ctime(time.time()) ) def check_sum(threadName,valueA,valueB): print "to calculate the sum of two number her" result=sum(valueA,valueB) print "the result is" ,result; def sum(valueA,valueB): if valueA >0 and valueB>0: return valueA+valueB def readFile(threadName, filename): file = open(filename) for line in file.xreadlines(): print line try: thread.start_new_thread( print_time, ("Thread-1", 2, ) ) thread.start_new_thread( check_sum, ("Thread-2", 4,5, ) ) thread.start_new_thread( readFile, ("Thread-3","test.txt",)) except: print "Error: unable to start thread" while 1: # print "end" pass

在除錯之前通常需要設定斷點,斷點可以設定在迴圈或者條件判斷的表示式處或者程式的關鍵點。設定斷點的方法非常簡單:在程式碼編輯框中將游標移動到需要設定斷點的行,然後直接按 Ctrl+F8 或者選擇選單"Run"->"Toggle Line Break Point",更為直接的方法是雙擊程式碼編輯處左側邊緣,可以看到出現紅色的小圓點(如圖 2)。當除錯開始的時候,當前正在執行的程式碼會直接顯示為藍色。下圖中設定了三個斷點,藍色高亮顯示的為正在執行的程式碼。
圖 2. 斷點設定

表示式求值:在除錯過程中有的時候需要追蹤一些表示式的值來發現程式中的問題,Pycharm 支援表示式求值,可以通過選中該表示式,然後選擇“Run”->”Evaluate Expression”,在出現的視窗中直接選擇 Evaluate 便可以檢視。

Pychar 同時提供了 Variables 和 Watches 視窗,其中除錯步驟中所涉及的具體變數的值可以直接在 variable 一欄中檢視。
圖 3. 變數檢視

如果要動態的監測某個變數可以直接選中該變數並選擇選單”Run”->”Add Watch”新增到 watches 欄中。當除錯進行到該變數所在的語句時,在該視窗中可以直接看到該變數的具體值。
圖 4. 監測變數

對於多執行緒程式來說,通常會有多個執行緒,當需要 debug 的斷點分別設定在不同執行緒對應的執行緒體中的時候,通常需要 IDE 有良好的多執行緒除錯功能的支援。 Pycharm 中在主執行緒啟動子執行緒的時候會自動產生一個 Dummy 開頭的名字的虛擬執行緒,每一個 frame 對應各自的除錯幀。如圖 5,本例項中一共有四個執行緒,其中主執行緒生成了三個執行緒,分別為 Dummy-4,Dummy-5,Dummy-6. 其中 Dummy-4 對應執行緒 1,其餘分別對應執行緒 2 和執行緒 3。
圖 5. 多執行緒視窗

當除錯進入到各個執行緒的子程式時,Frame 會自動切換到其所對應的 frame,相應的變數欄中也會顯示與該過程對應的相關變數,如圖 6,直接控制除錯按鈕,如 setp in,step over 便可以方便的進行除錯。
圖 6. 子執行緒除錯

使用 PyDev 進行除錯

PyDev 是一個開源的的 plugin,它可以方便的和 Eclipse 整合,提供方便強大的除錯功能。同時作為一個優秀的 Python IDE 還提供語法錯誤提示、原始碼編輯助手、Quick Outline、Globals Browser、Hierarchy View、執行等強大功能。下面講述如何將 PyDev 和 Eclipse 整合。在安裝 PyDev 之前,需要先安裝 Java 1.4 或更高版本、Eclipse 以及 Python。 第一步:啟動 Eclipse,在 Eclipse 選單欄中找到 Help 欄,選擇 Help > Install New Software,並選擇 Add button,新增 Ptdev 的下載站點 http://pydev.org/updates。選擇 PyDev 之後完成餘下的步驟便可以安裝 PyDev。
圖 7. 安裝 PyDev

安裝完成之後需要配置 Python 直譯器,在 Eclipse 選單欄中,選擇 Window > Preferences > Pydev > Interpreter – Python。Python 安裝在 C:\Python27 路徑下。單擊 New,選擇 Python 直譯器 python.exe,開啟後顯示出一個包含很多複選框的視窗,選擇需要加入系統 PYTHONPATH 的路徑,單擊 OK。
圖 8. 配置 PyDev

在配置完 Pydev 之後,可以通過在 Eclipse 選單欄中,選擇 File > New > Project > Pydev >Pydev Project,單擊 Next 建立 Python 專案,下面的內容假設 python 專案已經建立,並且有個需要除錯的指令碼 remote.py(具體內容如下),它是一個登陸到遠端機器上去執行一些命令的指令碼,在執行的時候需要傳入一些引數,下面將詳細講述如何在除錯過程中傳入引數 .
清單 11. Pydev 除錯示例程式碼

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 #!/usr/bin/env python import os def telnetdo(HOST=None, USER=None, PASS=None, COMMAND=None): #define a function import telnetlib, sys if not HOST: try: HOST = sys.argv[1] USER = sys.argv[2] PASS = sys.argv[3] COMMAND = sys.argv[4] except: print "Usage: remote.py host user pass command" return tn = telnetlib.Telnet() # try: tn.open(HOST) except: print "Cannot open host" return tn.read_until("login:") tn.write(USER + '\n') if PASS: tn.read_until("Password:") tn.write(PASS + '\n') tn.write(COMMAND + '\n') tn.write("exit\n") tmp = tn.read_all() tn.close() del tn return tmp if __name__ == '__main__': print telnetdo()

在除錯的時候有些情況需要傳入一些引數,在除錯之前需要進行相應的配置以便接收所需要的引數,選擇需要除錯的程式(本例 remote.py),該指令碼在 debug 的過程中需要輸入四個引數:host,user,password 以及命令。在 eclipse 的工程目錄下選擇需要 debug 的程式,單擊右鍵,選擇“Debug As”->“Debug Configurations”,在 Arguments Tab 頁中選擇“Variables”。如下 圖 9 所示 .
圖 9. 配置變數

在視窗”Select Variable”之後選擇“Edit Varuables” ,出現如下視窗,在下圖中選擇”New” 並在彈出的視窗中輸入對應的變數名和值。特別需要注意的是在值的後面一定要有空格,不然所有的引數都會被當做第一個引數讀入。
圖 10. 新增具體變數

按照以上方式依次配置完所有引數,然後在”select variable“視窗中安裝引數所需要的順序依次選擇對應的變數。配置完成之後狀態如下圖 11 所示。
圖 11. 完成配置

選擇 Debug 便可以開始程式的除錯,除錯方法與 eclipse 內建的除錯功能的使用相似,並且支援多執行緒的 debug,這方面的文章已經有很多,讀者可以自行搜尋閱讀,或者參考”使用 Eclipse 平臺進行除錯“一文。
使用日誌功能達到除錯的目的

日誌資訊是軟體開發過程中進行除錯的一種非常有用的方式,特別是在大型軟體開發過程需要很多相關人員進行協作的情況下。開發人員通過在程式碼中加入一些特定的能夠記錄軟體執行過程中的各種事件資訊能夠有利於甄別程式碼中存在的問題。這些資訊可能包括時間,描述資訊以及錯誤或者異常發生時候的特定上下文資訊。 最原始的 debug 方法是通過在程式碼中嵌入 print 語句,通過輸出一些相關的資訊來定位程式的問題。但這種方法有一定的缺陷,正常的程式輸出和 debug 資訊混合在一起,給分析帶來一定困難,當程式除錯結束不再需要 debug 輸出的時候,通常沒有很簡單的方法將 print 的資訊遮蔽掉或者定位到檔案。python 中自帶的 logging 模組可以比較方便的解決這些問題,它提供日誌功能,將 logger 的 level 分為五個級別,可以通過 Logger.setLevel(lvl) 來設定。預設的級別為 warning。
表 2. 日誌的級別

ogging lib 包含 4 個主要物件

  1. logger:logger 是程式資訊輸出的介面。它分散在不同的程式碼中使得程式可以在執行的時候記錄相應的資訊,並根據設定的日誌級別或 filter 來決定哪些資訊需要輸出並將這些資訊分發到其關聯的 handler。常用的方法有 Logger.setLevel(),Logger.addHandler() ,Logger.removeHandler() ,Logger.addFilter() ,Logger.debug(), Logger.info(), Logger.warning(), Logger.error(),getLogger() 等。logger 支援層次繼承關係,子 logger 的名稱通常是父 logger.name 的方式。如果不建立 logger 的例項,則使用預設的 root logger,通過 logging.getLogger() 或者 logging.getLogger("") 得到 root logger 例項。
  2. Handler:Handler 用來處理資訊的輸出,可以將資訊輸出到控制檯,檔案或者網路。可以通過 Logger.addHandler() 來給 logger 物件新增 handler,常用的 handler 有 StreamHandler 和 FileHandler 類。StreamHandler 傳送錯誤資訊到流,而 FileHandler 類用於向檔案輸出日誌資訊,這兩個 handler 定義在 logging 的核心模組中。其他的 hander 定義在 logging.handles 模組中,如 HTTPHandler,SocketHandler。
  3. Formatter:Formatter 則決定了 log 資訊的格式 , 格式使用類似於 %(< dictionary key >)s 的形式來定義,如'%(asctime)s - %(levelname)s - %(message)s',支援的 key 可以在 python 自帶的文件 LogRecord attributes 中檢視。
  4. Filter:Filter 用來決定哪些資訊需要輸出。可以被 handler 和 logger 使用,支援層次關係,比如如果設定了 filter 為名稱為 A.B 的 logger,則該 logger 和其子 logger 的資訊會被輸出,如 A.B,A.B.C.

清單 12. 日誌使用示例

import logging
LOG1=logging.getLogger('b.c')
LOG2=logging.getLogger('d.e')
filehandler = logging.FileHandler('test.log','a')
formatter = logging.Formatter('%(name)s %(asctime)s %(levelname)s %(message)s')
filehandler.setFormatter(formatter)
filter=logging.Filter('b')
filehandler.addFilter(filter)
LOG1.addHandler(filehandler)
LOG2.addHandler(filehandler)
LOG1.setLevel(logging.INFO)
LOG2.setLevel(logging.DEBUG)
LOG1.debug('it is a debug info for log1')
LOG1.info('normal infor for log1')
LOG1.warning('warning info for log1:b.c')
LOG1.error('error info for log1:abcd')
LOG1.critical('critical info for log1:not worked')
LOG2.debug('debug info for log2')
LOG2.info('normal info for log2')
LOG2.warning('warning info for log2')
LOG2.error('error:b.c')
LOG2.critical('critical')

上例設定了 filter b,則 b.c 為 b 的子 logger,因此滿足過濾條件該 logger 相關的日誌資訊會 被輸出,而其他不滿足條件的 logger(這裡是 d.e)會被過濾掉。
清單 13. 輸出結果

b.c 2011-11-25 11:07:29,733 INFO normal infor for log1
b.c 2011-11-25 11:07:29,733 WARNING warning info for log1:b.c
b.c 2011-11-25 11:07:29,733 ERROR error info for log1:abcd
b.c 2011-11-25 11:07:29,733 CRITICAL critical info for log1:not worked

logging 的使用非常簡單,同時它是執行緒安全的,下面結合多執行緒的例子講述如何使用 logging 進行 debug。
清單 14. 多執行緒使用 logging

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 logging.conf [loggers] keys=root,simpleExample [handlers] keys=consoleHandler [formatters] keys=simpleFormatter [logger_root] level=DEBUG handlers=consoleHandler [logger_simpleExample] level=DEBUG handlers=consoleHandler qualname=simpleExample propagate=0 [handler_consoleHandler] class=StreamHandler level=DEBUG formatter=simpleFormatter args=(sys.stdout,) [formatter_simpleFormatter] format=%(asctime)s - %(name)s - %(levelname)s - %(message)s datefmt= code example: #!/usr/bin/python import thread import time import logging import logging.config logging.config.fileConfig('logging.conf') # create logger logger = logging.getLogger('simpleExample') # Define a function for the thread def print_time( threadName, delay): logger.debug('thread 1 call print_time function body') count = 0 logger.debug('count:%s',count)

總結

全文介紹了 python 中 debug 的幾種不同的方式,包括 pdb 模組、利用 PyDev 和 Eclipse 整合進行除錯、PyCharm 以及 Debug 日誌進行除錯,希望能給相關 python 使用者一點參考。更多關於 python debugger 的資料可以參見參考資料。