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

2024-10-05 13:19:15 发布

您现在位置:Python中文网/ 问答频道 /正文

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

有更好的办法吗?检查异常消息中的子字符串相当难看,而且可能不可靠。


Tags: path方法paramikoforreturnobjectosdef
3条回答

没有为SFTP定义“exists”方法(不仅仅是paramiko),因此您的方法很好。

我觉得检查一下错误有点干净:

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

有关定义所有这些错误代码的常量,请参见^{} module。此外,使用异常的errno属性比使用__init__参数的扩展更清楚一些,因此我将执行以下操作:

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

Paramiko字面上提升了FileNotFoundError

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

相关问题 更多 >

    热门问题