Python代碼調(diào)試的幾種方法總結(jié)
使用 pdb 進行調(diào)試
pdb 是 python 自帶的一個包,為 python 程序提供了一種交互的源代碼調(diào)試功能,主要特性包括設置斷點、單步調(diào)試、進入函數(shù)調(diào)試、查看當前代碼、查看棧片段、動態(tài)改變變量的值等。pdb 提供了一些常用的調(diào)試命令,詳情見表 1。
表 1. pdb 常用命令
下面結(jié)合具體的實例講述如何使用 pdb 進行調(diào)試。
清單 1. 測試代碼示例
import pdb a = "aaa" pdb.set_trace() b = "bbb" c = "ccc" final = a + b + c print final
開始調(diào)試:直接運行腳本,會停留在 pdb.set_trace() 處,選擇 n+enter 可以執(zhí)行當前的 statement。在第一次按下了 n+enter 之后可以直接按 enter 表示重復執(zhí)行上一條 debug 命令。
清單 2. 利用 pdb 調(diào)試
[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 會以一種非常粗魯?shù)姆绞酵顺龀绦颍浣Y(jié)果是直接 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
打印變量的值:如果需要在調(diào)試過程中打印變量的值,可以直接使用 p 加上變量名,但是需要注意的是打印僅僅在當前的 statement 已經(jīng)被執(zhí)行了之后才能看到具體的值,否則會報 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 使程序繼續(xù)執(zhí)行。如果在下面的程序中繼續(xù)有 set_statement() 的申明,則又會重新進入到 debug 的狀態(tài),讀者可以在代碼 print final 之前再加上 set_trace() 驗證。
清單 5. 停止 debug 繼續(xù)執(zhí)行程序
[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 過程中顯示代碼
[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)
在使用函數(shù)的情況下進行 debug
清單 7. 使用函數(shù)的例子
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。如果想要對函數(shù)進行 debug 如何處理呢 ? 可以直接使用 s 進入函數(shù)塊。函數(shù)里面的單步調(diào)試與上面的介紹類似。如果不想在函數(shù)里單步調(diào)試可以在斷點處直接按 r 退出到調(diào)用的地方。
清單 8. 對函數(shù)進行 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)
在調(diào)試的時候動態(tài)改變值 。在調(diào)試的時候可以動態(tài)改變變量的值,具體如下實例。需要注意的是下面有個錯誤,原因是 b 已經(jīng)被賦值了,如果想重新改變 b 的賦值,則應該使用! B。
清單 9. 在調(diào)試的時候動態(tài)改變值
[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 調(diào)試有個明顯的缺陷就是對于多線程,遠程調(diào)試等支持得不夠好,同時沒有較為直觀的界面顯示,不太適合大型的 python 項目。而在較大的 python 項目中,這些調(diào)試需求比較常見,因此需要使用更為高級的調(diào)試工具。接下來將介紹 PyCharm IDE 的調(diào)試方法 .
使用 PyCharm 進行調(diào)試
PyCharm 是由 JetBrains 打造的一款 Python IDE,具有語法高亮、Project 管理、代碼跳轉(zhuǎn)、智能提示、自動完成、單元測試、版本控制等功能,同時提供了對 Django 開發(fā)以及 Google App Engine 的支持。分為個人獨立版和商業(yè)版,需要 license 支持,也可以獲取免費的 30 天試用。試用版本的 Pycharm 可以在官網(wǎng)上下載,下載地址為:http://www.jetbrains.com/pycharm/download/index.html。 PyCharm 同時提供了較為完善的調(diào)試功能,支持多線程,遠程調(diào)試等,可以支持斷點設置,單步模式,表達式求值,變量查看等一系列功能。PyCharm IDE 的調(diào)試窗口布局如圖 1 所示。
圖 1. PyCharm IDE 窗口布局
下面結(jié)合實例講述如何利用 PyCharm 進行多線程調(diào)試。具體調(diào)試所用的代碼實例見清單 10。
清單 10. PyCharm 調(diào)試代碼實例
__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
在調(diào)試之前通常需要設置斷點,斷點可以設置在循環(huán)或者條件判斷的表達式處或者程序的關(guān)鍵點。設置斷點的方法非常簡單:在代碼編輯框中將光標移動到需要設置斷點的行,然后直接按 Ctrl+F8 或者選擇菜單"Run"->"Toggle Line Break Point",更為直接的方法是雙擊代碼編輯處左側(cè)邊緣,可以看到出現(xiàn)紅色的小圓點(如圖 2)。當調(diào)試開始的時候,當前正在執(zhí)行的代碼會直接顯示為藍色。下圖中設置了三個斷點,藍色高亮顯示的為正在執(zhí)行的代碼。
圖 2. 斷點設置
表達式求值:在調(diào)試過程中有的時候需要追蹤一些表達式的值來發(fā)現(xiàn)程序中的問題,Pycharm 支持表達式求值,可以通過選中該表達式,然后選擇“Run”->”Evaluate Expression”,在出現(xiàn)的窗口中直接選擇 Evaluate 便可以查看。
Pychar 同時提供了 Variables 和 Watches 窗口,其中調(diào)試步驟中所涉及的具體變量的值可以直接在 variable 一欄中查看。
圖 3. 變量查看
如果要動態(tài)的監(jiān)測某個變量可以直接選中該變量并選擇菜單”Run”->”Add Watch”添加到 watches 欄中。當調(diào)試進行到該變量所在的語句時,在該窗口中可以直接看到該變量的具體值。
圖 4. 監(jiān)測變量
對于多線程程序來說,通常會有多個線程,當需要 debug 的斷點分別設置在不同線程對應的線程體中的時候,通常需要 IDE 有良好的多線程調(diào)試功能的支持。 Pycharm 中在主線程啟動子線程的時候會自動產(chǎn)生一個 Dummy 開頭的名字的虛擬線程,每一個 frame 對應各自的調(diào)試幀。如圖 5,本實例中一共有四個線程,其中主線程生成了三個線程,分別為 Dummy-4,Dummy-5,Dummy-6. 其中 Dummy-4 對應線程 1,其余分別對應線程 2 和線程 3。
圖 5. 多線程窗口
當調(diào)試進入到各個線程的子程序時,F(xiàn)rame 會自動切換到其所對應的 frame,相應的變量欄中也會顯示與該過程對應的相關(guān)變量,如圖 6,直接控制調(diào)試按鈕,如 setp in,step over 便可以方便的進行調(diào)試。
圖 6. 子線程調(diào)試
使用 PyDev 進行調(diào)試
PyDev 是一個開源的的 plugin,它可以方便的和 Eclipse 集成,提供方便強大的調(diào)試功能。同時作為一個優(yōu)秀的 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,打開后顯示出一個包含很多復選框的窗口,選擇需要加入系統(tǒng) PYTHONPATH 的路徑,單擊 OK。
圖 8. 配置 PyDev
在配置完 Pydev 之后,可以通過在 Eclipse 菜單欄中,選擇 File > New > Project > Pydev >Pydev Project,單擊 Next 創(chuàng)建 Python 項目,下面的內(nèi)容假設 python 項目已經(jīng)創(chuàng)建,并且有個需要調(diào)試的腳本 remote.py(具體內(nèi)容如下),它是一個登陸到遠程機器上去執(zhí)行一些命令的腳本,在運行的時候需要傳入一些參數(shù),下面將詳細講述如何在調(diào)試過程中傳入?yún)?shù) .
清單 11. Pydev 調(diào)試示例代碼
#!/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()
在調(diào)試的時候有些情況需要傳入一些參數(shù),在調(diào)試之前需要進行相應的配置以便接收所需要的參數(shù),選擇需要調(diào)試的程序(本例 remote.py),該腳本在 debug 的過程中需要輸入四個參數(shù):host,user,password 以及命令。在 eclipse 的工程目錄下選擇需要 debug 的程序,單擊右鍵,選擇“Debug As”->“Debug Configurations”,在 Arguments Tab 頁中選擇“Variables”。如下 圖 9 所示 .
圖 9. 配置變量
在窗口”Select Variable”之后選擇“Edit Varuables” ,出現(xiàn)如下窗口,在下圖中選擇”New” 并在彈出的窗口中輸入對應的變量名和值。特別需要注意的是在值的后面一定要有空格,不然所有的參數(shù)都會被當做第一個參數(shù)讀入。
圖 10. 添加具體變量
按照以上方式依次配置完所有參數(shù),然后在”select variable“窗口中安裝參數(shù)所需要的順序依次選擇對應的變量。配置完成之后狀態(tài)如下圖 11 所示。
圖 11. 完成配置
選擇 Debug 便可以開始程序的調(diào)試,調(diào)試方法與 eclipse 內(nèi)置的調(diào)試功能的使用相似,并且支持多線程的 debug,這方面的文章已經(jīng)有很多,讀者可以自行搜索閱讀,或者參考”使用 Eclipse 平臺進行調(diào)試“一文。
使用日志功能達到調(diào)試的目的
日志信息是軟件開發(fā)過程中進行調(diào)試的一種非常有用的方式,特別是在大型軟件開發(fā)過程需要很多相關(guān)人員進行協(xié)作的情況下。開發(fā)人員通過在代碼中加入一些特定的能夠記錄軟件運行過程中的各種事件信息能夠有利于甄別代碼中存在的問題。這些信息可能包括時間,描述信息以及錯誤或者異常發(fā)生時候的特定上下文信息。 最原始的 debug 方法是通過在代碼中嵌入 print 語句,通過輸出一些相關(guān)的信息來定位程序的問題。但這種方法有一定的缺陷,正常的程序輸出和 debug 信息混合在一起,給分析帶來一定困難,當程序調(diào)試結(jié)束不再需要 debug 輸出的時候,通常沒有很簡單的方法將 print 的信息屏蔽掉或者定位到文件。python 中自帶的 logging 模塊可以比較方便的解決這些問題,它提供日志功能,將 logger 的 level 分為五個級別,可以通過 Logger.setLevel(lvl) 來設置。默認的級別為 warning。
表 2. 日志的級別
ogging lib 包含 4 個主要對象
- logger:logger 是程序信息輸出的接口。它分散在不同的代碼中使得程序可以在運行的時候記錄相應的信息,并根據(jù)設置的日志級別或 filter 來決定哪些信息需要輸出并將這些信息分發(fā)到其關(guān)聯(lián)的 handler。常用的方法有 Logger.setLevel(),Logger.addHandler() ,Logger.removeHandler() ,Logger.addFilter() ,Logger.debug(), Logger.info(), Logger.warning(), Logger.error(),getLogger() 等。logger 支持層次繼承關(guān)系,子 logger 的名稱通常是父 logger.name 的方式。如果不創(chuàng)建 logger 的實例,則使用默認的 root logger,通過 logging.getLogger() 或者 logging.getLogger("") 得到 root logger 實例。
- Handler:Handler 用來處理信息的輸出,可以將信息輸出到控制臺,文件或者網(wǎng)絡。可以通過 Logger.addHandler() 來給 logger 對象添加 handler,常用的 handler 有 StreamHandler 和 FileHandler 類。StreamHandler 發(fā)送錯誤信息到流,而 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 使用,支持層次關(guān)系,比如如果設置了 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 相關(guān)的日志信息會 被輸出,而其他不滿足條件的 logger(這里是 d.e)會被過濾掉。
清單 13. 輸出結(jié)果
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 的使用非常簡單,同時它是線程安全的,下面結(jié)合多線程的例子講述如何使用 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)
總結(jié)
全文介紹了 python 中 debug 的幾種不同的方式,包括 pdb 模塊、利用 PyDev 和 Eclipse 集成進行調(diào)試、PyCharm 以及 Debug 日志進行調(diào)試,希望能給相關(guān) python 使用者一點參考。更多關(guān)于 python debugger 的資料可以參見參考資料。
相關(guān)文章
詳解Python的hasattr() getattr() setattr() 函數(shù)使用方法
這篇文章主要介紹了詳解Python的hasattr() getattr() setattr() 函數(shù)使用方法,本文給大家介紹的非常詳細,具有一定的參考借鑒價值,需要的朋友可以參考下2018-07-07matplotlib多子圖實現(xiàn)共享坐標軸的示例詳解
這篇文章主要為大家詳細介紹了matplotlib繪制多子圖師如何實現(xiàn)共享坐標軸,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下2024-02-02