首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如果任何目录没有读取权限,pysftp.Connection.walktree()就会失败

如果任何目录没有读取权限,pysftp.Connection.walktree()就会失败
EN

Stack Overflow用户
提问于 2021-07-15 19:30:16
回答 1查看 83关注 0票数 1

我正在使用pysftp连接,使用walktree()方法列出所有文件,如下所示

代码语言:javascript
运行
复制
with pysftp.Connection(domain, username=USER,
                       password=PWD, port=port,
                       cnopts=cnopts) as sftp:

    # call back method to list the files for the directory found in walktree
    def dir_found_list_files(path):
        if path:
            files = sftp.listdir_attr(path)
            for file in files:
                if 'r' in file.longname[:4]:
                    filelist.append(path+'/'+file.filename)

    # call back method when file found in walktree
    def file_found(path):
        pass

    # call back method when unknown found in walktree
    def unknown_file(path):
        pass

    # sftp walk tree to list files
    sftp.walktree("/", file_found, dir_found_list_files, unknown_file, recurse=True)

这部分运行得很好。但是,当任何文件夹没有读取权限时,walktree方法将引发权限异常。如何忽略拒绝访问文件夹并继续使用可访问文件夹的walktree

EN

Stack Overflow用户

回答已采纳

发布于 2021-07-15 20:05:19

你不能。Connection.walktree不允许这样的自定义。

但是这个方法非常简单,请查看its source code。只需复制代码并根据需要进行自定义即可。类似于以下内容(未经测试):

代码语言:javascript
运行
复制
def robust_walktree(sftp, remotepath, fcallback, dcallback, ucallback, recurse=True)
    try:
        entries = sftp.listdir(remotepath)
    except IOError as e:
        if e.errno != errno.EACCES:
            raise
        else
            entries = []

    for entry in entries:
        pathname = posixpath.join(remotepath, entry)
        mode = sftp.stat(pathname).st_mode
        if S_ISDIR(mode):
            # It's a directory, call the dcallback function
            dcallback(pathname)
            if recurse:
                # now, recurse into it
                robust_walktree(sftp, pathname, fcallback, dcallback, ucallback)
        elif S_ISREG(mode):
            # It's a file, call the fcallback function
            fcallback(pathname)
        else:
            # Unknown file type
            ucallback(pathname)
票数 1
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68392997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档