sdf*_*off 4 python printing overriding python-3.x
在一个相对较大的 python3 代码库中,有几个打印语句点缀在我想找到的代码中。如果可以覆盖打印函数,使其始终打印文件名和行号,那么事情会变得更加容易。输出示例:
>>> print("Some Message")
filename:line_number
Some Message
Run Code Online (Sandbox Code Playgroud)
就我而言,这尤其是一个问题,因为 python 文件被包装在二进制 blob 中,对它们进行 grep 是徒劳的,但回溯模块给出的文件名仍然是合理的。
对于 python2 解决方案,有这个问题/答案: How to make print() override work "globally"
在咨询了其他各种未能完全回答我的问题的 stackoverflow 问题后,出现了以下代码:
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
Run Code Online (Sandbox Code Playgroud)
它应该处理 print 的所有使用,因为它只是预先挂起一个参数。
| 归档时间: |
|
| 查看次数: |
2429 次 |
| 最近记录: |