为什么打印时会添加额外的时间戳?

2024-04-27 00:07:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用下面的代码将时间戳添加到打印中。但奇怪的是,为什么它在消息周围添加了两个时间戳。你知道吗

old_f = sys.stdout

class CFout:
    def write(self, x):
        old_f.write("%s %s " % (datetime.now().strftime("%d/%m/%Y %H:%M:%S:%f"), x))

sys.stdout = CFout()

当我print True。它的输出如下。你知道吗

15/05/2015 05:42:02:121945 True 15/05/2015 05:42:02:121977

True之前和之后,有两个时间戳。
为什么会这样?我只想在True之前添加时间戳。你知道吗


Tags: 代码selftrue消息datetimedefstdoutsys
2条回答

基于@Bakuriu answer,我使用下面的代码来实现我的目标,因为我相信我不会在打印消息中使用“\n”。:). 如果其他人也感兴趣,我会在这里发帖。你知道吗

old_f = sys.stdout
class CFout:
    def write(self, x):
        if x.find("\n") == -1:
            old_f.write("%s %s " % (datetime.now().strftime("%d/%m/%Y %H:%M:%S:%f"), x))
        else:
            old_f.write(x)
sys.stdout = CFout()

这是因为print语句或函数对write执行两个调用,一个用于打印消息('True'),另一个用于结束换行符或空格。你知道吗

您可以使用如下脚本看到这一点:

import sys
from datetime import datetime

args = []

class CFout:
    def write(self, x):
        args.append(x)
        sys.__stdout__.write("%s %s " % (datetime.now().strftime("%d/%m/%Y %H:%M:%S:%f"), x))


sys.stdout = CFout()

print True
print False
print 1, 2, 3

sys.stdout = sys.__stdout__
print 'arguments were'
print args

调用结果:

$python2 prnt.py 
15/05/2015 08:07:03:171182 True 15/05/2015 08:07:03:171392 
 15/05/2015 08:07:03:171452 False 15/05/2015 08:07:03:171477 
 15/05/2015 08:07:03:171517 1 15/05/2015 08:07:03:171540   15/05/2015 08:07:03:171561 2 15/05/2015 08:07:03:171581   15/05/2015 08:07:03:171601 3 15/05/2015 08:07:03:171621 
 arguments were
['True', '\n', 'False', '\n', '1', ' ', '2', ' ', '3', '\n']

注:

  • 'True''\n'是执行print True时执行的两个调用的参数。你知道吗
  • 'False''\n'是执行print False时执行的两个调用的参数
  • '1'' ''2'' ''3''\n'是执行print 1,2,3时执行的参数。你知道吗

另一种方法是使用异常:

>>> print 1, 1/0, 2
1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

注意:即使1/0引发了一个异常,1仍然被打印。python所做的是将每一部分内容打印出来,对其求值,然后调用write。之后它调用write(' ')来打印逗号引起的空格,最后计算1/0,这将导致异常。你知道吗

以同样的方式print True首先计算True,然后调用write(str(True)),最后调用write('\n')来添加最后的换行符。你知道吗

如果您想适当地为消息附加一个时间戳,那么应该改用^{}模块。你知道吗

相关问题 更多 >