Last active
August 4, 2018 03:39
python3 asyncio correctry interrupt.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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