Python源码示例:fnmatch.fnmatchcase()
示例1
def find_std(desc):
"""Search the standard (non-generalized) triggers. A list of
matches is returned. All terms must match. Wildcards are allowed.
Example:
find_std("CEIL UP S?") should return:
['CEIL S1 UP SLOW HNC', 'CEIL SR UP SLOW HNC']"""
terms = desc.split()
matches = []
for dsc in num2desc.values():
d = dsc.split()
matchedterms = 0
for term in terms:
for key in d:
if fnmatchcase(key, term):
matchedterms += 1
if matchedterms == len(terms):
matches.append(dsc)
return matches
示例2
def _matches_path(self, path: str) -> bool:
"""Match the URL's path.
Deviations from Chromium:
- Chromium only matches <all_urls> with "javascript:" (pathless); but
we also match *://*/* and friends.
"""
if self._path is None:
return True
# Match 'google.com' with 'google.com/'
if path + '/*' == self._path:
return True
# FIXME Chromium seems to have a more optimized glob matching which
# doesn't rely on regexes. Do we need that too?
return fnmatch.fnmatchcase(path, self._path)
示例3
def SelectParentAndDesiredChilds(obj):
#Selects only all child objects that must be exported with parent object
selectedObjs = []
bpy.ops.object.select_all(action='DESELECT')
for selectObj in GetExportDesiredChilds(obj):
if selectObj.name in bpy.context.view_layer.objects:
if GetAssetType(obj) == "SkeletalMesh":
#With skeletal mesh the socket must be not exported, ue4 read it like a bone
if not fnmatch.fnmatchcase(selectObj.name, "SOCKET*"):
selectObj.select_set(True)
selectedObjs.append(selectObj)
else:
selectObj.select_set(True)
selectedObjs.append(selectObj)
obj.select_set(True)
if obj.ExportAsProxy == True:
if obj.ExportProxyChild is not None:
obj.ExportProxyChild.select_set(True)
selectedObjs.append(obj)
bpy.context.view_layer.objects.active = obj
return selectedObjs
示例4
def UpdateNameHierarchy(list = None):
#Updates hierarchy names
if list is not None:
objs = list
else:
objs = GetAllCollisionAndSocketsObj()
for obj in objs:
if fnmatch.fnmatchcase(obj.name, "UBX*"):
UpdateUe4Name("Box", [obj])
if fnmatch.fnmatchcase(obj.name, "UCP*"):
UpdateUe4Name("Capsule", [obj])
if fnmatch.fnmatchcase(obj.name, "USP*"):
UpdateUe4Name("Sphere", [obj])
if fnmatch.fnmatchcase(obj.name, "UCX*"):
UpdateUe4Name("Convex", [obj])
if fnmatch.fnmatchcase(obj.name, "SOCKET*"):
UpdateUe4Name("Socket", [obj])
示例5
def _find(cls, pattern, manager, name, version):
name = '*' if name is None else name
installed = glob(
os.path.join(
manager.config.mods_directory,
pattern
)
)
for path in installed:
try:
mod = cls(manager, path)
except Exception as ex:
print("Warning: invalid mod %s: %s" % (path, ex))
continue
if not fnmatchcase(mod.name, name):
continue
if version is not None and version != mod.version:
continue
yield mod
示例6
def dict_match(d, key, default=None):
"""Like __getitem__ but works as if the keys() are all filename patterns.
Returns the value of any dict key that matches the passed key.
Args:
d (dict): A dict with filename patterns as keys
key (str): A key potentially matching any of the keys
default (object): The object to return if no pattern matched the
passed in key
Returns:
object: The dict value where the dict key matched the passed in key.
Or default if there was no match.
"""
if key in d and "[" not in key:
return d[key]
else:
for pattern, value in iteritems(d):
if fnmatchcase(key, pattern):
return value
return default
示例7
def command_wad_extract(parser, args):
if not os.path.isfile(args.wad):
parser.error("WAD file does not exist")
if not args.output:
args.output = os.path.splitext(args.wad)[0]
if os.path.exists(args.output) and not os.path.isdir(args.output):
parser.error("output is not a directory")
if args.hashes is None:
hashfile = default_hashfile(args.wad)
else:
hashfile = HashFile(args.hashes)
wad = Wad(args.wad, hashes=hashfile.load())
if args.unknown == 'yes':
pass # don't filter
elif args.unknown == 'only':
wad.files = [wf for wf in wad.files if wf.path is None]
elif args.unknown == 'no':
wad.files = [wf for wf in wad.files if wf.path is not None]
if args.pattern:
wad.files = [wf for wf in wad.files if any(wf.path is not None and fnmatch.fnmatchcase(wf.path, p) for p in args.pattern)]
wad.guess_extensions()
wad.extract(args.output, overwrite=not args.lazy)
示例8
def _expand_wildcard_action(action):
"""
:param action: 'autoscaling:*'
:return: A list of all autoscaling permissions matching the wildcard
"""
if isinstance(action, list):
expanded_actions = []
for item in action:
expanded_actions.extend(_expand_wildcard_action(item))
return expanded_actions
else:
if "*" in action:
expanded = [
expanded_action.lower()
for expanded_action in all_permissions
if fnmatch.fnmatchcase(expanded_action.lower(), action.lower())
]
# if we get a wildcard for a tech we've never heard of, just return the wildcard
if not expanded:
return [action.lower()]
return expanded
return [action.lower()]
示例9
def MatchesPattern(s, pattern):
if type(pattern) is str:
# old code:
# if ((len(s) > 1) and (s[0] == '/') and (s[-1] == '/'):
# re_string = p[1:-1] # strip off the slashes '/' and '/'
# if not re.search(re_string, s):
# return False
# new code:
# uses precompiled regular expressions (See "pattern.search" below)
if HasWildcard(pattern):
if not fnmatch.fnmatchcase(s, pattern):
return False
elif s != pattern:
return False
else:
#assert(type(p) is _sre.SRE_Match)
# I assume pattern = re.compile(some_reg_expr)
if not pattern.search(s):
return False
return True
示例10
def db_rebuild(self):
self.delete_table()
self.create_table()
for directory_name, directories, filenames in os.walk('modules/'):
for filename in filenames:
if filename not in ['__init__.py']\
and not fnmatchcase(filename, "*.pyc")\
and fnmatchcase(filename, "*.py"):
full_name = "{directory}/{filename}".format(directory=directory_name, filename=filename)
module_name = name_convert(full_name)
module_class = import_module("modules.{module_name}".format(
module_name=module_name.replace("/", ".")
))
module_instance = module_class.Exploit()
module_info = module_instance.get_info()
module_info['module_name'] = module_name
try:
getattr(module_instance, 'check')
module_info['check'] = 'True'
except AttributeError:
module_info['check'] = 'False'
self.insert_module(module_info)
示例11
def clear_wildcard_hooks(hc, stack_id, stack_patterns, hook_type,
resource_pattern):
if stack_patterns:
for resource in hc.resources.list(stack_id):
res_name = resource.resource_name
if fnmatch.fnmatchcase(res_name, stack_patterns[0]):
nested_stack = hc.resources.get(
stack_id=stack_id,
resource_name=res_name)
clear_wildcard_hooks(
hc,
nested_stack.physical_resource_id,
stack_patterns[1:], hook_type, resource_pattern)
else:
for resource in hc.resources.list(stack_id):
res_name = resource.resource_name
if fnmatch.fnmatchcase(res_name, resource_pattern):
clear_hook(hc, stack_id, res_name, hook_type)
示例12
def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf = self._flavour.casefold
path_pattern = cf(path_pattern)
drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
if not pat_parts:
raise ValueError("empty pattern")
if drv and drv != cf(self._drv):
return False
if root and root != cf(self._root):
return False
parts = self._cparts
if drv or root:
if len(pat_parts) != len(parts):
return False
pat_parts = pat_parts[1:]
elif len(pat_parts) > len(parts):
return False
for part, pat in zip(reversed(parts), reversed(pat_parts)):
if not fnmatch.fnmatchcase(part, pat):
return False
return True
示例13
def run_unittest(*classes):
"""Run tests from unittest.TestCase-derived classes."""
valid_types = (unittest.TestSuite, unittest.TestCase)
suite = unittest.TestSuite()
for cls in classes:
if isinstance(cls, str):
if cls in sys.modules:
suite.addTest(unittest.findTestCases(sys.modules[cls]))
else:
raise ValueError("str arguments must be keys in sys.modules")
elif isinstance(cls, valid_types):
suite.addTest(cls)
else:
suite.addTest(unittest.makeSuite(cls))
def case_pred(test):
if match_tests is None:
return True
for name in test.id().split("."):
if fnmatch.fnmatchcase(name, match_tests):
return True
return False
_filter_suite(suite, case_pred)
_run_suite(suite)
#=======================================================================
# Check for the presence of docstrings.
示例14
def run_unittest(*classes):
"""Run tests from unittest.TestCase-derived classes."""
valid_types = (unittest.TestSuite, unittest.TestCase)
suite = unittest.TestSuite()
for cls in classes:
if isinstance(cls, str):
if cls in sys.modules:
suite.addTest(unittest.findTestCases(sys.modules[cls]))
else:
raise ValueError("str arguments must be keys in sys.modules")
elif isinstance(cls, valid_types):
suite.addTest(cls)
else:
suite.addTest(unittest.makeSuite(cls))
def case_pred(test):
if match_tests is None:
return True
for name in test.id().split("."):
if fnmatch.fnmatchcase(name, match_tests):
return True
return False
_filter_suite(suite, case_pred)
_run_suite(suite)
# We don't have sysconfig on Py2.6:
# #=======================================================================
# # Check for the presence of docstrings.
#
# HAVE_DOCSTRINGS = (check_impl_detail(cpython=False) or
# sys.platform == 'win32' or
# sysconfig.get_config_var('WITH_DOC_STRINGS'))
#
# requires_docstrings = unittest.skipUnless(HAVE_DOCSTRINGS,
# "test requires docstrings")
#
#
# #=======================================================================
# doctest driver.
示例15
def request(self, route, *, files=None, header_bypass_delay=None, **kwargs):
req = Request(route.method, route.url, kwargs.get('data') or kwargs.get('json'))
log.info(str(req))
self._request_check_queue.put(req)
request_route = f"{req.method} {req.url.split(Route.BASE)[-1]}"
try:
endpoint = next(k for k in RESPONSES if fnmatchcase(request_route, k))
except StopIteration:
raise RuntimeError("Bot requested an endpoint we don't have a test for")
return RESPONSES[endpoint](req.data)
# helper functions
示例16
def GetAllCollisionAndSocketsObj():
#Get any object that can be understood as a collision or a socket by unreal
colObjs = [obj for obj in bpy.context.scene.objects if
fnmatch.fnmatchcase(obj.name, "UBX*") or
fnmatch.fnmatchcase(obj.name, "UCP*") or
fnmatch.fnmatchcase(obj.name, "USP*") or
fnmatch.fnmatchcase(obj.name, "UCX*") or
fnmatch.fnmatchcase(obj.name, "SOCKET*")]
return colObjs
示例17
def GetSocketDesiredChild(targetObj):
socket = [obj for obj in GetExportDesiredChilds(targetObj) if
fnmatch.fnmatchcase(obj.name, "SOCKET*")]
return socket
示例18
def GetAllCollisionObj():
#Get any object that can be understood as a collision or a socket by unreal
colObjs = [obj for obj in bpy.context.scene.objects if
fnmatch.fnmatchcase(obj.name, "UBX*") or
fnmatch.fnmatchcase(obj.name, "UCP*") or
fnmatch.fnmatchcase(obj.name, "USP*") or
fnmatch.fnmatchcase(obj.name, "UCX*")]
return colObjs
示例19
def GetActionToExport(obj):
#Returns only the actions that will be exported with the Armature
#if obj.animation_data is None:
#return []
if obj.ExportAsLod == True:
return []
TargetActionToExport = [] #Action list
if obj.exportActionEnum == "dont_export":
return []
elif obj.exportActionEnum == "export_specific_list":
for action in bpy.data.actions:
for targetAction in obj.exportActionList:
if targetAction.use == True:
if targetAction.name == action.name:
TargetActionToExport.append(action)
elif obj.exportActionEnum == "export_specific_prefix":
for action in bpy.data.actions:
if fnmatch.fnmatchcase(action.name, obj.PrefixNameToExport+"*"):
TargetActionToExport.append(action)
elif obj.exportActionEnum == "export_auto":
objBoneNames = [bone.name for bone in obj.data.bones]
for action in bpy.data.actions:
actionBoneNames = [group.name for group in action.groups]
if ChecksRelationship(objBoneNames, actionBoneNames):
TargetActionToExport.append(action)
return TargetActionToExport
示例20
def UpdateNameHierarchy():
#Updates hierarchy names
for obj in GetAllCollisionAndSocketsObj():
if fnmatch.fnmatchcase(obj.name, "UBX*"):
UpdateUe4Name("Box", [obj])
if fnmatch.fnmatchcase(obj.name, "UCP*"):
UpdateUe4Name("Capsule", [obj])
if fnmatch.fnmatchcase(obj.name, "USP*"):
UpdateUe4Name("Sphere", [obj])
if fnmatch.fnmatchcase(obj.name, "UCX*"):
UpdateUe4Name("Convex", [obj])
if fnmatch.fnmatchcase(obj.name, "SOCKET*"):
UpdateUe4Name("Socket", [obj])
示例21
def GetSocketDesiredChild(targetObj):
socket = [obj for obj in GetExportDesiredChilds(targetObj) if
fnmatch.fnmatchcase(obj.name, "SOCKET*")]
return socket
示例22
def GetAllCollisionObj():
#Get any object that can be understood as a collision or a socket by unreal
colObjs = [obj for obj in bpy.context.scene.objects if
fnmatch.fnmatchcase(obj.name, "UBX*") or
fnmatch.fnmatchcase(obj.name, "UCP*") or
fnmatch.fnmatchcase(obj.name, "USP*") or
fnmatch.fnmatchcase(obj.name, "UCX*")]
return colObjs
示例23
def GetActionToExport(obj):
#Returns only the actions that will be exported with the Armature
if obj.ExportAsLod == True:
return []
TargetActionToExport = [] #Action list
if obj.exportActionEnum == "dont_export":
return []
if obj.exportActionEnum == "export_current":
if obj.animation_data is not None:
if obj.animation_data.action is not None:
return [obj.animation_data.action]
elif obj.exportActionEnum == "export_specific_list":
for action in bpy.data.actions:
for targetAction in obj.exportActionList:
if targetAction.use == True:
if targetAction.name == action.name:
TargetActionToExport.append(action)
elif obj.exportActionEnum == "export_specific_prefix":
for action in bpy.data.actions:
if fnmatch.fnmatchcase(action.name, obj.PrefixNameToExport+"*"):
TargetActionToExport.append(action)
elif obj.exportActionEnum == "export_auto":
#This will cheak if the action contains the same bones of the armature
objBoneNames = [bone.name for bone in obj.data.bones]
for action in bpy.data.actions:
actionBoneNames = [group.name for group in action.groups]
if ChecksRelationship(actionBoneNames, objBoneNames):
TargetActionToExport.append(action)
return TargetActionToExport
示例24
def match(self, target):
return fnmatchcase(target, self.expected)
示例25
def _build_filter(*patterns):
"""
Given a list of patterns, return a callable that will be true only if
the input matches one of the patterns.
"""
return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
示例26
def check_standard_dir(module_path):
"""Checks whether path belongs to standard library or installed modules."""
if 'site-packages' in module_path:
return True
for stdlib_path in _STDLIB_PATHS:
if fnmatch.fnmatchcase(module_path, stdlib_path + '*'):
return True
return False
示例27
def matches_patterns(path, patterns=None):
"""
Return True or False depending on whether the ``path`` should be
ignored (if it matches any pattern in ``ignore_patterns``).
"""
if patterns is None:
patterns = []
for pattern in patterns:
if fnmatch.fnmatchcase(path, pattern):
return True
return False
示例28
def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf = self._flavour.casefold
path_pattern = cf(path_pattern)
drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
if not pat_parts:
raise ValueError("empty pattern")
if drv and drv != cf(self._drv):
return False
if root and root != cf(self._root):
return False
parts = self._cparts
if drv or root:
if len(pat_parts) != len(parts):
return False
pat_parts = pat_parts[1:]
elif len(pat_parts) > len(parts):
return False
for part, pat in zip(reversed(parts), reversed(pat_parts)):
if not fnmatch.fnmatchcase(part, pat):
return False
return True
# Can't subclass os.PathLike from PurePath and keep the constructor
# optimizations in PurePath._parse_args().
示例29
def _build_filter(*patterns):
"""
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
"""
return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns)
示例30
def match(self, path_pattern):
"""
Return True if this path matches the given pattern.
"""
cf = self._flavour.casefold
path_pattern = cf(path_pattern)
drv, root, pat_parts = self._flavour.parse_parts((path_pattern,))
if not pat_parts:
raise ValueError("empty pattern")
if drv and drv != cf(self._drv):
return False
if root and root != cf(self._root):
return False
parts = self._cparts
if drv or root:
if len(pat_parts) != len(parts):
return False
pat_parts = pat_parts[1:]
elif len(pat_parts) > len(parts):
return False
for part, pat in zip(reversed(parts), reversed(pat_parts)):
if not fnmatch.fnmatchcase(part, pat):
return False
return True
# Can't subclass os.PathLike from PurePath and keep the constructor
# optimizations in PurePath._parse_args().