如何在asyncio中使用subprocess模块​​限制并发进程数python

How to limit the number of concurrent processes using subprocess module in asyncio python

import asyncio
import asyncio.subprocess
args="blah blah argument "     
create=asyncio.create_subprocess_shell(args,stdout=asyncio.subprocess.PIPE)
proc = await create
output= await proc.stdout.read( )

这是我的服务器代码的一部分,它从 clients.Now 获得了 1000 次并行点击 我应该如何将服务器创建的最大子进程数限制为 运行 参数等等。因为这是代码使用了我的 cpu 的 100%。我需要在 smae cpu

上部署其他服务器

asyncio.Semaphore 是一种限制同时作业的内部计数器的方法:

sem = asyncio.Semaphore(10)

async def do_job(args):
    async with sem:  # Don't run more than 10 simultaneous jobs below
        proc = await asyncio.create_subprocess_shell(args, stdout=PIPE)
        output = await proc.stdout.read()
        return output

请注意,您应该确保作业数量的增加不会比您实际完成它们的速度快得多。否则,您将需要比这更复杂的东西。