.gitignore style fnmatch()

Mik*_*maa 9 python regex filenames gitignore fnmatch

使用Python的.gitignore样式fnmatch()最简单的方法是什么?看起来stdlib不提供match()函数,该函数将路径规范与UNIX样式路径正则表达式匹配.

.gitignore具有通配符的路径和文件(黑色)列出

Dav*_*ser 16

现在有一个名为pathspec的库,它实现了完整的.gitignore规范,包括类似的东西**/*.py; 该文件没有详细描述的选项,但是他说,这是git的兼容,以及代码处理它们.

>>> import pathspec
>>> spec_src = '**/*.pyc'
>>> spec = pathspec.PathSpec.from_lines(pathspec.patterns.GitWildMatchPattern,, spec_src.splitlines())
>>> set(spec.match_files({"test.py", "test.pyc", "deeper/file.pyc", "even/deeper/file.pyc"}))
set(['test.pyc', 'even/deeper/file.pyc', 'deeper/file.pyc'])
>>> set(spec.match_tree("pathspec/"))
set(['__init__.pyc', 'gitignore.pyc', 'util.pyc', 'pattern.pyc', 'tests/__init__.pyc', 'tests/test_gitignore.pyc', 'compat.pyc', 'pathspec.pyc'])
Run Code Online (Sandbox Code Playgroud)


jdi*_*jdi 7

如果你想使用混合UNIX通配符模式作为你的.gitignore例如上市,为什么不采取每个图案,并使用fnmatch.translatere.search

import fnmatch
import re

s = '/path/eggs/foo/bar'
pattern = "eggs/*"

re.search(fnmatch.translate(pattern), s)
# <_sre.SRE_Match object at 0x10049e988>
Run Code Online (Sandbox Code Playgroud)

translate 将通配符模式转换为重新模式

隐藏的UNIX文件:

s = '/path/to/hidden/.file'
isHiddenFile = re.search(fnmatch.translate('.*'), s)
if not isHiddenFile:
    # do something with it
Run Code Online (Sandbox Code Playgroud)