使用 paramiko 检查远程主机上是否存在路径 [英] Check whether a path exists on a remote host using paramiko
本文介绍了使用 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:
...
这篇关于使用 paramiko 检查远程主机上是否存在路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文