gpt4 book ai didi

python - 全局覆盖打印语句python

转载 作者:行者123 更新时间:2023-12-01 02:52:41 27 4
gpt4 key购买 nike

在一个相对较大的 python3 代码库中,有几个打印语句点缀在我想要查找的代码中。如果可以覆盖打印函数,使其始终打印文件名和行号,那么事情会变得更加容易。示例输出:

>>> print("Some Message")
filename:line_number
Some Message

就我而言,这尤其是一个问题,因为 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

它应该处理 print 的所有使用,因为它只是预先挂起一个参数。

关于python - 全局覆盖打印语句python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44562633/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com