Skip to Content
Python Cookbook
book

Python Cookbook

by Alex Martelli, David Ascher
July 2002
Intermediate to advanced
608 pages
15h 46m
English
O'Reilly Media, Inc.
Content preview from Python Cookbook

Tracing Expressions and Comments in Debug Mode

Credit: Olivier Dagenais

Problem

You are coding a program that cannot use an interactive, step-by-step debugger, so you need detailed logging of state and control flow to perform debugging effectively despite this.

Solution

The extract_stack function from the traceback module is the key here, as it lets our code easily perform runtime introspection to find out about the code that called it:

import types, string, sys from traceback import * traceOutput = sys.stdout watchOutput = sys.stdout rawOutput = sys.stdout """ Should print out something like: File "trace.py", line 57, in _ _testTrace secretOfUniverse <int> = 42 """ def watch(variableName): if _ _debug_ _: stack = extract_stack( )[-2:][0] actualCall = stack[3] if actualCall is None: actualCall = "watch([unknown])" left = string.find(actualCall, '(') right = string.rfind(actualCall, ')') paramDict = {} paramDict["varName"] = string.strip( actualCall[left+1:right]) # all from '(' to ')' paramDict["varType"] = str(type(variableName))[7:-2] paramDict["value"] = repr(variableName) paramDict["methodName"] = stack[2] paramDict["lineNumber"] = stack[1] paramDict["fileName"] = stack[0] outStr = 'File "%(fileName)s", line %(lineNumber)d, in' \ ' %(methodName)s\n %(varName)s <%(varType)s>' \ ' = %(value)s\n\n' watchOutput.write(outStr % paramDict) """ Should print out something like: File "trace.py", line 64, in ? This line was executed! """ def trace(text): if _ _debug_ _: stack = extract_stack( ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Python Cookbook - Second Edition

Modern Python Cookbook - Second Edition

Steven F. Lott
Python Cookbook, 3rd Edition

Python Cookbook, 3rd Edition

David Beazley, Brian K. Jones

Publisher Resources

ISBN: 0596001673Supplemental ContentCatalog PageErrata