Python源码示例:fnmatch.fnmatch()
示例1
def _get_measures_by_name(resources, metric_wildcards, operations,
start, stop, granularity, needed_overlap, fill,
details):
references = []
for r in resources:
references.extend([
processor.MetricReference(m, agg, r, wildcard)
for wildcard, agg in metric_wildcards
for m in r.metrics if fnmatch.fnmatch(m.name, wildcard)
])
if not references:
raise indexer.NoSuchMetric(set((m for (m, a) in metric_wildcards)))
response = {
"measures": get_measures_or_abort(
references, operations, start, stop, granularity,
needed_overlap, fill)
}
if details:
response["references"] = set((r.resource for r in references))
return response
示例2
def match(path: Path, pattern_list: Iterable) -> bool:
"""
Check if a Path matches to one of the patterns
Internally fnmatch is used.
See https://docs.python.org/3/library/fnmatch.html for details.
Arguments:
path (Path): Path to check if it matches to one of the patterns
pattern_list (iterable): Iterable (e.g tuple or list) of patterns to
match against the path
Returns:
Boolean: True if path matches a pattern of the list
"""
for pattern in pattern_list:
if fnmatch.fnmatch(str(path), pattern):
return True
return False
示例3
def load_data(folder):
images_sat = [img for img in os.listdir(os.path.join(folder, "sat_img")) if fnmatch.fnmatch(img, "*.tif*")]
images_map = [img for img in os.listdir(os.path.join(folder, "map")) if fnmatch.fnmatch(img, "*.tif*")]
assert(len(images_sat) == len(images_map))
images_sat.sort()
images_map.sort()
# images are 1500 by 1500 pixels each
data = np.zeros((len(images_sat), 3, 1500, 1500), dtype=np.uint8)
target = np.zeros((len(images_sat), 1, 1500, 1500), dtype=np.uint8)
ctr = 0
for sat_im, map_im in zip(images_sat, images_map):
data[ctr] = plt.imread(os.path.join(folder, "sat_img", sat_im)).transpose((2, 0, 1))
# target has values 0 and 255. make that 0 and 1
target[ctr, 0] = plt.imread(os.path.join(folder, "map", map_im))/255
ctr += 1
return data, target
示例4
def fnmatch(self, pattern):
"""return true if the basename/fullname matches the glob-'pattern'.
valid pattern characters::
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
If the pattern contains a path-separator then the full path
is used for pattern matching and a '*' is prepended to the
pattern.
if the pattern doesn't contain a path-separator the pattern
is only matched against the basename.
"""
return FNMatcher(pattern)(self)
示例5
def __call__(self, path):
pattern = self.pattern
if (pattern.find(path.sep) == -1 and
iswin32 and
pattern.find(posixpath.sep) != -1):
# Running on Windows, the pattern has no Windows path separators,
# and the pattern has one or more Posix path separators. Replace
# the Posix path separators with the Windows path separator.
pattern = pattern.replace(posixpath.sep, path.sep)
if pattern.find(path.sep) == -1:
name = path.basename
else:
name = str(path) # path.strpath # XXX svn?
if not os.path.isabs(pattern):
pattern = '*' + path.sep + pattern
return fnmatch.fnmatch(name, pattern)
示例6
def _get_source(self):
if Version(self.version) == "3.4.0":
filename = os.path.basename(self.conan_data["sources"][self.version]["url"])
tools.download(filename=filename, **self.conan_data["sources"][self.version])
with tarfile.TarFile.open(filename, 'r:*') as tarredgzippedFile:
# NOTE: In fruit v3.4.0, The archive file contains the file names
# build and BUILD in the extras/bazel_root/third_party/fruit directory.
# Extraction fails on a case-insensitive file system due to file
# name conflicts.
# Exclude build as a workaround.
exclude_pattern = "%s/extras/bazel_root/third_party/fruit/build" % (self._extracted_dir,)
members = list(filter(lambda m: not fnmatch(m.name, exclude_pattern),
tarredgzippedFile.getmembers()))
tarredgzippedFile.extractall(".", members=members)
else:
tools.get(**self.conan_data["sources"][self.version])
示例7
def _archive_dir(self):
# the archive expands to a directory named expected-[COMMIT SHA1];
# we'd like to put this under a stable name
expected_dirs = [
de for de in os.scandir(self.source_folder)
if de.is_dir() and fnmatch(de.name, "expected-*")
]
return expected_dirs[0].name
示例8
def _ancestor_target(self):
if "CONAN_OPENSSL_CONFIGURATION" in os.environ:
return os.environ["CONAN_OPENSSL_CONFIGURATION"]
query = "%s-%s-%s" % (self.settings.os, self.settings.arch, self.settings.compiler)
ancestor = next((self._targets[i] for i in self._targets if fnmatch.fnmatch(query, i)), None)
if not ancestor:
raise ConanInvalidConfiguration("unsupported configuration: %s %s %s, "
"please open an issue: "
"https://github.com/conan-io/conan-center-index/issues. "
"alternatively, set the CONAN_OPENSSL_CONFIGURATION environment variable "
"into your conan profile "
"(list of configurations can be found by running './Configure --help')." %
(self.settings.os,
self.settings.arch,
self.settings.compiler))
return ancestor
示例9
def expect(self, cat, messagepattern="*", invert=False):
__tracebackhide__ = True
if not messagepattern.startswith("*"):
messagepattern = "*{}".format(messagepattern)
while self._index < len(self.instance.reported_lines):
try:
call = self.getnext(cat)
except LookupError:
break
for lmsg in call[1:]:
lmsg = str(lmsg).replace("\n", " ")
if fnmatch(lmsg, messagepattern):
if invert:
raise AssertionError(
"found {}({!r}), didn't expect it".format(cat, messagepattern),
)
return
if not invert:
raise AssertionError(
"looking for {}({!r}), no reports found at >={:d} in {!r}".format(
cat, messagepattern, self._index + 1, self.instance.reported_lines,
),
)
示例10
def fnmatch(filename, patterns, default=True):
# type: (str, List[str], bool) -> bool
"""Wrap :func:`fnmatch.fnmatch` to add some functionality.
:param str filename:
Name of the file we're trying to match.
:param list patterns:
Patterns we're using to try to match the filename.
:param bool default:
The default value if patterns is empty
:returns:
True if a pattern matches the filename, False if it doesn't.
``default`` if patterns is empty.
"""
if not patterns:
return default
return any(_fnmatch.fnmatch(filename, pattern) for pattern in patterns)
示例11
def should_skip(filename, config, path='/'):
"""Returns True if the file should be skipped based on the passed in settings."""
for skip_path in config['skip']:
if posixpath.abspath(posixpath.join(path, filename)) == posixpath.abspath(skip_path.replace('\\', '/')):
return True
position = os.path.split(filename)
while position[1]:
if position[1] in config['skip']:
return True
position = os.path.split(position[0])
for glob in config['skip_glob']:
if fnmatch.fnmatch(filename, glob):
return True
return False
示例12
def test_fnmatch(self):
""" Test the matching done by fnmatch. """
matrix = [
["pagure", "*", True],
["ns/pagure", "*", True],
["forks/user/ns/pagure", "*", True],
["forks/user/pagure", "*", True],
["pagure", "rpms/*", False],
["rpms/pagure", "rpms/*", True],
["forks/user/pagure", "rpms/*", False],
["forks/user/pagure", "rpms/*", False],
["pagure", "pagure", True],
["rpms/pagure", "pagure", False],
["forks/user/pagure", "pagure", False],
["forks/user/pagure", "pagure", False],
["pagure", "pag*", True],
["rpms/pagure", "pag*", False],
["forks/user/pagure", "pag*", False],
["forks/user/pagure", "pag*", False],
]
for row in matrix:
self.assertEqual(fnmatch.fnmatch(row[0], row[1]), row[2])
示例13
def read_train_and_test_data_from_path(path):
only_files = [f for f in listdir(path) if (isfile(join(path, f)))]
train_files = [f for f in only_files if fnmatch.fnmatch(f, '*_train.tsv')]
data_names = ["_".join(f.split("_")[:-1]) for f in train_files]
data_table = {}
data_table_no_entities = {}
for name in data_names:
train_data, train_labels = read_data_from_file(join(path, name + "_train.tsv"))
test_data, test_labels = read_data_from_file(join(path, name + "_test.tsv"))
is_multiclass = name.find('multiclass') > -1
# without entities as well:
train_data_no_entities, indices_to_remove = remove_entities_from_text(train_data)
train_labels_no_entities = train_labels
test_data_no_entities, indices_to_remove = remove_entities_from_text(test_data)
test_labels_no_entities = test_labels
data_table[name] = TrainTestData(train_data, train_labels, test_data, test_labels, is_multiclass)
data_table_no_entities[name] = TrainTestData(train_data_no_entities, train_labels_no_entities,
test_data_no_entities, test_labels_no_entities, is_multiclass)
return data_table, data_table_no_entities
示例14
def _expand_package_ids(self, id_patterns, source):
for id_pattern in id_patterns:
if '*' in id_pattern:
pkg_ids = [
pkg_id for pkg_id in source if fnmatch(pkg_id, id_pattern)
]
if pkg_ids:
yield from pkg_ids
else:
# The pattern could not be expanded, yield it back
yield id_pattern
else:
yield id_pattern
示例15
def is_hidden(self, filename, path, goto=''):
if not (path or goto): # special case for ThisPC
return False
tests = self.view.settings().get('dired_hidden_files_patterns', ['.*'])
if isinstance(tests, str):
tests = [tests]
if any(fnmatch.fnmatch(filename, pattern) for pattern in tests):
return True
if sublime.platform() != 'windows':
return False
# check for attribute on windows:
try:
attrs = ctypes.windll.kernel32.GetFileAttributesW(join(path, goto, filename))
assert attrs != -1
result = bool(attrs & 2)
except (AttributeError, AssertionError):
result = False
return result
示例16
def match_file(filename, exclude):
"""Return True if file is okay for modifying/recursing."""
base_name = os.path.basename(filename)
if base_name.startswith('.'):
return False
for pattern in exclude:
if fnmatch.fnmatch(base_name, pattern):
return False
if fnmatch.fnmatch(filename, pattern):
return False
if not os.path.isdir(filename) and not is_python_file(filename):
return False
return True
示例17
def fnmatch(self, pattern):
"""return true if the basename/fullname matches the glob-'pattern'.
valid pattern characters::
* matches everything
? matches any single character
[seq] matches any character in seq
[!seq] matches any char not in seq
If the pattern contains a path-separator then the full path
is used for pattern matching and a '*' is prepended to the
pattern.
if the pattern doesn't contain a path-separator the pattern
is only matched against the basename.
"""
return FNMatcher(pattern)(self)
示例18
def __call__(self, path):
pattern = self.pattern
if (pattern.find(path.sep) == -1 and
iswin32 and
pattern.find(posixpath.sep) != -1):
# Running on Windows, the pattern has no Windows path separators,
# and the pattern has one or more Posix path separators. Replace
# the Posix path separators with the Windows path separator.
pattern = pattern.replace(posixpath.sep, path.sep)
if pattern.find(path.sep) == -1:
name = path.basename
else:
name = str(path) # path.strpath # XXX svn?
if not os.path.isabs(pattern):
pattern = '*' + path.sep + pattern
return fnmatch.fnmatch(name, pattern)
示例19
def match_file(filename, exclude):
"""Return True if file is okay for modifying/recursing."""
base_name = os.path.basename(filename)
if base_name.startswith('.'):
return False
for pattern in exclude:
if fnmatch.fnmatch(base_name, pattern):
return False
if fnmatch.fnmatch(filename, pattern):
return False
if not os.path.isdir(filename) and not is_python_file(filename):
return False
return True
示例20
def match_instance_to_bastion(instance, bastions):
for bastion_config in bastions:
for ipv4_pattern in bastion_config["hosts"]:
if fnmatch.fnmatch(instance.private_ip_address, ipv4_pattern["pattern"]):
logger.info("Using %s to connect to %s", bastion_config["pattern"], instance)
return bastion_config
示例21
def is_domain_match_glob_whitelist(domain):
"""
域名是否匹配 `domains_whitelist_auto_add_glob_list` 中设置的通配符
:type domain: str
:rtype: bool
"""
for domain_glob in domains_whitelist_auto_add_glob_list:
if fnmatch(domain, domain_glob):
return True
return False
示例22
def findMatchingInterface(iface_name, interfaces):
"""
Search an interface list for one matching a given name.
iface_name can contain shell-style wildcards (* and ?).
"""
for iface in interfaces:
if fnmatch.fnmatch(iface['name'], iface_name):
return iface
return None
示例23
def _list_files(root):
"""
Lists all of the files in a directory, taking into account any .gitignore
file that is present
:param root:
A unicode filesystem path
:return:
A list of unicode strings, containing paths of all files not ignored
by .gitignore with root, using relative paths
"""
dir_patterns, file_patterns = _gitignore(root)
paths = []
prefix = os.path.abspath(root) + os.sep
for base, dirs, files in os.walk(root):
for d in dirs:
for dir_pattern in dir_patterns:
if fnmatch(d, dir_pattern):
dirs.remove(d)
break
for f in files:
skip = False
for file_pattern in file_patterns:
if fnmatch(f, file_pattern):
skip = True
break
if skip:
continue
full_path = os.path.join(base, f)
if full_path[:len(prefix)] == prefix:
full_path = full_path[len(prefix):]
paths.append(full_path)
return sorted(paths)
示例24
def get_archive_policy_for_metric(self, metric_name):
"""Helper to get the archive policy according archive policy rules."""
rules = self.list_archive_policy_rules()
for rule in rules:
if fnmatch.fnmatch(metric_name or "", rule.metric_pattern):
return self.get_archive_policy(rule.archive_policy_name)
raise NoArchivePolicyRuleMatch(metric_name)
示例25
def _match_path(self, path, full_path, pattern):
# override this method to use alternative matching strategy
return fnmatch(path, pattern)
示例26
def recursive_glob(root, pattern):
if root is None:
return
if os.path.isfile(root) and fnmatch.fnmatch(root, pattern):
yield root
return
for base, dirs, files in os.walk(root):
matches = fnmatch.filter(files, pattern)
for filename in matches:
yield os.path.join(base, filename)
示例27
def is_ignored_key(key, ignore_files):
# Check if any subdirectories match the ignore patterns
key_parts = key.split("/")
for part in key_parts:
if any(fnmatch.fnmatch(part, pattern) for pattern in ignore_files):
return True
else:
return False
示例28
def get_find_process(pattern):
for p in psutil.process_iter():
if fnmatch.fnmatch(p.name(), pattern):
return p.pid
raise Exception("Process matching '" + pattern + "' not found")
示例29
def execute(self, context):
apps = join(getRoot(), 'applications')
for root, dirs, files in os.walk(apps):
for name in files:
if fnmatch.fnmatch(name, '*.blend'):
blendpath = norm(join(root, name))
# use file utility to check .blend version
if sys.platform.startswith('linux'):
fileinfo = subprocess.check_output(['file', '--uncompress', blendpath]).decode()
ver = re.search('\d\.\d\d', fileinfo).group(0)
verMaj, verMin = [int(n) for n in ver.split('.')]
# ignore incompatible blender files
if verMaj != 2:
continue
if verMin < 80:
continue
IGNORE = []
ignore = False
for pattern in IGNORE:
if fnmatch.fnmatch(name, pattern):
ignore = True
if ignore:
continue
gltfpath = findExportedAssetPath(blendpath)
if gltfpath:
self.__class__.exported.append((blendpath, gltfpath))
self.__class__.exported.sort()
self.__class__.reexportNext()
return {"FINISHED"}
示例30
def find_files(pattern, root):
"""Return all the files matching pattern below root dir."""
for dirpath, _, files in os.walk(root):
for filename in fnmatch.filter(files, pattern):
yield os.path.join(dirpath, filename)