Where Python retrieves the <filename> trace record field from
Each trace element has the following format:
File "<filename>", line xxx, in <module>
line
I'm interested in changing the filename field (to something custom) for certain modules. Is it possible? I've tried modifying a member of __file__
a module object, but that doesn't seem to be used when python creates a trace stack.
source to share
You can use a module inspect
to get the file path of many modules. eg
>>> inspect.getabsfile(traceback)
'/usr/local/Cellar/python3/3.4.2_1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/traceback.py'
Knowing that the trace comes from traceback.print_stack () , we can look at the definition print_stack()
:
279 def print_stack(f=None, limit=None, file=None):
280 """Print a stack trace from its invocation point.
281
282 The optional 'f' argument can be used to specify an alternate
283 stack frame at which to start. The optional 'limit' and 'file'
284 arguments have the same meaning as for print_exception().
285 """
286 print_list(extract_stack(_get_stack(f), limit=limit), file=file)
With "where is it defined?" I'll save you the hassle of making function calls and suggest looking at format_exception and related examples . Without knowing specifically what you want to do with the tracing, I would suggest looking at the jinja2 source as it distorts the tracing quite a bit.