我发现我真的想要内联扩展。这并不像我想象的那么容易。
无论如何,这就是我所拥有的。只进行了简单的测试,但让我知道它适合你的地方,我会编辑它。
def expand_pathglobs(pathparts, basepaths=None):
# Logic:
# 0. Argue with a Path(str).parts and optional ['/start','/dirs'].
# 1. for each basepath, expand out pathparts[0] into "expandedpaths"
# 2. If there are no more pathparts, expandedpaths is the result.
# 3. Otherwise, recurse with expandedpaths and the remaining pathparts.
# eg: expand_pathglobs('/tmp/a*/b*')
# --> /tmp/a1/b1
# --> /tmp/a2/b2
if isinstance(pathparts, str) or isinstance(pathparts, Path):
pathparts = Path(pathparts).parts
if basepaths == None:
return expand_pathglobs(pathparts[1:], [Path(pathparts[0])])
else:
assert pathparts[0] != '/'
expandedpaths = []
for p in basepaths:
assert isinstance(p, Path)
globs = p.glob(pathparts[0])
for g in globs:
expandedpaths.append(g)
if len(pathparts) > 1:
return expand_pathglobs(pathparts[1:], expandedpaths)
return expandedpaths