【问题标题】:Reading file opened with Python Paramiko SFTPClient.open method is slow读取用 Python Paramiko SFTPClient.open 方法打开的文件很慢
【发布时间】:2019-10-17 13:35:15
【问题描述】:

我正在尝试远程读取 netcdf 文件。
我使用 Paramiko 包来读取我的文件,如下所示:

import paramiko
from netCDF4 import Dataset

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(hostname=’hostname’, username=’usrname’, password=’mypassword’)

sftp_client = client.open_sftp()
ncfile = sftp_client.open('mynetCDFfile')
b_ncfile = ncfile.read()    # ****

nc = Dataset('test.nc', memory=b_ncfile)

但是ncfile.read()的运行速度非常慢。

所以我的问题是:有没有其他方法可以远程读取 netcdf 文件,或者有什么方法可以加速paramiko.sftp_file.SFTPFile.read()

【问题讨论】:

    标签: python ssh sftp paramiko netcdf


    【解决方案1】:

    调用SFTPFile.prefetch 应该会提高读取速度:

    ncfile = sftp_client.open('mynetCDFfile')
    ncfile.prefetch()
    b_ncfile = ncfile.read()
    

    另一个选项是启用读取缓冲,使用SFTPClient.openbufsize 参数:

    ncfile = sftp_client.open('mynetCDFfile', bufsize=32768)
    b_ncfile = ncfile.read()
    

    32768SFTPFile.MAX_REQUEST_SIZE 的值)

    同样适用于写入/上传:
    Writing to a file on SFTP server opened using pysftp "open" method is slow


    另一种选择是明确指定要读取的数据量(它使BufferedFile.read 采用更有效的代码路径):

    ncfile = sftp_client.open('mynetCDFfile')
    b_ncfile = ncfile.read(ncfile.stat().st_size)
    

    如果这些都不起作用,您可以将整个文件下载到内存中:
    Use pdfplumber and Paramiko to read a PDF file from an SFTP server


    强制性警告:不要以这种方式使用AutoAddPolicy - 这样做会失去对MITM attacks 的保护。有关正确的解决方案,请参阅Paramiko "Unknown Server"

    【讨论】:

    • 非常有帮助!谢谢
    猜你喜欢
    • 2015-09-19
    • 2021-02-17
    • 2010-11-19
    • 1970-01-01
    • 2022-08-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多