Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- import asyncio
- class ArbitraryException(Exception):
- pass
- async def consumer(p):
- while True:
- try:
- product = yield # unpack the sent product, consume somehow
- print("product was {}, okok".format(product))
- except ArbitraryException as e:
- print("cons stopping")
- break # jump out of consumption loop
- async def producer(n):
- c = yield # yield to get consumer passed in
- for i in range(n):
- await c.asend(i) # produce portion of coroutine
- try:
- await c.athrow(ArbitraryException())
- except StopAsyncIteration:
- print("prod stopping")
- async def main():
- p = producer(10) # Create coroutine object producer
- c = consumer(p) # Create coroutine object consumer
- await p.asend(None) # start producer instance
- await c.asend(None) # start consumer instance
- try:
- await p.asend(c) # send producer a consumer, wait for execution to return from it.
- except StopAsyncIteration:
- print("main returning")
- if __name__ == '__main__':
- try:
- loop = asyncio.get_event_loop()
- loop.run_until_complete(main())
- finally:
- print("program exiting")
- loop.close()
- # Sample Output:
- """product was 0, okok
- product was 1, okok
- product was 2, okok
- product was 3, okok
- product was 4, okok
- product was 5, okok
- product was 6, okok
- product was 7, okok
- product was 8, okok
- product was 9, okok
- cons stopping
- prod stopping
- main returning
- program exiting"""
Add Comment
Please, Sign In to add comment