#!/usr/bin/python import sys, time class TimeStamper(object): def __init__(self, timeFormat = None): self.old_stdout = None #Set the time format for output self.__time_format = timeFormat or "%Y-%m-%d %H:%M:%S" def enable(self): if self.old_stdout == None: #get a copy of stdout self.old_stdout = sys.stdout #place ourself in sys.stdout to intercept #calls to sys.stdout.write() sys.stdout = self #initialize softspace for print's benefit. #(optional, I think) self.__softspace = 0 #initialize show timestamp for us self.__show_timestamp = 1 def disable(self): if self.old_stdout is not None: #put the REAL stdout back in sys.stdout sys.stdout = self.old_stdout self.old_stdout = None def write(self, output): if self.__show_timestamp: self.__show_timestamp = 0 tt = time.localtime(time.time()) timeString = '%s: ' % time.strftime(self.__time_format, tt) self.old_stdout.write(timeString) if output == '\n': self.__show_timestamp = 1 self.old_stdout.write("%s" % output) if __name__ == "__main__": ts = TimeStamper() ts.enable() print 'test', "apple", ['list', 'of','items'], \ "\nMultiple lines get one timestamp,\nunless seperated by a ", \ "\n", "solitary newline." print print ts.disable() print 'test', "apple", ['list', 'of','items'], \ "\nMultiple lines get one timestamp,\nunless seperated by a ", \ "\n", "solitary newline." print print