You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

dircache.py 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. """Read and cache directory listings.
  2. The listdir() routine returns a sorted list of the files in a directory,
  3. using a cache to avoid reading the directory more often than necessary.
  4. The annotate() routine appends slashes to directories."""
  5. import os
  6. __all__ = ["listdir", "opendir", "annotate", "reset"]
  7. cache = {}
  8. def reset():
  9. """Reset the cache completely."""
  10. global cache
  11. cache = {}
  12. def listdir(path):
  13. """List directory contents, using cache."""
  14. try:
  15. cached_mtime, list = cache[path]
  16. del cache[path]
  17. except KeyError:
  18. cached_mtime, list = -1, []
  19. try:
  20. mtime = os.stat(path)[8]
  21. except os.error:
  22. return []
  23. if mtime != cached_mtime:
  24. try:
  25. list = os.listdir(path)
  26. except os.error:
  27. return []
  28. list.sort()
  29. cache[path] = mtime, list
  30. return list
  31. opendir = listdir # XXX backward compatibility
  32. def annotate(head, list):
  33. """Add '/' suffixes to directories."""
  34. for i in range(len(list)):
  35. if os.path.isdir(os.path.join(head, list[i])):
  36. list[i] = list[i] + '/'