Guest User

Untitled

a guest
Feb 19th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.53 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. import asyncio
  4.  
  5. class ArbitraryException(Exception):
  6. pass
  7.  
  8. async def consumer(p):
  9. while True:
  10. try:
  11. product = yield # unpack the sent product, consume somehow
  12. print("product was {}, okok".format(product))
  13. except ArbitraryException as e:
  14. print("cons stopping")
  15. break # jump out of consumption loop
  16.  
  17. async def producer(n):
  18. c = yield # yield to get consumer passed in
  19. for i in range(n):
  20. await c.asend(i) # produce portion of coroutine
  21. try:
  22. await c.athrow(ArbitraryException())
  23. except StopAsyncIteration:
  24. print("prod stopping")
  25.  
  26. async def main():
  27. p = producer(10) # Create coroutine object producer
  28. c = consumer(p) # Create coroutine object consumer
  29. await p.asend(None) # start producer instance
  30. await c.asend(None) # start consumer instance
  31. try:
  32. await p.asend(c) # send producer a consumer, wait for execution to return from it.
  33. except StopAsyncIteration:
  34. print("main returning")
  35.  
  36. if __name__ == '__main__':
  37. try:
  38. loop = asyncio.get_event_loop()
  39. loop.run_until_complete(main())
  40. finally:
  41. print("program exiting")
  42. loop.close()
  43.  
  44. # Sample Output:
  45. """product was 0, okok
  46. product was 1, okok
  47. product was 2, okok
  48. product was 3, okok
  49. product was 4, okok
  50. product was 5, okok
  51. product was 6, okok
  52. product was 7, okok
  53. product was 8, okok
  54. product was 9, okok
  55. cons stopping
  56. prod stopping
  57. main returning
  58. program exiting"""
Add Comment
Please, Sign In to add comment