Skip to content

Commit b607be5

Browse files
henryiiijonathanslenders
authored andcommitted
Cleaner tasks and exceptions
Removed need for explicit exception handling (which could be done at the `run_until_complete` stage instead of using `return_exceptions`)
1 parent 65a59e0 commit b607be5

File tree

1 file changed

+6
-7
lines changed

1 file changed

+6
-7
lines changed

examples/asyncio-prompt.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,7 @@ async def print_counter():
3131
while True:
3232
print('Counter: %i' % i)
3333
i += 1
34-
try:
35-
await asyncio.sleep(3)
36-
except asyncio.CancelledError:
37-
return
34+
await asyncio.sleep(3)
3835

3936

4037
async def interactive_shell():
@@ -64,12 +61,14 @@ async def interactive_shell():
6461

6562

6663
def main():
67-
counter = loop.create_task(print_counter())
6864
shell = loop.create_task(interactive_shell())
65+
66+
# This gathers all the async calls, so they can be cancelled at once
67+
tasks = asyncio.gather(print_counter(), return_exceptions=True)
6968

7069
loop.run_until_complete(shell)
71-
counter.cancel()
72-
loop.run_until_complete(counter)
70+
tasks.cancel()
71+
loop.run_until_complete(tasks)
7372
print('Qutting event loop. Bye.')
7473
loop.close()
7574

0 commit comments

Comments
 (0)