如何解决AsyncSSH SFTP示例似乎按顺序而不是异步下载文件
我从https://asyncssh.readthedocs.io/en/latest/#sftp-client网站复制了示例代码,并对其进行了少许更改以适合我的要求。
我能够连接到SFTP站点并从“ / Exports”文件夹下载文件,但是似乎文件是一次下载一个,而不是一次下载多个文件。
我的代码:
import asyncio
import asyncssh
import sys
async def run_client():
async with asyncssh.connect(host=host,username=username,password=password,port=port_no,known_hosts=None) as conn:
async with conn.start_sftp_client() as sftp:
await sftp.get(
remotepaths='/Exports',localpath=r'Path on my local machine',preserve=True,recurse=True,max_requests=128
)
try:
asyncio.get_event_loop().run_until_complete(run_client())
except (OSError,asyncssh.Error) as exc:
sys.exit('SFTP operation failed: ' + str(exc))
我需要下载9000个文件,大多数文件为1KB。我绝对可以看到文件正在一个接一个地下载。知道问题可能是什么吗?
解决方法
这里有一个异步下载文件的解决方案。
import asyncio
import asyncssh
async def download_file(sftp,file: str,localdir: str):
await sftp.get(file,localpath=f"{localdir}/{file}")
async def run_client():
async with asyncssh.connect(
"host",username="username",password="password"
) as conn:
async with conn.start_sftp_client() as sftp:
files = await sftp.glob("/Exports/*")
tasks = (download_file(sftp,file,localdir="/") for file in files)
await asyncio.gather(*tasks)
asyncio.run(run_client())
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。