使用 pdb 進行調試
pdb 是 python 自帶的一個包,為 python 程序提供了一種交互的源代碼調試功能,主要特性包括設置斷點、單步調試、進入函數調試、查看當前代碼、查看棧片段、動態改變變量的值等。pdb 提供了一些常用的調試命令,詳情見表 1。
表 1. pdb 常用命令
命令 | 解釋 |
---|---|
break 或 b 設置斷點 | 設置斷點 |
continue 或 c | 繼續執行程序 |
list 或 l | 查看當前行的代碼段 |
step 或 s | 進入函數 |
return 或 r | 執行代碼直到從當前函數返回 |
exit 或 q | 中止並退出 |
next 或 n | 執行下一行 |
pp | 打印變量的值 |
help | 幫助 |
下面結合具體的實例講述如何使用 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: 錯誤。
清單 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:
(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
|
__author__ = 'zhangying'
#!/usr/bin/python
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count 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("exitn")
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. 日志的級別
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 信息的格式 , 格式使用類似於 %()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. 日志使用示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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. 輸出結果
1
2
3
4
|
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 的資料可以參見參考資料。