Skip to content

Instantly share code, notes, and snippets.

@tcwalther
Last active November 3, 2016 11:52
Show Gist options
  • Save tcwalther/98ce82ca7837dd49c904b87e74ce4474 to your computer and use it in GitHub Desktop.
Save tcwalther/98ce82ca7837dd49c904b87e74ce4474 to your computer and use it in GitHub Desktop.
import asyncio
loop = asyncio.get_event_loop()
async def f1():
for _ in range(10):
await asyncio.sleep(1)
print("task 1 is done")
async def f2():
for _ in range(3):
await asyncio.sleep(0.5)
print("task 2 will raise exception")
raise RuntimeError("artificial exception")
def main_wait():
a = asyncio.ensure_future(f1())
b = asyncio.ensure_future(f2())
done, pending = loop.run_until_complete(
asyncio.wait([a, b], return_when=asyncio.FIRST_EXCEPTION)
)
print("done", done)
print("pending", pending)
try:
for task in done:
if task.exception():
raise task.exception()
finally:
for task in pending:
task.cancel()
try:
loop.run_until_complete(task)
except asyncio.CancelledError:
pass
if __name__ == "__main__":
main_wait()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment