[Python-Dev] FW: printing Python stack info from gdb

Tim Peters tim.one@home.com
Sun, 10 Jun 2001 00:25:51 -0400

Fwd'ing this Skip gem from c.l.py, primarily so I can find it again next
time I'm thrashing on a Unix box.  gdb clearly needs to adopt Python as its
extension language.

but-then-what-doesn't-ly y'rs  - tim

-----Original Message-----
From: python-list-admin@python.org
[mailto:python-list-admin@python.org]On Behalf Of Skip Montanaro
Sent: Saturday, June 09, 2001 12:31 AM
To: python-list@python.org
Subject: printing Python stack info from gdb

>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*):

    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

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@pobox.com)