printing Python stack info from gdb

Skip Montanaro skip at
Sat Jun 9 06:31:23 CEST 2001

>From time to time I've wanted to be able to print the Python stack from gdb.
Today I broke down and spent some time actually implementing something.

    set $__trimpath = 1
    define ppystack
	set $__fr = 0
	select-frame $__fr
	while !($pc > Py_Main && $pc < Py_GetArgcArgv)
	    if $pc > eval_code2 && $pc < set_exc_info
		set $__fn = PyString_AsString(co->co_filename)
		set $__n = PyString_AsString(co->co_name)
		if $__n[0] == '?'
		    set $__n = "<module code>"
		if $__trimpath
		    set $__f = strrchr($__fn, '/')
		    if $__f
			set $__fn = $__f + 1
		printf "%s (%d): %s\n", $__fn, f->f_lineno, $__n
	    set $__fr = $__fr + 1
	    select-frame $__fr
	select-frame 0

Output looks like this (and dribbles out *quite slowly*): (147): apply_tag (152): apply_tag_by_name (302): push_help (113): put_help (119): focus_enter (34): handle_signal (324): main (338): <module code>

If you don't want to trim the paths from the filenames, set $__trimpath to

Warning: I've only tried this with a very recent CVS version of Python on a
PIII-based Linux system with an interpreter compiled using gcc.  I rely on
the ordering of functions within the while loop to detect when to exit the
loop and when the frame I'm examining is an eval_code2 frame.  I'm sure
there are plenty of people out there with more gdb experience than me.  I
welcome any feedback on ways to improve this little bit of code.

Skip Montanaro (skip at

More information about the Python-list mailing list