Функция asyncio.wait() это еще один способ вызвать множество асинхронных задач.
Она работает в нескольких режимах.
1. Самый простой - ждем завершения всех задач
async def main():
tasks = [asyncio.create_task(do_it(i)) for i in range(10)]
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.ALL_COMPLETED
)
for task in done:
try:
print(task.result())
except Exception as e:
print(e)
Очень похоже на gather, но работает не так.
▫️возвращает не результаты, а два сета с объектами Task у которых можно забрать результат через task.result() если они в списке done
▫️не гарантирует порядок результатов так как оба объекта это set
▫️не выбрасывает исключение когда оно появляется, а сохраняет его в Task. Исключение появится когда попробуете забрать резултьтат.
2. Ждем завершения первой задачи, даже если там ошибка.
async def main():
tasks = [asyncio.create_task(do_it(i)) for i in range(3)]
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.FIRST_COMPLETED
)
# в done может быть несколько задач!
for task in done:
try:
print(task.result())
except Exception as e:
print(f"Fail: {e}")
# Оставшиеся задачи в pending, как правило, нужно отменить, иначе они будут продолжать работать
for task in pending:
task.cancel()
В сете done будут таски которые успели завершится, причем как успешно так и нет.
3. До первой ошибки.
Тоже самое, но с аргументом FIRST_EXCEPTION
done, pending = await asyncio.wait(
tasks,
return_when=asyncio.FIRST_EXCEPTION
)
Функция завершается как только первая задача упадет с ошибкой.
Учтите, что в любом случае done вы можете обранужить несколько задач, как с ошибками так и успешные.
↗️ Полный листинг примеров здесь
#async
🇫🇷The presence of 4 thousand French soldiers in the Gaza war
Thomas Bourtes, a member of the #French parliament, announced that more than 4,000 French citizens are participating in the Israeli army in the war against Gaza.
La présence de 4 mille soldats français dans la guerre à Gaza
Thomas Bourtes, député français, a annoncé que plus de 4 000 citoyens français participent à l'armée israélienne dans la guerre contre Gaza.
https://t.me/YediotNewsChat
Еще одна полезная рекомендация для french learners:
https://youtube.com/playlist?list=PLycTNLUo2y2EAKEhVfxB9gYo6r0OTMgM0&si=SBoZIA4aZQhFpzMl
Очень классный подкаст, легко понять и даже есть транскрипт, если слушать на сайте
#french
Я довольно неплохо понимаю текста, которые читаю на французском и после этого фото поняла почему😆
Но я понимаю, что словарный запас надо расширять, поэтому решила, что буду больше читать. С английским было так же, больше всего слов я выучила после фокуса на чтение
#french
#Rap#French
Manau le curé et les Loups
It speaks of a priest guarding a village against a wolf pack, the priest speaks of his regrets and the things he would have liked to do in his life.
In the end, as the sun clears the night, the villagers find the priest dead, killed by the wolves as he was protecting the village.
https://youtu.be/UEpzez_H2CI
After calling the #Hijab “a symbol of women’s submission to men”, #French Interior Minister continues his #Islamophobic comments, calling the Hijab “a sign of inferiority.”
#Op_ed: #Djibouti: Pillar of stability, not a "rentier fortress" in decline
In a rebuttal to an op-ed titled "Crumbling of Rentier Fortress: Ethiopia’s Maritime Pivot, Decline of Djibouti’s Monopoly," Naguib Ali Taher, Communications Officer for the Republic of Djibouti, firmly rejects the characterization of his nation as a “crumbling rentier fortress.” He dismisses the portrayal as both “inaccurate and dismissive,” arguing that it misrepresents the geopolitical reality of the Horn of Africa.
Taher contends that Djibouti remains “an undeniable bedrock of stability” within a volatile region—a status validated by the presence of major #American, #French, #Chinese, and #Japanese military installations.
The author further brushes aside accusations of authoritarianism and regional meddling, labeling them "tabloid-style slander."
https://addisstandard.com/?p=55291
#Vocabee#Snap#amp#Learn#French
Join the Vocabee: Snap & Learn French beta on ✈️#TestFlight
🔗 Link: https://testflight.apple.com/join/tAwWnF8e
Shared by Dimitri