读取用 Python Paramiko SFTPClient.open 方法打开的文件很慢 [英] Reading file opened with Python Paramiko SFTPClient.open method is slow
问题描述
我正在尝试远程读取 netcdf 文件.
我使用 Paramiko 包来读取我的文件,如下所示:
I am trying to remote read a netcdf file.
I used Paramiko package to read my file, like this:
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()
的运行速度非常慢.
But the run speed of ncfile.read()
is VERY SLOW.
所以我的问题是:有没有其他方法可以远程读取 netcdf 文件,或者有什么方法可以加快 paramiko.sftp_file.SFTPFile.read()
的速度?
So my question is: Is there any alternative way to read a netcdf file remotely, or is there any approach to speed up paramiko.sftp_file.SFTPFile.read()
?
推荐答案
调用 SFTPFile.prefetch
应该会提高读取速度:
Calling SFTPFile.prefetch
should increase the read speed:
ncfile = sftp_client.open('mynetCDFfile')
ncfile.prefetch()
b_ncfile = ncfile.read()
<小时>
另一个选项是使用SFTPClient.open
:
Another option is enabling read buffering, using bufsize
parameter of SFTPClient.open
:
ncfile = sftp_client.open('mynetCDFfile', bufsize=32768)
b_ncfile = ncfile.read()
(32768
是 SFTPFile.MAX_REQUEST_SIZE
的值)
同样适用于写入/上传:
写入使用 pysftp open"打开的 SFTP 服务器上的文件方法很慢.
Similarly for writes/uploads:
Writing to a file on SFTP server opened using pysftp "open" method is slow.
另一种选择是明确指定要读取的数据量(它使 BufferedFile.read
采取更高效的代码路径):
Yet another option is to explicitly specify the amount of data to read (it makes BufferedFile.read
take a more efficient code path):
ncfile = sftp_client.open('mynetCDFfile')
b_ncfile = ncfile.read(ncfile.stat().st_size)
<小时>
如果这些都不起作用,您可以将整个文件下载到内存中:
使用 pdfplumber 和 Paramiko 从 SFTP 服务器读取 PDF 文件
强制性警告:请勿以这种方式使用 AutoAddPolicy
- 您将失去对 MITM 攻击 这样做.如需正确的解决方案,请参阅Paramiko未知服务器".
Obligatory warning: Do not use AutoAddPolicy
this way – You are losing a protection against MITM attacks by doing so. For a correct solution, see Paramiko "Unknown Server".
这篇关于读取用 Python Paramiko SFTPClient.open 方法打开的文件很慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!