coop.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #!/usr/bin/env python
  2. # https://twistedmatrix.com/documents/16.2.0/core/howto/defer.html
  3. from twisted.internet import reactor, defer
  4. from twisted.internet.task import cooperate, coiterate
  5. from twisted.internet.defer import gatherResults
  6. from os.path import basename
  7. from pprint import pprint
  8. LONG = 15
  9. def work_some(filename):
  10. base = basename(filename)
  11. with open(filename) as fp:
  12. for line in fp:
  13. if 'Sector' in line:
  14. print("{0:15} : {1}".format(base, line.strip()))
  15. yield
  16. def work_done(value):
  17. print("Job done:", value)
  18. # cooperate(work_some("../logs/proxy.log"))
  19. # cooperate(work_some("../logs/proxy.log.2019_11_30"))
  20. d1 = coiterate(work_some("../logs/proxy.log"))
  21. # There's no way this way to tell work_done what file is done.
  22. # d.addCallback(work_done)
  23. d1.addCallback(lambda ignore: work_done('proxy.log'))
  24. d2 = coiterate(work_some("../logs/proxy.log.2019_11_30"))
  25. # d.addCallback(work_done)
  26. d2.addCallback(lambda ignore: work_done('proxy.log.2019_11_30'))
  27. # Gather the results, stop the reactor when they are all done.
  28. gr = gatherResults([d1, d2])
  29. gr.addCallback(lambda ignore: reactor.stop())
  30. # Not needed, we stop when we need to. ;)
  31. # print("Stop the reactor in", LONG, "seconds...")
  32. # reactor.callLater(LONG, reactor.stop)
  33. print("starting the reactor")
  34. reactor.run()
  35. print("Reactor has been safely shutdown. :P")