使用Python拥有.gitignore样式fnmatch()最简单的方法是什么。看起来,stdlib不提供匹配()函数,它将匹配路径规范与UNIX样式的路径regex匹配。
.gitignore有路径和文件,并且要列出通配符(黑色)
发布于 2012-04-06 20:22:56
如果您想使用.gitignore示例中列出的混合UNIX通配符模式,为什么不使用每个模式并在re.search中使用fnmatch.translate
import fnmatch
import re
s = '/path/eggs/foo/bar'
pattern = "eggs/*"
re.search(fnmatch.translate(pattern), s)
# <_sre.SRE_Match object at 0x10049e988>translate将通配符模式转换为re模式
隐藏的UNIX文件:
s = '/path/to/hidden/.file'
isHiddenFile = re.search(fnmatch.translate('.*'), s)
if not isHiddenFile:
# do something with it发布于 2014-02-28 09:05:46
有一个名为路径规范的库,它实现了完整的.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'])https://stackoverflow.com/questions/10048667
复制相似问题