printing Python stack info from gdb

Skip Montanaro skip at pobox.com
Sat Jun 9 00:31:23 EDT 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>"
		end
		if $__trimpath
		    set $__f = strrchr($__fn, '/')
		    if $__f
			set $__fn = $__f + 1
		    end
		end
		printf "%s (%d): %s\n", $__fn, f->f_lineno, $__n
	    end
	    set $__fr = $__fr + 1
	    select-frame $__fr
	end
	select-frame 0
    end

Output looks like this (and dribbles out *quite slowly*):

    Text_Editor.py (147): apply_tag
    Text_Editor.py (152): apply_tag_by_name
    Script_GUI.py (302): push_help
    Script_GUI.py (113): put_help
    Script_GUI.py (119): focus_enter
    Signal.py (34): handle_signal
    Script_GUI.py (324): main
    Script_GUI.py (338): <module code>

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

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 pobox.com)
(847)971-7098




More information about the Python-list mailing list