Skip to main content
 首页 » 编程设计

python之使用 pathlib 的 rglob 处理缺少权限/组

2024年10月25日12zhwl

我正在尝试使用 pathlib 以递归方式 glob 和/或查找文件。由于我无法控制的文件系统管理不善,文件权限和组到处都是。

当我缺少 rglob 试图进入的目录的权限和组成员资格时,就会出现问题。 Rglob 抛出一个 KeyError,然后是一个 PermissionError,最后完全停止。我看不出有什么办法可以优雅地从中恢复并继续 globbing。

我想要的行为是让 rglob 跳过我没有权限的目录,并生成它看到/有权限的所有内容的列表。在这种特殊情况下,全有或全无的性质不会让我走得太远,因为我几乎可以保证在每次运行时对某个目录或另一个目录具有错误的权限。

更多细节:

Python: 3.4.1 从 linux 源代码编译

我正在寻找的文件系统:自动挂载的 nfs 共享

如何重现:

mkdir /tmp/path_test && cd /tmp/path_test && mkdir dir1 dir2 dir2/dir3 && touch dir1/file1 dir1/file2 dir2/file1 dir2/file2 dir2/dir3/file1 
su 
chmod 700 dir2/dir3/ 
chown root:root dir2/dir3/ 
exit 

python3.4.1

from pathlib import Path 
p = Path('/tmp/path_test') 
for x in p.rglob('*') : print(x) 

请您参考如下方法:

起初我尝试像这样手动迭代 rglob() 的结果:

from pathlib import Path 
p = Path('/tmp/path_test') 
files = p.rglob('*') 
while True: 
    try: 
        f = next(files) 
    except (KeyError, PermissionError): 
        continue 
    except StopIteration: 
        break 
    print(f) 

但它看起来像 next(files) 在第一个 PermissionError 之后抛出一个 StopIteration,所以在那之后我没有得到任何文件.

您最好使用 os.walk() .