使用pyram slow中的paramiko打开远程文件

Rin*_*nks 3 python file

我正在使用paramiko在python中打开一个远程sftp文件.使用paramiko返回的文件对象,我逐行读取文件并处理信息.与使用来自os的python内置方法'open'相比,这看起来真的很慢.以下是我用来获取文件对象的代码.

使用paramiko(慢2倍) -

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(myHost,myPort,myUser,myPassword)
sftp = client.open_sftp()
fileObject = sftp.file(fullFilePath,'rb')
Run Code Online (Sandbox Code Playgroud)

使用os -

import os
fileObject = open(fullFilePath,'rb')
Run Code Online (Sandbox Code Playgroud)

我错过了什么吗?有没有办法使paramiko fileobject读取方法与使用os fileobject的方法一样快?

谢谢!!

Joh*_*yon 6

您的问题可能是由文件作为远程对象引起的.您已经在服务器上打开它并且一次请求一行 - 因为它不是本地的,每个请求所需的时间比文件位于您的硬盘上要长得多.最好的选择可能是使用Paramiko's将文件首先复制到本地位置SFTP get.

完成后,您可以使用本地位置打开文件os.open.


aro*_*man 5

我遇到了同样的问题,由于安全原因,我无法在本地复制文件,我通过使用预取和 bytesIO 的组合解决了这个问题:

def fetch_file_as_bytesIO(sftp, path):
    """
    Using the sftp client it retrieves the file on the given path by using pre fetching.
    :param sftp: the sftp client
    :param path: path of the file to retrieve
    :return: bytesIO with the file content
    """
    with sftp.file(path, mode='rb') as file:
        file_size = file.stat().st_size
        file.prefetch(file_size)
        file.set_pipelined()
        return io.BytesIO(file.read(file_size))
Run Code Online (Sandbox Code Playgroud)