Функция 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
@JPG2PDFBot
Qué puede hacer este bot?
Envíame fotos JPG o BMP como medios de Telegram.
Cuando hayas terminado,
use /done e intentaré generar un archivo PDF usando las imágenes enviadas en ese orden.
Idioma: Inglés
(visto en @BotsGram_cu)
#pdf, #convert, #photo
@HearForYou_Bot
Qué puede hacer este bot?
Este bot puede Convertir mensajes de audio de Telegram y WhatsApp a texto
Idioma: Inglés
(visto en @BotsGram_cu)
#whatsapp, #telegram, #speachtotext, #convert, #audio
@textUtilsBot
Qué puede hacer este bot?
Bot en línea para transformaciones de texto. Puede ayudarlo a traducir texto del lenguaje humano a código binario o hexadecimal, cadena base64 y viceversa.
Idioma: Inglés
(visto en @BotsGram_cu)
#inline, #utility, #base64, #binary, #hexadecimal, #convert
@NewStickerOptimizerBot
Qué puede hacer este bot?
Simplemente envíeme una imagen o pegatina, y la convertiré en un archivo png y la optimizaré para que su tamaño sea más pequeño o igual a 350Kb, para que pueda agregarlo a un paquete de pegatinas usando el bot @stickers.
Idioma: Inglés
(visto en @BotsGram_cu)
#sticker, #png, #image, #picture, #optimize, #pack, #create, #tool, #convert
#typescript#bun#conversion#convert#converter#document_conversion#elysia#file_conversion#file_converter#hacktoberfest#pdf_converter#self_hosted#tailwindcss#typescript
ConvertX is a self-hosted online file converter that supports over a thousand file formats, including images, videos, documents, e-books, and 3D assets. It lets you convert multiple files at once, offers password protection, and supports multiple user accounts for privacy. You can run it easily using Docker, making it simple to set up on your own server. This means your files stay private since conversions happen locally without sending data to external servers. It uses powerful open-source tools like FFmpeg and ImageMagick, giving you a versatile and secure way to handle all your file conversion needs in one place[1][2].
https://github.com/C4illin/ConvertX
@TelescopyBot
Qué puede hacer este bot?
Con este bot puedes convertir videos cuadrados a videos redondos
Idioma: Inglés, Ruso
(visto en @BotsGram.cu)
#telescope, #video_\message, #convert, #mp4, #gif, #media, #questions, #command, #round, #message, #video