简体   繁体   中英

Paramiko SFTP Client creates zero sized file after throwing IOError

Hi I am trying to copy a remote file in a server to a local location using Paramiko's SFTP client. Here below is the code.

    try:
        self.SFTP.get(remotepath, localpath, callback=None)
    except IOError as e:
        print "File Not Found  "+self.location

Remote location doesn't always contains the file requested so I want to print the Error message and end the process.

Unfortunately it prints the message(IOError message) but it also creates the local file with zero size.

Is this a bug or is there any other way to avoid this?

I would use: sftp.stat(remotepath)

So, in your sample code:

try:
    if self.SFTP.stat(remotepath):
        self.SFTP.get(remotepath, localpath, callback=None)
except IOError as e:
    print "File Not Found  "+self.location

SFTP - Paramiko documentation

It's expected.

Instead trying to get a file that you don't know if it exist, I suggest you either:

  • first try to find it using the Paramiko SFTP listdir command, or
  • try to get an SFTPFile object from it using Paramiko SFTP file command.
    • If it fails, the file doesn't exist.
    • If it succeeds, just close the SFTPFile object, and download the file with the get command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM