在Python打印中添加日期时间戳 [英] Adding a datetime stamp to Python print

查看:2593
本文介绍了在Python打印中添加日期时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调试我所依赖的大型库的行为,它通过其许多源文件使用了散布(没有太多的)调试打印语句。麻烦的是,大多数(不是全部)这些调试打印语句不包含日期/时间戳,因此很难将应用程序级别的故障与库代码本身中的故障相关联。

I am trying to debug the behaviour of a large library I depend on, which uses a scattering (no make that plethora) of debug print statements through its many source files. Trouble is, most if not all of these debug print statements do not contain a date/time stamp so it is hard to associate failures at the application level with failures within the library code itself.

而不是修改所有在我看到的故障中涉及到的所有调试打印的源代码,我认为这可能是内置的Python打印函数临时,以便所有输出都带有时间戳。

Rather than modifying the source code for all the debug prints suspected to be involved in the failure I am seeing, I thought it may be possible to monkey patch the built-in Python print "function" temporarily, in order that all output is prefixed with a timestamp.

由于内置打印不是一个功能在Python 2.6环境中我正在使用,我不知道这是否可能。如果任何人已经完成了这一工作,或者使用Python中的另一个钩子实现了类似的结果,那么我将不胜感激您的建议,或者更好地解决这个问题的代码。

Since the built-in print is not a function in the Python 2.6 environment I am working with, I don't know if this is possible. If anyone has done this or achieved a similar result using another hook into Python then I would be grateful for your advice, or even better the code for a solution to this problem.

推荐答案

因为你不能覆盖写入函数 - 只有一个简单的猴子补丁可能看起来像这样(将时间戳记附加到每个打印行):

As you can’t override the write function (it's read-only) a simple monkey-patch could look like this (appending the timestamp to every printed line):

old_f = sys.stdout
class F:
    def write(self, x):
        old_f.write(x.replace("\n", " [%s]\n" % str(datetime.now())))
sys.stdout = F()

将如下所示:

>>> print "foo"
foo [2011-02-03 09:31:05.226899]

这篇关于在Python打印中添加日期时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆