python 使用 paramiko 检查远程主机上是否存在路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/850749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check whether a path exists on a remote host using paramiko
提问by Sridhar Ratnakumar
Paramiko's SFTPClientapparently does not have an exists
method. This is my current implementation:
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
Is there a better way to do this? Checking for substring in Exception messages is pretty ugly and can be unreliable.
有一个更好的方法吗?检查异常消息中的子字符串非常难看,而且可能不可靠。
回答by Matt Good
See the errno
modulefor 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:
...
回答by JimB
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
回答by jslay
Paramiko literally raises FileNotFoundError
Paramiko 字面上提出 FileNotFoundError
def sftp_exists(sftp, path):
try:
sftp.stat(path)
return True
except FileNotFoundError:
return False