使用 paramiko 检查远程主机上是否存在路径

问题描述:

Paramiko 的 SFTPClient 显然没有 存在方法.这是我目前的实现:

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.

参见 errno 模块 用于定义所有错误代码的常量.此外,使用异常的 errno 属性比 __init__ 参数的扩展更清晰,所以我会这样做:

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:
    ...