使用 pdb 進行調試
pdb 是 python 自帶的一個包,爲 python 程序提供了一種交互的源代碼調試功能,主要特性包括設置斷點、單步調試、進入函數調試、查看當前代碼、查看棧片斷、動態改變變量的值等。pdb 提供了一些經常使用的調試命令,詳情見表 1。python
表 1. pdb 經常使用命令
命令 | 解釋 |
---|---|
break 或 b 設置斷點 | 設置斷點 |
continue 或 c | 繼續執行程序 |
list 或 l | 查看當前行的代碼段 |
step 或 s | 進入函數 |
return 或 r | 執行代碼直到從當前函數返回 |
exit 或 q | 停止並退出 |
next 或 n | 執行下一行 |
pp | 打印變量的值 |
help | 幫助 |
下面結合具體的實例講述如何使用 pdb 進行調試。linux
清單 1. 測試代碼示例
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 調試步驟以下:
[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
[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 過程當中打印變量
[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() 驗證。eclipse
清單 5. 中止 debug 繼續執行程序
[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 的語句。jsp
清單 6. debug 過程當中顯示代碼
[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)
在使用函數的狀況下進行 debugide
清單 7. 使用函數的例子
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
[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. 在調試的時候動態改變值
[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 窗口布局
![圖片示例](http://static.javashuo.com/static/loading.gif)
下面結合實例講述如何利用 PyCharm 進行多線程調試。具體調試所用的代碼實例見清單 10。
清單 10. PyCharm 調試代碼實例
__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. 斷點設置
![圖片示例 2](http://static.javashuo.com/static/loading.gif)
表達式求值:在調試過程當中有的時候須要追蹤一些表達式的值來發現程序中的問題,Pycharm 支持表達式求值,能夠經過選中該表達式,而後選擇「Run」->」Evaluate Expression」,在出現的窗口中直接選擇 Evaluate 即可以查看。
Pychar 同時提供了 Variables 和 Watches 窗口,其中調試步驟中所涉及的具體變量的值能夠直接在 variable 一欄中查看。
圖 3. 變量查看
![圖片示例 3](http://static.javashuo.com/static/loading.gif)
若是要動態的監測某個變量能夠直接選中該變量並選擇菜單」Run」->」Add Watch」添加到 watches 欄中。當調試進行到該變量所在的語句時,在該窗口中能夠直接看到該變量的具體值。
圖 4. 監測變量
![圖片示例 4](http://static.javashuo.com/static/loading.gif)
對於多線程程序來講,一般會有多個線程,當須要 debug 的斷點分別設置在不一樣線程對應的線程體中的時候,一般須要 IDE 有良好的多線程調試功能的支持。 Pycharm 中在主線程啓動子線程的時候會自動產生一個 Dummy 開頭的名字的虛擬線程,每個 frame 對應各自的調試幀。如圖 5,本實例中一共有四個線程,其中主線程生成了三個線程,分別爲 Dummy-4,Dummy-5,Dummy-6. 其中 Dummy-4 對應線程 1,其他分別對應線程 2 和線程 3。
圖 5. 多線程窗口
![圖片示例 5](http://static.javashuo.com/static/loading.gif)
當調試進入到各個線程的子程序時,Frame 會自動切換到其所對應的 frame,相應的變量欄中也會顯示與該過程對應的相關變量,如圖 6,直接控制調試按鈕,如 setp in,step over 即可以方便的進行調試。
圖 6. 子線程調試
![圖片示例 6](http://static.javashuo.com/static/loading.gif)
查看大圖。
使用 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
![圖片示例 7](http://static.javashuo.com/static/loading.gif)
安裝完成以後須要配置 Python 解釋器,在 Eclipse 菜單欄中,選擇 Window > Preferences > Pydev > Interpreter – Python。Python 安裝在 C:\Python27 路徑下。單擊 New,選擇 Python 解釋器 python.exe,打開後顯示出一個包含不少複選框的窗口,選擇須要加入系統 PYTHONPATH 的路徑,單擊 OK。
圖 8. 配置 PyDev
![圖片示例 8](http://static.javashuo.com/static/loading.gif)
在配置完 Pydev 以後,能夠經過在 Eclipse 菜單欄中,選擇 File > New > Project > Pydev >Pydev Project,單擊 Next 建立 Python 項目,下面的內容假設 python 項目已經建立,而且有個須要調試的腳本 remote.py(具體內容以下),它是一個登錄到遠程機器上去執行一些命令的腳本,在運行的時候須要傳入一些參數,下面將詳細講述如何在調試過程當中傳入參數 .
清單 11. Pydev 調試示例代碼
#!/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. 配置變量
![圖片示例 9](http://static.javashuo.com/static/loading.gif)
在窗口」Select Variable」以後選擇「Edit Varuables」 ,出現以下窗口,在下圖中選擇」New」 並在彈出的窗口中輸入對應的變量名和值。特別須要注意的是在值的後面必定要有空格,否則全部的參數都會被當作第一個參數讀入。
圖 10. 添加具體變量
![圖片示例 10](http://static.javashuo.com/static/loading.gif)
按照以上方式依次配置完全部參數,而後在」select variable「窗口中安裝參數所須要的順序依次選擇對應的變量。配置完成以後狀態以下圖 11 所示。
圖 11. 完成配置
![圖片示例 11](http://static.javashuo.com/static/loading.gif)
選擇 Debug 即可以開始程序的調試,調試方法與 eclipse 內置的調試功能的使用類似,而且支持多線程的 debug,這方面的文章已經有不少,讀者能夠自行搜索閱讀,或者參考」使用 Eclipse 平臺進行調試「一文。
使用日誌功能達到調試的目的
日誌信息是軟件開發過程當中進行調試的一種很是有用的方式,特別是在大型軟件開發過程須要不少相關人員進行協做的狀況下。開發人員經過在代碼中加入一些特定的可以記錄軟件運行過程當中的各類事件信息可以有利於甄別代碼中存在的問題。這些信息可能包括時間,描述信息以及錯誤或者異常發生時候的特定上下文信息。 最原始的 debug 方法是經過在代碼中嵌入 print 語句,經過輸出一些相關的信息來定位程序的問題。但這種方法有必定的缺陷,正常的程序輸出和 debug 信息混合在一塊兒,給分析帶來必定困難,當程序調試結束再也不須要 debug 輸出的時候,一般沒有很簡單的方法將 print 的信息屏蔽掉或者定位到文件。python 中自帶的 logging 模塊能夠比較方便的解決這些問題,它提供日誌功能,將 logger 的 level 分爲五個級別,能夠經過 Logger.setLevel(lvl) 來設置。默認的級別爲 warning。
表 2. 日誌的級別
Level | 使用情形 |
---|---|
DEBUG | 詳細的信息,在追蹤問題的時候使用 |
INFO | 正常的信息 |
WARNING | 一些不可預見的問題發生,或者將要發生,如磁盤空間低等,但不影響程序的運行 |
ERROR | 因爲某些嚴重的問題,程序中的一些功能受到影響 |
CRITICAL | 嚴重的錯誤,或者程序自己不可以繼續運行 |
logging lib 包含 4 個主要對象
- 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 實例。
- Handler:Handler 用來處理信息的輸出,能夠將信息輸出到控制檯,文件或者網絡。能夠經過 Logger.addHandler() 來給 logger 對象添加 handler,經常使用的 handler 有 StreamHandler 和 FileHandler 類。StreamHandler 發送錯誤信息到流,而 FileHandler 類用於向文件輸出日誌信息,這兩個 handler 定義在 logging 的核心模塊中。其餘的 hander 定義在 logging.handles 模塊中,如 HTTPHandler,SocketHandler。
- Formatter:Formatter 則決定了 log 信息的格式 , 格式使用相似於 %(< dictionary key >)s 的形式來定義,如'%(asctime)s - %(levelname)s - %(message)s',支持的 key 能夠在 python 自帶的文檔 LogRecord attributes 中查看。
- 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
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 的資料能夠參見參考資料。
參考資料
學習
- 參考 Tutorial Python查看 Python 的官方文檔。
- 參考 Python Logging文檔獲取更多的 logging 使用信息。
- 在 developerWorks Linux 專區 尋找爲 Linux 開發人員(包括 Linux 新手入門)準備的更多參考資料,查閱咱們 最受歡迎的文章和教程。
- 在 developerWorks 上查閱全部 Linux 技巧 和 Linux 教程。
- 隨時關注 developerWorks 技術活動和網絡廣播。
討論
- 參考 Python Debugger 博客獲取更多的 Python debug 信息。
- 加入 developerWorks 中文社區,developerWorks 社區是一個面向全球 IT 專業人員,能夠提供博客、書籤、wiki、羣組、聯繫、共享和協做等社區功能的專業社交網絡社區。
- 加入 IBM 軟件下載與技術交流羣組,參與在線交流。