glob.py 1.5 KB

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