dircache.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  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. mtime = os.stat(path).st_mtime
  20. if mtime != cached_mtime:
  21. list = os.listdir(path)
  22. list.sort()
  23. cache[path] = mtime, list
  24. return list
  25. opendir = listdir # XXX backward compatibility
  26. def annotate(head, list):
  27. """Add '/' suffixes to directories."""
  28. for i in range(len(list)):
  29. if os.path.isdir(os.path.join(head, list[i])):
  30. list[i] = list[i] + '/'