Created
August 1, 2016 16:17
-
-
Save vxgmichel/9132ecd7f78efc30ef0180bc79b67624 to your computer and use it in GitHub Desktop.
Non-interruptible asyncio program after PR #305
This file contains 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 background(): | |
while running: | |
await asyncio.sleep(0) | |
[x**2 for x in range(10**5)] | |
async def main(): | |
return await asyncio.sleep(20, result='hello') | |
# Schedule the background task | |
running = True | |
loop = asyncio.get_event_loop() | |
background_task = asyncio.ensure_future(background()) | |
# Run the main task | |
try: | |
result = loop.run_until_complete(main()) | |
except KeyboardInterrupt: | |
print('Interrupted!') | |
else: | |
print(result) | |
# Stop the background task | |
running = False | |
if background_task.done(): | |
background_task.exception() | |
else: | |
loop.run_until_complete(background_task) | |
loop.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment