Python 在尝试使用 asyncio 子进程调用 shell 命令时引发 NotImplementedError [重复]

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

我是 Python 编程新手。我想并行调用几个 shell 命令并将它们的结果累积在单个数组中,就像 javascript

promise.all()
方法一样。

我在Python中有以下代码:

import asyncio
import os


commands = [
    'netstat -n | findstr 55601',
    'dir | findstr portMonitoring.py',
    'ssh 10.6.100.192 netstat'
]

async def job(cmd):
    # await asyncio.sleep(1)
    # return "HEE"
    # return os.popen(cmd).read()
    process = await asyncio.create_subprocess_exec(
        cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
    )

    return await process.communicate()



async def main():
    jobs = [job(cmd) for cmd in commands]
    done, pending = await asyncio.wait(jobs, return_when=asyncio.FIRST_COMPLETED)
    folders = []
    [folders.append(d.result()) for d in done]
    print("RESULT:", folders)

asyncio.run(main())

我收到以下错误:

Traceback (most recent call last):
  File "test.py", line 16, in job
    cmd, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
  File "C:\DEV\Python3.7.4\lib\asyncio\subprocess.py", line 217, in create_subprocess_exec
    stderr=stderr, **kwds)
  File "C:\DEV\Python3.7.4\lib\asyncio\base_events.py", line 1529, in subprocess_exec
    bufsize, **kwargs)
  File "C:\DEV\Python3.7.4\lib\asyncio\base_events.py", line 458, in _make_subprocess_transport
    raise NotImplementedError
NotImplementedError
python windows subprocess python-asyncio
3个回答
1
投票

https://github.com/python/cpython/blob/master/Lib/asyncio/base_events.py#L493

这是一个计划中的功能,但尚未实现。将来可以使用,但当前版本不支持。

我查看了其他分支,但都没有实现。 subprocess 模块 (https://docs.python.org/3/library/subprocess.html) 已广为人知,并且

asyncio
对它的支持尚未完成。端点已定义,但它们目前不可用。


0
投票

文档中有解释:

Python 3.7

https://docs.python.org/3.7/library/asyncio-platforms.html#asyncio-windows-subprocess

Windows 上的 SelectorEventLoop 不支持子进程。在 Windows 上, 应使用 ProactorEventLoop 来代替:

import asyncio

asyncio.set_event_loop_policy(
    asyncio.WindowsProactorEventLoopPolicy())

asyncio.run(your_code())

Python 3.8

Windows 上的默认事件循环现在是 ProactorEventLoop。


0
投票

如果您使用的是 Jupyter,因此无法切换到 ProactorEventLoop,请查看:https://stackoverflow.com/a/76981596/1951947

© www.soinside.com 2019 - 2024. All rights reserved.