Index: Lib/traceback.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/traceback.py,v retrieving revision 1.31 diff -u -r1.31 traceback.py --- Lib/traceback.py 26 Oct 2004 09:16:41 -0000 1.31 +++ Lib/traceback.py 9 Jan 2005 01:51:07 -0000 @@ -3,6 +3,7 @@ import linecache import sys import types +import inspect __all__ = ['extract_stack', 'extract_tb', 'format_exception', 'format_exception_only', 'format_list', 'format_stack', @@ -12,17 +13,42 @@ def _print(file, str='', terminator='\n'): file.write(str+terminator) +def _format_vars(localvars): + lst = [] + keys = localvars.keys() + keys.sort() + for key in keys: + # skip Python-special vars + if key.startswith("__") and key.endswith("__"): + continue + val = localvars[key] + # skip modules if the variable name and the module name are + # identical + if isinstance(val, types.ModuleType) and key == val.__name__: + continue + val = repr(val) + if val != val[:30]: + val = "%s..." % val[:30] + lst.append(' %s: %s' % (key, val)) + return "\n".join(lst) -def print_list(extracted_list, file=None): +def _print_vars(file, localvars): + _print(file, _format_vars(localvars)) + +def print_list(extracted_list, file=None, args=False): """Print the list of tuples as returned by extract_tb() or - extract_stack() as a formatted stack trace to the given file.""" + extract_stack() as a formatted stack trace to the given file. + If the optional args argument is True, the local variables + are printed as well.""" if file is None: file = sys.stderr - for filename, lineno, name, line in extracted_list: + for filename, lineno, name, line, localvars in extracted_list: _print(file, ' File "%s", line %d, in %s' % (filename,lineno,name)) if line: _print(file, ' %s' % line.strip()) + if args: + _print_vars(file, localvars) def format_list(extracted_list): """Format a list of traceback entry tuples for printing. @@ -35,7 +61,7 @@ whose source text line is not None. """ list = [] - for filename, lineno, name, line in extracted_list: + for filename, lineno, name, line, localvars in extracted_list: item = ' File "%s", line %d, in %s\n' % (filename,lineno,name) if line: item = item + ' %s\n' % line.strip() @@ -43,13 +69,14 @@ return list -def print_tb(tb, limit=None, file=None): +def print_tb(tb, limit=None, file=None, args=False): """Print up to 'limit' stack trace entries from the traceback 'tb'. If 'limit' is omitted or None, all entries are printed. If 'file' is omitted or None, the output goes to sys.stderr; otherwise 'file' should be an open file or file-like object with a write() - method. + method. If the optional args argument is True, each frame's + local variables are printed. """ if file is None: file = sys.stderr @@ -59,6 +86,7 @@ n = 0 while tb is not None and (limit is None or n < limit): f = tb.tb_frame + localvars = inspect.getargvalues(f)[3] lineno = tb.tb_lineno co = f.f_code filename = co.co_filename @@ -67,7 +95,10 @@ ' File "%s", line %d, in %s' % (filename,lineno,name)) linecache.checkcache(filename) line = linecache.getline(filename, lineno) - if line: _print(file, ' ' + line.strip()) + if line: + _print(file, ' ' + line.strip()) + if args: + _print_vars(file, localvars) tb = tb.tb_next n = n+1 @@ -80,11 +111,12 @@ This is useful for alternate formatting of stack traces. If 'limit' is omitted or None, all entries are extracted. A - pre-processed stack trace entry is a quadruple (filename, line - number, function name, text) representing the information that is - usually printed for a stack trace. The text is a string with - leading and trailing whitespace stripped; if the source is not - available it is None. + pre-processed stack trace entry is a five-element tuple (filename, + line number, function name, text, localvars) representing the + information that is usually printed for a stack trace. The text + is a string with leading and trailing whitespace stripped; if the + source is not available it is None. The localvars item is a + dictionary of local variables for that frame. """ if limit is None: if hasattr(sys, 'tracebacklimit'): @@ -96,18 +128,19 @@ lineno = tb.tb_lineno co = f.f_code filename = co.co_filename + localvars = inspect.getargvalues(f)[3] name = co.co_name linecache.checkcache(filename) line = linecache.getline(filename, lineno) if line: line = line.strip() else: line = None - list.append((filename, lineno, name, line)) + list.append((filename, lineno, name, line, localvars)) tb = tb.tb_next n = n+1 return list -def print_exception(etype, value, tb, limit=None, file=None): +def print_exception(etype, value, tb, limit=None, file=None, args=False): """Print exception up to 'limit' stack trace entries from 'tb' to 'file'. This differs from print_tb() in the following ways: (1) if @@ -116,13 +149,14 @@ stack trace; (3) if type is SyntaxError and value has the appropriate format, it prints the line where the syntax error occurred with a caret on the next line indicating the approximate - position of the error. + position of the error. If the optional args argument is True, + each frame's local variables are printed. """ if file is None: file = sys.stderr if tb: _print(file, 'Traceback (most recent call last):') - print_tb(tb, limit, file) + print_tb(tb, limit, file, args) lines = format_exception_only(etype, value) for line in lines[:-1]: _print(file, line, ' ') @@ -232,19 +266,21 @@ limit, file) -def print_stack(f=None, limit=None, file=None): +def print_stack(f=None, limit=None, file=None, args=False): """Print a stack trace from its invocation point. The optional 'f' argument can be used to specify an alternate stack frame at which to start. The optional 'limit' and 'file' - arguments have the same meaning as for print_exception(). + arguments have the same meaning as for print_exception(). If + the optional args argument is True, the local variables for + each stack frame are printed as well. """ if f is None: try: raise ZeroDivisionError except ZeroDivisionError: f = sys.exc_info()[2].tb_frame.f_back - print_list(extract_stack(f, limit), file) + print_list(extract_stack(f, limit), file, args=args) def format_stack(f=None, limit=None): """Shorthand for 'format_list(extract_stack(f, limit))'.""" @@ -260,9 +296,9 @@ The return value has the same format as for extract_tb(). The optional 'f' and 'limit' arguments have the same meaning as for - print_stack(). Each item in the list is a quadruple (filename, - line number, function name, text), and the entries are in order - from oldest to newest stack frame. + print_stack(). Each item in the list is a five-element tuple + (filename, line number, function name, text, localvars), and the + entries are in order from oldest to newest stack frame. """ if f is None: try: @@ -275,6 +311,7 @@ list = [] n = 0 while f is not None and (limit is None or n < limit): + localvars = inspect.getargvalues(f)[3] lineno = f.f_lineno co = f.f_code filename = co.co_filename @@ -283,7 +320,7 @@ line = linecache.getline(filename, lineno) if line: line = line.strip() else: line = None - list.append((filename, lineno, name, line)) + list.append((filename, lineno, name, line, localvars)) f = f.f_back n = n+1 list.reverse() Index: Lib/test/test_traceback.py =================================================================== RCS file: /cvsroot/python/python/dist/src/Lib/test/test_traceback.py,v retrieving revision 1.14 diff -u -r1.14 test_traceback.py --- Lib/test/test_traceback.py 1 Nov 2004 22:27:14 -0000 1.14 +++ Lib/test/test_traceback.py 9 Jan 2005 01:51:07 -0000 @@ -1,5 +1,6 @@ """Test cases for traceback module""" +import sys import unittest from test.test_support import run_unittest, is_jython @@ -40,6 +41,17 @@ self.assert_(len(err) == 3) self.assert_(err[1].strip() == "[x for x in x] = x") + def test_args(self): + def f1(a): + raise TypeError + + try: + f1(37) + except TypeError: + lst = traceback.extract_tb(sys.exc_info()[2]) + ### lst[0] is me, lst[1] is f1 + self.assertEqual(lst[1][4], {'a': 37}) + def test_bug737473(self): import sys, os, tempfile, time @@ -77,7 +89,7 @@ try: test_bug737473.test() except NotImplementedError: - src = traceback.extract_tb(sys.exc_traceback)[-1][-1] + src = traceback.extract_tb(sys.exc_traceback)[-1][-2] self.failUnlessEqual(src, 'raise NotImplementedError') finally: sys.path[:] = savedpath Index: Doc/lib/libtraceback.tex =================================================================== RCS file: /cvsroot/python/python/dist/src/Doc/lib/libtraceback.tex,v retrieving revision 1.19 diff -u -r1.19 libtraceback.tex --- Doc/lib/libtraceback.tex 13 Dec 2003 22:34:09 -0000 1.19 +++ Doc/lib/libtraceback.tex 9 Jan 2005 01:51:07 -0000 @@ -28,7 +28,8 @@ \end{funcdesc} \begin{funcdesc}{print_exception}{type, value, traceback\optional{, - limit\optional{, file}}} + limit=None\optional{, file=None\optional{, + args=False}}}} Print exception information and up to \var{limit} stack trace entries from \var{traceback} to \var{file}. This differs from \function{print_tb()} in the @@ -37,7 +38,9 @@ exception \var{type} and \var{value} after the stack trace; (3) if \var{type} is \exception{SyntaxError} and \var{value} has the appropriate format, it prints the line where the syntax error occurred -with a caret indicating the approximate position of the error. +with a caret indicating the approximate position of the error. If the +optional \var{args} argument is \code{True}, each frame's local variables +are printed. \end{funcdesc} \begin{funcdesc}{print_exc}{\optional{limit\optional{, file}}} @@ -59,11 +62,14 @@ sys.last_value, sys.last_traceback, \var{limit}, \var{file})}. \end{funcdesc} -\begin{funcdesc}{print_stack}{\optional{f\optional{, limit\optional{, file}}}} +\begin{funcdesc}{print_stack}{\optional{f=None\optional{, +limit=None\optional{, file=None\optional{, args=False}}}}} This function prints a stack trace from its invocation point. The optional \var{f} argument can be used to specify an alternate stack frame to start. The optional \var{limit} and \var{file} arguments have the -same meaning as for \function{print_exception()}. +same meaning as for \function{print_exception()}. If +the optional \var{args} argument is \code{True}, the local variables for +each stack frame are printed as well. \end{funcdesc} \begin{funcdesc}{extract_tb}{traceback\optional{, limit}} @@ -71,11 +77,14 @@ entries extracted from the traceback object \var{traceback}. It is useful for alternate formatting of stack traces. If \var{limit} is omitted or \code{None}, all entries are extracted. A -``pre-processed'' stack trace entry is a quadruple (\var{filename}, -\var{line number}, \var{function name}, \var{text}) representing +``pre-processed'' stack trace entry is a five-element tuple +(\var{filename}, \var{line number}, \var{function name}, +{}\var{text}, \var{localvars}) representing the information that is usually printed for a stack trace. The \var{text} is a string with leading and trailing whitespace stripped; if the source is not available it is \code{None}. +The \var{localvars} item is a dictionary of local variables for that +frame. \end{funcdesc} \begin{funcdesc}{extract_stack}{\optional{f\optional{, limit}}}