【问题标题】:Check whether a path exists on a remote host using paramiko使用 paramiko 检查远程主机上是否存在路径
【发布时间】:2010-10-25 10:40:28
【问题描述】:

Paramiko 的 SFTPClient 显然没有 exists 方法。这是我目前的实现:

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

有没有更好的方法来做到这一点?检查异常消息中的子字符串非常难看,而且可能不可靠。

【问题讨论】:

    标签: python ssh scp paramiko


    【解决方案1】:

    请参阅errno module 了解定义所有这些错误代码的常量。此外,使用异常的errno 属性比使用__init__ 参数的扩展更清晰,所以我会这样做:

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

    【讨论】:

    【解决方案2】:

    Paramiko 确实提高了FileNotFoundError

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

    【讨论】:

    • 实际上是FileNotFoundError(来自内置异常类)ETA:排队编辑此答案以更改它
    【解决方案3】:

    没有为 SFTP 定义“存在”方法(不仅仅是 paramiko),所以你的方法很好。

    我认为检查 errno 会更干净一些:

    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
    

    【讨论】:

      猜你喜欢
      • 2016-07-29
      • 2012-10-02
      • 1970-01-01
      • 2020-06-15
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多