new to twisted and just trying some deferred stuff out. I have the following code that makes up a list of 100 deferred calls - each waiting a random time and returning a value. That list the prints the results and finally terminates the reactor.
However, I'm pretty sure the way I'm stopping the reactor is probably... not great.
__author__ = 'Charlie'
from twisted.internet import defer, reactor
import random
def getDummyData(x):
"""returns a deferred object that will have a value in some random seconds
sets up a callLater on the reactor to trgger the callback of d"""
d = defer.Deferred()
pause = random.randint(1,10)
reactor.callLater(pause, d.callback, (x, pause))
return d
def printData(result):
"""prints whatever is passed to it"""
print result
def main():
"""makes a collection of deffered calls and then fires them. Stops reactor at end"""
deferred_calls = [getDummyData(r) for r in range(0,100)]
d = defer.gatherResults(deferred_calls, consumeErrors = True)
d.addCallback(printData)
# this additional callback on d stops the reacor
# it fires after all the delayed callbacks have printed their values
# the lambda ignored: ractor.stop() is required as callback takes a function
# that takes a parameter.
d.addCallback(lambda ignored: reactor.stop())
# start the reactor.
reactor.run()
if __name__ == "__main__":
main()
I'm assuming that by adding a callback:
d.addCallback(lambda ignored: reactor.stop())
to the gathered results actually adds that callback on all the deferred items?
if so then there is probably a more elegant / correct way to do it?
Cheers!