简体   繁体   English

Python中如何给多个异步任务传递参数

[英]How to pass parameters to multiple async tasks in Python

Right now I have some code that looks like this:现在我有一些代码看起来像这样:

    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())

As you can see above, I have 3 async functions that do separate things simultaneously.正如您在上面看到的,我有 3 个异步函数,它们同时执行不同的操作。 I was wondering if theres any way to easily create many functions based off of user input?我想知道是否有任何方法可以根据用户输入轻松创建许多功能? Essentially what I want to have it be able to do is this:基本上我想让它能够做的是:

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

And then once it had gotten that data it would run like this 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())

So pretty much it would make functions based off of certain veriables (such as userinput1) and then do this however many times specified (amount_of_needed_functions) and then run all of these simultaneously.几乎它会根据某些可验证的(例如 userinput1)创建函数,然后按照指定的次数执行此操作(amount_of_needed_functions),然后同时运行所有这些。 Sorry this is a bit of confusing question but I'm quite lost as where to start researching this.抱歉,这是一个有点令人困惑的问题,但我不知道从哪里开始研究这个问题。 Thanks!谢谢!

Pass user input as an argument to each task:将用户输入作为参数传递给每个任务:

Single Function For Multiple Tasks单个 Function 用于多个任务

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())

Multiple Functions For Multiple Tasks多项任务的多项功能

Use a dictionary to invoke your desired method for each input.使用字典为每个输入调用所需的方法。

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())

You can try something like this if all the functions do the same thing如果所有功能都做同样的事情,你可以尝试这样的事情


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]
    )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM