Skip to content

Commit

Permalink
Fix example code for Docker events (#70)
Browse files Browse the repository at this point in the history
1.  The event_task must be cancelled in any case. Cancelling a task
    never raises an exception even if the task is already done.
2.  Check that the event_task has not been cancelled and get its result.
    If the task has been cancelled properly, nothing will happen. If the
    task had an exception, the exception will be raised and displayed
    properly to the terminal.
3.  Add another level of try...except because even if the Docker
    exception is raised by the task, we still need to close the loop.

Fixes #34
  • Loading branch information
cecton authored and Christian Barra committed Jul 20, 2017
1 parent 7053b84 commit d9a7871
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions examples/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ async def demo(docker):

while True:
event = await subscriber.get()
if event is None:
break
print(f"event: {event!r}")

# Demonstrate simple event-driven container mgmt.
Expand All @@ -50,14 +52,18 @@ async def demo(docker):

if __name__ == '__main__':
loop = asyncio.get_event_loop()
docker = Docker()
try:
docker = Docker()
# start a monitoring task.
event_task = loop.create_task(docker.events.run())
# do our stuffs.
loop.run_until_complete(demo(docker))
# explicitly stop monitoring.
event_task.cancel()
try:
# do our stuffs.
loop.run_until_complete(demo(docker))
finally:
# explicitly stop monitoring.
event_task.cancel()
loop.run_until_complete(docker.close())
if not event_task.cancelled():
event_task.result() # NOTE: maybe raise an exception
finally:
loop.run_until_complete(docker.close())
loop.close()

0 comments on commit d9a7871

Please sign in to comment.