import sys import asyncio @asyncio.coroutine def long_sleep_subprocess(): args = [sys.executable, '-c', 'import time; time.sleep(20)'] proc = yield from asyncio.create_subprocess_exec(*args) try: yield from proc.wait() except asyncio.CancelledError: proc.terminate() @asyncio.coroutine def fast_sleep(): yield from asyncio.sleep(.500) long_sleep_task.cancel() @asyncio.coroutine def cancel_after_first_completed(tasks): while tasks: done, pending = yield from asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED) for task in done: tasks.remove(task) for task in pending: task.cancel() loop = asyncio.get_event_loop() loop.set_debug(True) long_sleep_task = asyncio.Task(long_sleep_subprocess()) tasks = [asyncio.Task(fast_sleep()), long_sleep_task, asyncio.Task(asyncio.sleep(10)), # No exception when this task is not in the list. ] main_task = asyncio.Task(cancel_after_first_completed(tasks)) loop.run_until_complete(main_task) loop.close()