gpt4 book ai didi

尝试使用 asyncio 子进程调用 shell 命令时,Python 引发 NotImplementedError

转载 作者:行者123 更新时间:2023-12-02 01:55:20 29 4
gpt4 key购买 nike

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

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

我查看了其他分支,但都没有实现。 subprocess 模块 ( https://docs.python.org/3/library/subprocess.html ) 广为人知,并且对它的 asyncio 支持尚未完成。端点已定义,但目前无法使用。

关于尝试使用 asyncio 子进程调用 shell 命令时,Python 引发 NotImplementedError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60432219/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com