[PEAK] Twisted Deferred as EventSources & Generators
Chad Rosenberg
chad at idrankwhat.net
Wed Jan 28 15:27:15 EST 2004
I've run into the problem where I need to wait for the results of a
Deferred while in _run of an AbstractCommand. I noticed the following
doesn't work:
eventLoop = binding.Obtain(IEventSource)
def doSomeWork(self):
d = self.somePBCall()
result = self.eventLoop.runUntil(d)
The above gives me:
("Can't adapt", <Deferred at 0x1038af8>, <class
'peak.events.interfaces.IEventSource'>)
So I took a look at the adapter DeferredAsEventSource and noticed that
it only adapts a Deferred to ITaskSwitch, and not IEventSource (as the
name would seem to imply). So, I suppose my question is: how does one
obtain the results of a deferred outside a generator/event.threaded
function?
Alternatively, as workaround I suppose that I could do something like
the following?:
def doSomeWork(self):
t = self.getPBData()
self.eventLoop.runUntil(t)
def getPBData(self)
d = self.somePBCall()
yield d; results = events.resume()
getPBData = events.threaded(getPBData)
But, even if I were to do the above I'm not quite sure how I could pass
the results of getPBData back up to doSomeWork. I guess I could pass
in a event source Value, but this is turning into a lot of extra code
just to get the value of a deferred.
I was wondering, if something like the following wouldn't be useful:
def doSomeWork(self):
d = self.getPBData()
yield d; result = events.resume()
if result == 'something bad':
raise Exception, 'bad'
yield events.exit(result)
doSomeWork = events.waitFor(doSomeWork)
def _run(self):
try:
print self.doSomeWork()
except Exception, reason:
print reason
Where event.waitFor would wrap a Thread and provide a blocking call.
That way, as far as the caller is concerned, doSomeWork looks like any
other blocking method with a return value, and doSomeWork gets to use
events nice and cleanly. Or is there already a way to do this that I
have missed?
Thanks,
Chad
More information about the PEAK
mailing list