Skip to content

Instantly share code, notes, and snippets.

@syfun
Last active August 4, 2018 03:39
python3 asyncio correctry interrupt.
import asyncio
async def task():
while True:
print('Do something.')
await asyncio.sleep(1)
async def run(lp):
try:
await task()
except asyncio.CancelledError:
print('Cancel the future.')
except Exception as e:
print(e)
lp.stop()
loop = asyncio.get_event_loop()
future = asyncio.ensure_future(run(loop))
try:
loop.run_forever()
except KeyboardInterrupt:
future.cancel()
loop.run_until_complete(future)
finally:
loop.close()
import asyncio
async def task():
while True:
print('Do something.')
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(task())
except Exception as e:
print(e)
finally:
loop.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment