how to display clock?, plus musings on the Nerd factor in Python
John Benson
jsbenson at bensonsystems.com
Sun Dec 7 14:49:07 EST 2003
Hi, here's some code I use to update a clock and some other stuff. You can
probably use the Tkinter mainloop() instead of the twisted reactor and
after(milliseconddelay, callback, args, ...) instead of the twisted
callLater routine if the twisted framework isn't being used.
You don't have to wrap the after()/callLater() stuff in a class like I did,
but it facilitates setup of various independent periodic events.
Attention veteran pythonistas: I'm a newcomer to python, so criticism of the
following code will be welcomed and assiduously studied:
...
from twisted.internet import reactor, tksupport
...
class Pulsar:
def __init__(self, reactor, requiredparamslist=[], kwdparamsdict={},
pulseinterval=1.0, maxpulses=None,
callbeforefirstdelay=True):
# begin create attributes
self.reactor = reactor # from twisted.internet import reactor
self.requiredparamslist = requiredparamslist
self.kwdparamsdict = kwdparamsdict
self.pulseinterval = float(pulseinterval)
if maxpulses == None:
self.maxpulses = None
else:
self.maxpulses = int(maxpulses)
self.pulses = 0
# end create attributes
# start and/or schedule repetition
if self.maxpulses == None or self.pulses < self.maxpulses:
self.reactor.callLater(0, self.beforefirst)
if (self.maxpulses == None) or (self.pulses < self.maxpulses):
if callbeforefirstdelay:
self.IDelayedCall = self.reactor.callLater(0,
self.functionwrapper)
else:
self.IDelayedCall =
self.reactor.callLater(self.pulseinterval, self.functionwrapper)
else:
# looks like there was just 1 repetition
self.afterlast()
else:
# no repetitions!
self.afterlast()
def afterlast(self):
pass
def beforefirst(self):
pass
def cancel(self):
self.IDelayedCall.cancel()
self.maxpulses = self.pulses # paranoia, in case the cancel suffered
from a race condition
self.cancelled()
def cancelled(self):
pass
def functionwrapper(self):
# assume that if we have been called/scheduled, we need to run the
function:
self.pulses += 1
apply(self.function, self.requiredparamslist, self.kwdparamsdict)
if (self.maxpulses == None) or (self.pulses < self.maxpulses):
self.IDelayedCall = self.reactor.callLater(self.pulseinterval,
self.functionwrapper)
else:
# that's all, folks: no more repetitions
self.afterlast()
def function(self):
raise NotImplementedError # must be overridden
class Heartbeat(Pulsar):
def afterlast(self):
log("Heartbeat: that's all, folks!")
reactor.stop()
def beforefirst(self):
log("XYZ Emulator entering service at %s" % time.asctime())
...
def cancelled(self):
log("Heartbeat: I was cancelled!", fei.ERROR)
self.afterlast()
def function(self):
fei.timenow.set(time.asctime())
log("Heartbeat %d " % self.pulses)
...
heartbeat = Heartbeat(reactor, pulseinterval=1)
reactor.listenTCP(5600, FalconFactory())
reactor.run()
...
More information about the Python-list
mailing list