Paramiko's SFTPClient apparently does not have an exists
method. This is my current implementation:
Paramiko的SFTPClient显然没有存在方法。这是我目前的实施:
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.
有一个更好的方法吗?在异常消息中检查子字符串非常难看,并且可能不可靠。
2 个解决方案
#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:
有关定义所有这些错误代码的常量,请参阅errno模块。此外,使用异常的errno属性比__init__ args的扩展更清楚,所以我这样做:
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.
没有为SFTP(不仅仅是paramiko)定义“存在”方法,所以你的方法很好。
I think checking the errno is a little cleaner:
我认为检查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
#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:
有关定义所有这些错误代码的常量,请参阅errno模块。此外,使用异常的errno属性比__init__ args的扩展更清楚,所以我这样做:
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.
没有为SFTP(不仅仅是paramiko)定义“存在”方法,所以你的方法很好。
I think checking the errno is a little cleaner:
我认为检查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