In a relatively large python3 codebase there are several print statments that are dotted through the code that I would like to find. It would make be significantly easier if the print function could be overridden so that it always prints the filename and line number. Example output:
>>> print("Some Message")
filename:line_number
Some Message
In my case, this is particularly an issue because the python files are wrapped up inside binary blobs, and grepping for them is an exercise in futility, but the filenames given by the traceback module are still sensible.
For a python2 solution, there is this question/answer: How to make print() override work "globally"
After consulting various other stackoverflow questions that didn't quite answer my question, the following code emerged:
import traceback
def dprint(*args):
'''Pre-pends the filename and linenumber to the print
statement'''
stack = traceback.extract_stack()[:-1]
last = stack[-1]
# Handle different versions of the traceback module
if hasattr(last, 'filename'):
out_str = "{}:{}\n".format(last.filename, last.lineno)
else:
out_str = "{}:{}\n".format(last[0], last[1])
# Prepend the filename and linenumber
__builtins__['oldprint'](out_str, *args)
if 'oldprint' not in __builtins__:
__builtins__['oldprint'] = __builtins__['print']
__builtins__['print'] = dprint
It should handle all uses of print as it just pre-pends an argument.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With