PageRenderTime 43ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 0ms

/Python/system/glob.py

https://bitbucket.org/cwalther/moulscript-dlanor
Python | 56 lines | 43 code | 7 blank | 6 comment | 18 complexity | 7ba28c586eb5f250017f292f390d295d MD5 | raw file
Possible License(s): AGPL-1.0, GPL-3.0
  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.exists(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.exists(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