July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Olivier Dagenais
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.
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( ...