跳转到主要内容

虚拟文件系统的通配符匹配。

项目描述

virtual-glob

PyPI

远程/虚拟文件系统的通配符匹配。

动机

通配符匹配是许多程序中的常见操作,但并不总是需要使用本地文件系统,例如 glob.globpathlib.Path.glob。此包提供了一种遍历远程/虚拟文件系统的方法。

除了未维护的 python-glob2 之外,我没有找到其他提供此功能的Python包,所以我制作了自己的包!

使用方法

安装包

pip install virtual-glob

使用 glob 函数,它可以接受 pathlib.Path 实例、提供的 InMemoryPath 类或实现以下 VirtualPath 的任何其他类

from virtual_glob import glob, InMemoryPath

fs = InMemoryPath.from_list(["a/b/c/my1.txt", "e/f/g/my2.txt", "x/y/z/other.txt"])
matches = {p.path for p in glob(fs, "**/my[0-9].txt")}
assert matches == {"a/b/c/my1.txt", "e/f/g/my2.txt"}

glob 还接受关键字参数

  • follow_symlinks:是否在迭代目录时跟随符号链接(默认:False
  • depth_first:是否按深度优先顺序迭代目录,或按广度优先(默认:True

请参阅测试用例以获取更多示例。

虚拟文件系统

文件系统必须可以通过单个类访问,直接模仿 pathlib.Path,以下协议

class VirtualPath(Protocol):
    @property
    def name(self) -> str:
        """Return the name of this path."""

    def is_dir(self) -> bool:
        """Return True if this path is a directory."""

    def is_symlink(self) -> bool:
        """Return True if this path is a symbolic link."""

    def iterdir(self: PathType) -> Iterable[PathType]:
        """Iterate over the contents of this directory."""

    def joinpath(self: PathType, *parts: str) -> PathType:
        """Join this path with the given parts."""

    def exists(self) -> bool:
        """Return True if this path exists."""

规则

  • 模式必须以POSIX格式,即 / 是路径分隔符。
  • 模式必须是相对的,即它们不能以 / 开头。
  • 模式是区分大小写的。
  • 带有尾随 / 的模式仅匹配目录。
  • ** 匹配零个或多个目录,它必须是路径段中的唯一项。
  • * 匹配零个或多个字符,但不能是 /
  • ? 匹配恰好一个字符,但不能是 /
  • [...] 匹配集合中的一个字符,但不能是 /
  • [!...] 匹配集合中不存在的字符,但不能是 /

设计

尽可能减少对底层文件系统的调用,尤其是对于iterdir。例如,当模式中不包含“魔法”字符时,尝试“短路”。

项目详情


下载文件

下载您平台对应的文件。如果您不确定选择哪个,请了解更多关于安装包的信息。

源分发

virtual_glob-0.2.0.tar.gz (10.8 kB 查看哈希)

上传时间

构建分发

virtual_glob-0.2.0-py3-none-any.whl (6.7 kB 查看哈希)

上传时间 Python 3

由以下支持