Comment passer des paramètres à plusieurs tâches asynchrones en Python

Sep 02 2020

En ce moment, j'ai un code qui ressemble à ceci:

    userinput1 = abc.....
    userinput2 = abc.....
    userinput3 = abc.....
    
    async def task1():
        do something with userinput1...
        do another thing...
    
    async def task2():
        do something with userinput2...
        do another thing...
    
    async def task3():
        do something with userinput3...
        do another thing...
    
    async def main():
        await asyncio.wait([task1() , task2(), task3()])
    
    if __name__ == '__main__':
        asyncio.get_event_loop().run_until_complete(main())

Comme vous pouvez le voir ci-dessus, j'ai 3 fonctions asynchrones qui font des choses séparées simultanément. Je me demandais s'il existe un moyen de créer facilement de nombreuses fonctions basées sur l'entrée de l'utilisateur? Ce que je veux essentiellement qu'il puisse faire, c'est ceci:

    userinput1 = abc.....
    userinput2 = abc.....
    userinput3 = abc.....
    userinput4 = abc.....
    amount_of_needed_functions = 4

Et puis une fois qu'il avait obtenu ces données, il fonctionnerait comme ce script:

    async def task1():
            do something with userinput1...
            do another thing...
        
    async def task2():
            do something with userinput2...
            do another thing...
        
    async def task3():
            do something with userinput3...
            do another thing...
    
    async def task4():
            do something with userinput4...
            do another thing...
        
    async def main():
            await asyncio.wait([task1() , task2(), task3(), task4()])
        
    if __name__ == '__main__':
            asyncio.get_event_loop().run_until_complete(main())

Donc, à peu près, cela créerait des fonctions basées sur certaines variables (telles que userinput1), puis le ferait le nombre de fois spécifié (amount_of_needed_functions), puis les exécuterait toutes simultanément. Désolé, c'est une question un peu déroutante, mais je ne sais pas trop par où commencer à faire des recherches. Merci!

Réponses

1 AvivYaniv Sep 02 2020 at 04:06

Transmettez l'entrée utilisateur en tant qu'argument à chaque tâche:

Fonction unique pour plusieurs tâches

import asyncio

async def function(user_input, input_index):
    print(f'In {input_index} function: {user_input}')


async def main():
    tasks = []
    for input_index in range(1, 4):
        user_input = input(f"Enter input #{input_index}\n")
        tasks.append(asyncio.create_task(function(user_input, input_index)))
    await asyncio.gather(*tasks)


if __name__ == '__main__':
    asyncio.run(main())

Fonctions multiples pour plusieurs tâches

Utilisez un dictionnaire pour appeler la méthode souhaitée pour chaque entrée.

import asyncio

async def function1(user_input, input_index):
    print(f'In {input_index} function1: {user_input}')

async def function2(user_input, input_index):
    print(f'In {input_index} function2: {user_input}')

async def function3(user_input, input_index):
    print(f'In {input_index} function3: {user_input}')


FUNCTION_DICTIONARY = { 1 : function1, 2 : function2, 3 : function3 }

async def main():
    tasks = []
    for input_index in range(1, 4):
        user_input = input(f"Enter input #{input_index}\n")
        tasks.append(asyncio.create_task(FUNCTION_DICTIONARY[input_index](user_input, input_index)))
    await asyncio.gather(*tasks)


if __name__ == '__main__':
    asyncio.run(main())
JosefKorbel Sep 02 2020 at 03:58

Vous pouvez essayer quelque chose comme ça si toutes les fonctions font la même chose


inputs = ['a', 'b', 'c']

async def task(input: str):
    # Do stuff / await stuff
    return input
   
async def main()
    await asyncio.wait(
        [task(arg) for arg in inputs]
    )