Emacs + python (Was Re: python is going to die! =()

Andrew Dalke adalke at mindspring.com
Wed Sep 22 15:41:48 EDT 2004


Chris Green wrote:
> M-/ is good for saving keystrokes.

Well I'll be..  Never knew about that one.

> The trick that I like most about emacs+python right now is inserting
> import pdb; pdb.set_trace() and then running the python script from a
> *shell* buffer. It just happens to load the exact same code that would
> occur from running pdb.py directly so code lines can be synced up.

I played around with it a bit but couldn't figure out how
to make it do what I've needed, which is to print the lines
of code as they are running.  Unlike doing a step by step
in the debugger, this gives me an record of the entire
program flow.  I used it once to debug code running at one
of my client's site.

 >>> import spam
 >>> spam.do_this()
50
 >>> import showtrace
 >>> import sys
 >>> sys.settrace(showtrace.linetrace)
 >>> spam.do_this()
Calling: ?
.
Calling: do_this
spam.py:2:   a = 5
spam.py:3:   b = 10
spam.py:4:   c = a*b
spam.py:5:   return c
return
50
return
 >>>

Here's showtrace.py

import sys, linecache

def getlineinfo(frame):
     filename = frame.f_globals.get("__file__")
     if filename is None:
         # Don't know a file?
         return "."
     if filename[-4:] in (".pyc", ".pyo"):
         filename = filename[:-1]
     lineno = frame.f_lineno
     if filename.endswith(".py"):
         line = linecache.getline(filename, lineno)
         if not line:
             line = "???"
         return "%s:%s: %s" % (filename, lineno, line.rstrip())
     line = "???!!!"
     return "%s:%s: %s" % (filename, lineno, line.rstrip())

def getfuncinfo(frame):
     return "Calling: " + frame.f_code.co_name

def linetrace(frame, event, arg):
     if event == 'line':
         sys.stderr.write("  " * indent + getlineinfo(frame) + "\n")
     elif event == 'call':
         sys.stderr.write("  " * indent + getfuncinfo(frame) + "\n")
         return linetrace
     elif event == 'return':
         sys.stderr.write("  " * indent + "return\n")

				Andrew
				dalke at dalkescientific.com



More information about the Python-list mailing list