Chris Chris - 4 months ago 10
Python Question

How to print every line of processing code in Python?

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

Is there a way that can serve this purpose? I'm looking for something more convenient so I don't have to type 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'd like to write this without writing print, yet 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 for this?

Answer

You'd better use debugger for that purpose. But if you want to print each line you can run 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)