July 2002
Intermediate to advanced
608 pages
15h 46m
English
Credit: Luther Blissett
You have a program that needs to run on both Windows and Unix, and you want to trace and/or log output (typically for debugging) simply and flexibly.
You can rebind sys.stdout so that
print statements will be logged and use a
sophisticated class for the rebinding to ensure that auxiliary
functionality such as automatic timestamping is done in a
platform-independent way:
# tweakable timestamper callable import time class Timestamper: msg_format = "%y%m%d %H%M%S", time.localtime, "%s: %s" def _ _call_ _(self, msg): tfmt, tfun, gfmt = self.msg_format return gfmt%(time.strftime(tfmt,tfun( )), msg) # Bind name 'syslogger' to an output-to-system-log function (if any) try: import syslog except ImportError: try: import servicemanager except ImportError: # no logging available -- maybe OutputDebugString? try: import win32api except ImportError: # none, give up and use a dummy function def syslogger(msg): pass else: timestamp = Timestamper( ) def syslogger(msg): win32api.OutputDebugString(timestamp(msg)) else: syslogger = servicemanager.LogInfoMsg else: syslogger = syslog.syslog class FunctionFilelikeWrapper: def _ _init_ _(self, func): self.func = func def write(self, msg): self.func(msg) syslogfile = FunctionFilelikeWrapper(syslogger) class TeeFilelikeWrapper: def _ _init_ _(self, *files): self.files = files def write(self, msg): for f in self.files: f.write(msg) class FlushingWrapper: def _ _init_ _(self, *files): ...
Read now
Unlock full access