代码之家  ›  专栏  ›  技术社区  ›  Aravind

如何在asyncio python中使用子进程模块限制并发进程的数量

  •  1
  • Aravind  · 技术社区  · 7 年前
    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( )
    

    1 回复  |  直到 7 年前
        1
  •  3
  •   Ogaga Uzoh    7 年前

    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
    

    注意,你应该确保工作数量的增加不会比你实际做的快得多。否则,你将需要比这更复杂的东西。