在Windows异步上与python并行运行进程

问题描述 投票:0回答:1

我有一个代码只能在带有asyncio的Linux上运行,但是我需要它在Windows上运行,我对多处理的了解很少,在Windows上运行的方式是什么?我看到在Windows上运行asyncio有一个局限性:https://docs.python.org/3/library/asyncio-platforms.html#asyncio-windows-subprocess

我的代码:

import sys
import asyncio


scriptspy = [
    'scrp1.py',
    'scrp2.py',
    'scrp3.py',
    'scrp4.py',
    'scrp5.py',
    'scrp6.py',
    'scrp7.py',
    'scrp8.py',
    'scrp9.py',
    'scrp10.py',
    'scrp11.py',
    'scrp12.py',
]

async def main():
    tarefas_rodando = set()
    while scriptspy:
        # start up to 6 scripts
        while len(tarefas_rodando) < 6 and scriptspy:
            script = scriptspy.pop()
            p = await asyncio.create_subprocess_exec(sys.executable, script)
            tarefa = asyncio.create_task(p.wait())
            tarefas_rodando.add(tarefa)
        # wait for one of the scripts to end
        tarefas_rodando, finalizadas = await asyncio.wait(tarefas_rodando, return_when=asyncio.FIRST_COMPLETED)
    # finished, wait for the rest to finish
    await asyncio.wait(tarefas_rodando, return_when=asyncio.ALL_COMPLETED)


asyncio.run(main())

此代码在Linux上运行良好,但在Windows上运行不佳。我需要在Windows上运行它。 https://docs.python.org/3/library/asyncio-platforms.html#asyncio-windows-subprocess

在Windows中运行的异常:

Traceback (most recent call last):
   File "scripts.py", line 53, in <module>
    asyncio.run(main())
   File "C:\Python\Python37\lib\asyncio\runners.py", line 43, in run
    return loop.run_until_complete(main)
   File "C:\Python\Python37\lib\asyncio\base_events.py", line 584, in run_until_complete
    return future.result()
   File "scripts.py", line 44, in main
    p = await asyncio.create_subprocess_exec(sys.executable, script)
   File "C:\Python\Python37\lib\asyncio\subprocess.py", line 217, in create_subprocess_exec
    stderr=stderr, **kwds)
   File "C:\Python\Python37\lib\asyncio\base_events.py", line 1533, in subprocess_exec
    bufsize, **kwargs)
   File "C:\Python\Python37\lib\asyncio\base_events.py", line 463, in
_make_subprocess_transport
    raise NotImplementedError NotImplementedError
python python-3.x multithreading python-asyncio
1个回答
0
投票

根据the documentation,要在Windows上运行子流程,您需要切换到proactor事件循环:

asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy())
© www.soinside.com 2019 - 2024. All rights reserved.