#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ #end_pymotw_header import traceback import sys from traceback_example import call_function def f(): traceback.print_stack(file=sys.stdout) print 'Calling f() directly:' f() print print 'Calling f() from 3 levels deep:' call_function(f)
import traceback import sys from traceback_example import call_function def f(): summary = traceback.StackSummary.extract(traceback.walk_stack(None)) print(''.join(summary.format())) print('Calling f() directly:') f() print() print('Calling f() from 3 levels deep:') call_function(f)
# # traceback_extract_stack.py import sys import os from traceback_example import call_function template = '{filename:<26}:{linenum}:{funcname}:\n {source}' def f(): return traceback.extract_stack() stack = call_function(f) for filename, linenum, funcname, source in stack: if funcname != '<module>': funcname = funcname + '()' print( template.format(filename=os.path.basename(filename), linenum=linenum, source=source, funcname=funcname)) # It also accepts arguments, not shown here, to start from an alternate place in the stack frame or to limit the depth of traversal. # # $ python3 traceback_extract_stack.py # # traceback_extract_stack.py:23:<module>: # stack = call_function(f)
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id: traceback_format_stack.py 1882 2009-01-04 15:38:33Z dhellmann $" import traceback import sys from pprint import pprint from traceback_example import call_function def f(): return traceback.format_stack() formatted_stack = call_function(f) pprint(formatted_stack)
#!/usr/bin/env python # encoding: utf-8 # # Copyright (c) 2008 Doug Hellmann All rights reserved. # """ """ __version__ = "$Id: traceback_extract_stack.py 1882 2009-01-04 15:38:33Z dhellmann $" import traceback import sys from pprint import pprint from traceback_example import call_function def f(): return traceback.extract_stack() stack = call_function(f) pprint(stack)