home *** CD-ROM | disk | FTP | other *** search
/ PC World 2005 June / PCWorld_2005-06_cd.bin / software / vyzkuste / firewally / firewally.exe / framework-2.3.exe / glob.py < prev    next >
Text File  |  2003-12-30  |  1KB  |  57 lines

  1. """Filename globbing utility."""
  2.  
  3. import os
  4. import fnmatch
  5. import re
  6.  
  7. __all__ = ["glob"]
  8.  
  9. def glob(pathname):
  10.     """Return a list of paths matching a pathname pattern.
  11.  
  12.     The pattern may contain simple shell-style wildcards a la fnmatch.
  13.  
  14.     """
  15.     if not has_magic(pathname):
  16.         if os.path.exists(pathname):
  17.             return [pathname]
  18.         else:
  19.             return []
  20.     dirname, basename = os.path.split(pathname)
  21.     if not dirname:
  22.         return glob1(os.curdir, basename)
  23.     elif has_magic(dirname):
  24.         list = glob(dirname)
  25.     else:
  26.         list = [dirname]
  27.     if not has_magic(basename):
  28.         result = []
  29.         for dirname in list:
  30.             if basename or os.path.isdir(dirname):
  31.                 name = os.path.join(dirname, basename)
  32.                 if os.path.exists(name):
  33.                     result.append(name)
  34.     else:
  35.         result = []
  36.         for dirname in list:
  37.             sublist = glob1(dirname, basename)
  38.             for name in sublist:
  39.                 result.append(os.path.join(dirname, name))
  40.     return result
  41.  
  42. def glob1(dirname, pattern):
  43.     if not dirname: dirname = os.curdir
  44.     try:
  45.         names = os.listdir(dirname)
  46.     except os.error:
  47.         return []
  48.     if pattern[0]!='.':
  49.         names=filter(lambda x: x[0]!='.',names)
  50.     return fnmatch.filter(names,pattern)
  51.  
  52.  
  53. magic_check = re.compile('[*?[]')
  54.  
  55. def has_magic(s):
  56.     return magic_check.search(s) is not None
  57.