创建协程列表并收集它们

Create list of co-routines and gather them

我正在为 python 中的 asyncio 苦苦挣扎。 我希望能够做这样的事情:

import asyncio

async def create_task(task):
    proc = asyncio.create_subprocess_shell(
        task.code,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE)
    stdout, stderr = await proc.communicate()
    if(stdout):
        print (stdout)
    if(stderr):
        print (stderr)

async def main():
    tasks_to_do = *a list of Task objects*
    tasks_to_run = []
    for task in tasks_to_do:
        task_to_run = create_task(task)
        tasks_to_run.append(task_to_run)
        
    L = await asyncio.gather(*tasks_to_run)
    print(L)


asyncio.run(main())

所以:

  1. 根据一系列不同的任务填充协程列表
  2. 运行所有协程等待他们

其中每个任务都是一个子流程。

这可能吗?

提前致谢

你的问题几乎和你写的一样有效。我做了一些小改动以打印每一步所花费的时间。关于同时发出 10 个 ping 的预期结果

import asyncio
import time

start = time.perf_counter()
first = 0

async def create_task(task):
    global start, first
    proc = await asyncio.create_subprocess_shell(
        task,
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE)
    stdout, stderr = await proc.communicate()
    if(stdout):
        #  print (stdout)
        print(first, time.perf_counter() - start)
        first += 1
    if(stderr):
        # print (stderr)
        pass

async def main():
    global start, first
    tasks_to_do = [f"ping 192.0.2.2 -n 1 -w {x}000" for x in range(10)]
    tasks_to_run = []
    for task in tasks_to_do:
        task_to_run = create_task(task)
        tasks_to_run.append(task_to_run)
    L = await asyncio.gather(*tasks_to_run)
    print(time.perf_counter() - start)
    print(L)

asyncio.run(main())

输出是...

0 0.04503160000000006
1 0.6204607000000001
2 1.6138199000000002
3 2.6133104
4 3.620059
5 4.617139099999999
6 5.6125441
7 6.617551199999999
8 7.613781399999999
9 8.6230318
8.623507199999999
[None, None, None, None, None, None, None, None, None, None]