0001 """Filename globbing utility.""" 0002 0003 import os 0004 import fnmatch 0005 import re 0006 0007 __all__ = ["glob"] 0008 0009 def glob(pathname): 0010 """Return a list of paths matching a pathname pattern. 0011 0012 The pattern may contain simple shell-style wildcards a la fnmatch. 0013 0014 """ 0015 if not has_magic(pathname): 0016 if os.path.lexists(pathname): 0017 return [pathname] 0018 else: 0019 return [] 0020 dirname, basename = os.path.split(pathname) 0021 if not dirname: 0022 return glob1(os.curdir, basename) 0023 elif has_magic(dirname): 0024 list = glob(dirname) 0025 else: 0026 list = [dirname] 0027 if not has_magic(basename): 0028 result = [] 0029 for dirname in list: 0030 if basename or os.path.isdir(dirname): 0031 name = os.path.join(dirname, basename) 0032 if os.path.lexists(name): 0033 result.append(name) 0034 else: 0035 result = [] 0036 for dirname in list: 0037 sublist = glob1(dirname, basename) 0038 for name in sublist: 0039 result.append(os.path.join(dirname, name)) 0040 return result 0041 0042 def glob1(dirname, pattern): 0043 if not dirname: dirname = os.curdir 0044 try: 0045 names = os.listdir(dirname) 0046 except os.error: 0047 return [] 0048 if pattern[0]!='.': 0049 names=filter(lambda x: x[0]!='.',names) 0050 return fnmatch.filter(names,pattern) 0051 0052 0053 magic_check = re.compile('[*?[]') 0054 0055 def has_magic(s): 0056 return magic_check.search(s) is not None 0057
Generated by PyXR 0.9.4