如何在Python的VariantDir()环境中制作递归的Glob()?
来自问题< Use a Glob() to find files recursively in Python?>的答案;将无法使用,因为您需要使用Glob()来获取知道VariantDir()环境的文件列表.
因此,您需要类似:
import fnmatch
import os
matches = []
for root, dirnames, filenames in os.walk('src'):
for filename in fnmatch.filter(filenames, '*.c'):
matches.append(os.path.join(root, filename))
matches = Glob(matches)
这样行吗?
解决方法:
您的方法可以进行较小的调整,如下所示:
import fnmatch
import os
def RecursiveGlob(pathname)
matches = []
for root, dirnames, filenames in os.walk(pathname):
for filename in fnmatch.filter(filenames, '*.c'):
matches.append(File(os.path.join(root, filename)))
return matches
注意,我将其转换为File(),因为如果“ strings”参数为false,SCons Glob()函数将返回Nodes.
为了能够处理VariantDir等并更好地将功能与现有SCons Glob()功能集成在一起,您实际上可以将对现有Glob()函数的调用并入,如下所示:
# Notice the signature is similar to the SCons Glob() signature,
# look at scons-2.1.0/engine/SCons/Node/FS.py line 1403
def RecursiveGlob(pattern, ondisk=True, source=True, strings=False):
matches = []
# Instead of using os.getcwd() consider passing-in a path
for root, dirnames, filenames in os.walk(os.getcwd()):
cwd = Dir(root)
# Glob() returns a list, so using extend() instead of append()
# The cwd param isnt documented, (look at the code) but its
# how you tell SCons what directory to look in.
matches.extend(Glob(pattern, ondisk, source, strings, cwd))
return matches
您可以更进一步,并执行以下操作:
def MyGlob(pattern, ondisk=True, source=True, strings=False, recursive=False):
if not recursive:
return Glob(pattern, ondisk, source, strings)
matches = []
# Instead of using os.getcwd() consider passing-in a path
for root, dirnames, filenames in os.walk(os.getcwd()):
cwd = Dir(root)
# Glob() returns a list, so using extend() instead of append()
# The cwd param isnt documented, (look at the code) but its
# how you tell SCons what directory to look in.
matches.extend(Glob(pattern, ondisk, source, strings, cwd))
return matches