在 VariantDir() 环境中使用 Glob() 在 Python 中递归查找文件? [英] Use a Glob() in VariantDir() einvironment to find files recursively in Python?
问题描述
如何在 Python 的 VariantDir()
环境中实现递归 Glob()
?
How can one make recursive Glob()
in a VariantDir()
environment in Python?
问题的答案 <使用 Glob() 在 Python 中递归查找文件?> 将不起作用,因为您需要使用 Glob()
来获取知道 VariantDir()
环境.
The answer from the question <Use a Glob() to find files recursively in Python?> will not work, because you need use Glob()
to get a list of files that is aware of VariantDir()
environment.
所以你需要这样的东西:
So you need something like:
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)
这行得通吗?
推荐答案
您的方法只需稍作调整,如下所示:
Your approach would work with a minor tweak as follows:
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() 函数将返回节点.
Notice that I converted it to a File(), since the SCons Glob() function returns Nodes if the "strings" parameter is false.
为了能够处理 VariantDir 等并将该功能与现有的 SCons Glob() 功能更好地集成,您实际上可以合并对现有 Glob() 函数的调用,如下所示:
To be able to handle the VariantDir, etc and to better integrate the functionality with the existing SCons Glob() functionality, you could actually incorporate a call to the existing Glob() function, like this:
# 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
您可以更进一步并执行以下操作:
You could take it one step further and do the following:
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
这篇关于在 VariantDir() 环境中使用 Glob() 在 Python 中递归查找文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!