How do I print each line of processing code in Python?

When testing or creating a new function, I often like to print every line of code that happens so I can see how each line is processed.

Is there a way that can serve this purpose? I'm looking for something more convenient so I don't have to print after every line.

For example, instead of writing this function

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

      

I would like to write this without printing, but still get every line printed

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

      

Perhaps I can use a Python decorator or something?

+3


source to share


2 answers


You are better off using a debugger for this purpose. But if you want to print every line, you can run the program with "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)

      

+6


source


The best way is to use pdb, run the code from pdb like below,

python -m pdb create_vpc.py

      

Common options used in pdb are



(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 

      

You can also import pdb anywhere in your program so that it stops at it and gives you a console

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


source







All Articles