2015-07-10 42 views
3

當測試或創建一個新函數時,我經常打印正在發生的每行代碼,以便我可以看到每行是如何處理的。如何在Python中打印每一行處理代碼?

有沒有一種方法可以達到這個目的?我正在尋找更方便的東西,所以我不必在每行之後輸入打印內容。

例如,我想,而不是寫這個功能

def test_func(): 
    l = range(10) 
    print l 
    l = zip(l,range(30,40)) 
    print l 
    l = dict(l) 
    print l 

寫這無需編寫打印,但仍然得到每一行打印

def test_func(): 
    l = range(10) 
    l = zip(l,range(30,40)) 
    l = dict(l) 

也許我可以用一個Python裝飾或爲此?

+1

調查例如https://docs.python.org/2/library/debug.html - 這個問題對於SO來說太廣泛了。 – jonrsharpe

+4

使用調試器,這就是它的功能 –

+0

我通常先在交互式會話中使用各個步驟,然後再將其寫入函數中。 – mkrieger1

回答

6

你最好使用調試器來達到這個目的。但是如果你想打印每一行,你可以用'trace'來運行程序。

python -m trace --trace asd.py 

--- modulename: asd, funcname: <module> 
asd.py(1): def test_func(): 
asd.py(6): test_func(); 
--- modulename: asd, funcname: test_func 
asd.py(2):  l = range(10) 
asd.py(3):  l = zip(l,range(30,40)) 
asd.py(4):  l = dict(l) 
--- modulename: trace, funcname: _unsettrace 
trace.py(80):   sys.settrace(None) 
0

最好的辦法是使用PDB,運行具有如下PDB你的代碼,在PDB使用

python -m pdb create_vpc.py 

頻繁選項,

(pdb) n - next line 
(pdb) l - print few lines before and after 
(pdb) range(10) or yoru variable "test" ---> this prints current value of any variable from stack 
(pdb) !val = range(10) ----> assign any variable while running 

您還可以在導入PDB你的程序的任何一點,所以它會停在那裏,給你的控制檯

def test_func(): 
l = range(10) 
print l 
import pdb;pdb.set_trace()  -----> Program stops here and you can check any current variable status or before and after lines etc 
l = zip(l,range(30,40)) 
print l 
l = dict(l) 
print l 
+0

你也可以使用ipdb。愜意 – comalex3

相關問題