python - Why does this add an extra timestamp when printing? -
i use below code add timestamp print. strange why add 2 timestamp around message.
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() when print true. output below.
15/05/2015 05:42:02:121945 true 15/05/2015 05:42:02:121977 before , after true, there 2 timestamp.
why this? want add timestamp before true.
it's due fact print statement or function performs two calls write, 1 print message ('true') , 1 ending newline or space.
you can see using script following:
import sys 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 called results in:
$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 ['true', '\n', 'false', '\n', '1', ' ', '2', ' ', '3', '\n'] note:
'true','\n'arguments 2 calls performed when doingprint true.'false','\n'arguments 2 calls performed when doingprint false'1',' ','2',' ','3','\n'arguments performed when doingprint 1,2,3.
an other way of seeing using exceptions:
>>> print 1, 1/0, 2 1 traceback (most recent call last): file "<stdin>", line 1, in <module> zerodivisionerror: integer division or modulo 0 note: 1 still printed though 1/0 raised exception. python doing taking each single portion of stuff print, evaluating , calling write. afterwards calls write(' ') print space due comma , evaluates 1/0 results in exception.
in same way print true first evaluates true, calls write(str(true)) , calls write('\n') add final newline.
if want propoerly attach timestamp messages should use logging module instead.
Comments
Post a Comment