簡體   English   中英

嘗試異步調用 shell 命令時,Python 錯誤引發 NotImplementedError

[英]Python error raise NotImplementedError when trying to call shell command async

我是 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

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

這是一個計划中的功能,但尚未實施。 它會在未來工作,但當前版本不支持它。

我查看了其他分支,但都沒有實現。 asyncio模塊 ( https://docs.python.org/3/library/subprocess.html ) 廣為人知,對它的asyncio支持尚未完成。 端點已定義,但截至目前無法使用。

它在文檔中解釋:

蟒蛇 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())

蟒蛇 3.8

Windows 上的默認事件循環現在是 ProactorEventLoop。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM