Wednesday, April 10, 2013

Using sys._current_frames() and the Python traceback module for debugging

By Vasudev Ram

Python's sys._current_frames() function/method and the traceback module of Python can be useful for debugging your Python code.

In the example below, I've used py, the Python Launcher for Windows. It comes with Python 3.3. If you're on Python 2, you can download the py launcher for Python 2 here. Use either of the versions (32-bit or 64-bit, as appropriate) called launcher*, not launchwin*, for the commands below.

The example below works on both Python 2 and Python 3.

#--------------------------------------------------------
# test_current_frames.py 

import sys, traceback

def foo():

    for thread, frame in sys._current_frames().items():
        print('Thread 0x%x' % thread)
        traceback.print_stack(frame)

def bar():
    foo()

def baz():
    bar()

baz()
#--------------------------------------------------------

Run the program with any of the following 3 commands:
py test_current_frames.py

or

py -2 test_current_frames.py

or

py -3 test_current_frames.py
You should get output similar to this:
Thread 0x17dc
  File "test_current_frames.py", line 17, in 
    baz()
  File "test_current_frames.py", line 15, in baz
    bar()
  File "test_current_frames.py", line 12, in bar
    foo()
  File "test_current_frames.py", line 9, in foo
    traceback.print_stack(frame)

Also read more about the traceback module on Doug Hellmann's Python Module Of The Week (PyMOTW) site, a.k.a. PyMOTW.

- Vasudev Ram - Dancing Bison Enterprises

1 comment:

Anonymous said...

The launchwin versions are installed by 3.3. Installing it to the Windows directory means one less directory that needs to be added to PATH. Seems fine to me.