【问题标题】:Globally override print statement python全局覆盖打印语句python
【发布时间】:2017-06-15 08:34:58
【问题描述】:

在一个相对较大的 python3 代码库中,有几个打印语句点缀在我想找到的代码中。如果 print 函数可以被覆盖,它会变得容易得多,以便它总是打印文件名和行号。示例输出:

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

在我的情况下,这尤其是一个问题,因为 python 文件被包装在二进制 blob 中,并且对它们进行 grepping 是徒劳的,但是 traceback 模块给出的文件名仍然是合理的。

对于 python2 解决方案,有这个问题/答案: How to make print() override work "globally"

【问题讨论】:

  • 注意,这是你不应该使用print 进行日志记录的一个很好的理由,而是使用实际的logging 模块。这将允许您定义完全符合您需要的处理程序和格式化程序。
  • 我完全同意,并在我自己的代码中做到这一点

标签: python python-3.x printing overriding


【解决方案1】:

在咨询了其他各种未能完全回答我的问题的 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 的所有使用,因为它只是预先挂起一个参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 2016-11-07
    • 2014-09-27
    相关资源
    最近更新 更多