Check whether a path exists on a remote host using paramiko

一个人想着一个人 提交于 2019-12-21 07:30:20

问题


Paramiko's SFTPClient apparently does not have an exists method. This is my current implementation:

def rexists(sftp, path):
    """os.path.exists for paramiko's SCP object
    """
    try:
        sftp.stat(path)
    except IOError, e:
        if 'No such file' in str(e):
            return False
        raise
    else:
        return True

Is there a better way to do this? Checking for substring in Exception messages is pretty ugly and can be unreliable.


回答1:


See the errno module for constants defining all those error codes. Also, it's a bit clearer to use the errno attribute of the exception than the expansion of the __init__ args, so I'd do this:

except IOError, e: # or "as" if you're using Python 3.0
  if e.errno == errno.ENOENT:
    ...



回答2:


There is no "exists" method defined for SFTP (not just paramiko), so your method is fine.

I think checking the errno is a little cleaner:

def rexists(sftp, path):
    """os.path.exists for paramiko's SCP object
    """
    try:
        sftp.stat(path)
    except IOError, e:
        if e[0] == 2:
            return False
        raise
    else:
        return True



回答3:


Paramiko literally raises FileNotFoundError

def sftp_exists(sftp, path):
    try:
        sftp.stat(path)
        return True
    except FileNotFoundError:
        return False


来源:https://stackoverflow.com/questions/850749/check-whether-a-path-exists-on-a-remote-host-using-paramiko

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!