Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python, a clean way to check if a task has finished

loop = asyncio.get_event_loop()
executor = concurrent.futures.ThreadPoolExecutor(max_workers=5)
tasks = [loop.run_in_executor(executor, self.parse_url, url) for url in urls]
await asyncio.wait(tasks, timeout=5)
for (i, task) in zip(urls, tasks):
    result = task.result() if task._state.lower() == 'finished' else []

In the code above I use the '_state' property to check if the task has indeed finished and did not timeout.

Is there a cleaner way of doing it? I don't think I'm supposed to access the '_state' property like that.

like image 715
Zaid Amir Avatar asked Mar 08 '26 21:03

Zaid Amir


1 Answers

You can use task.done() to check whether a task has finished.

Also, asyncio.wait() itself returns two sets of tasks: those that have actually finished, and those that haven't, so you can iterate only over the done set:

done, pending = await asyncio.wait(tasks, timeout=5)
for t in done:
    ...
like image 170
user4815162342 Avatar answered Mar 12 '26 08:03

user4815162342