home *** CD-ROM | disk | FTP | other *** search
/ PC World 2001 April / PCWorld_2001-04_cd.bin / Software / TemaCD / webclean / !!!python!!! / BeOpen-Python-2.0.exe / STATCACHE.PY < prev    next >
Encoding:
Python Source  |  2000-09-28  |  1.6 KB  |  76 lines

  1. """Maintain a cache of stat() information on files.
  2.  
  3. There are functions to reset the cache or to selectively remove items.
  4. """
  5.  
  6. import os
  7. from stat import *
  8.  
  9. # The cache.
  10. # Keys are pathnames, values are `os.stat' outcomes.
  11. #
  12. cache = {}
  13.  
  14.  
  15. def stat(path):
  16.     """Stat a file, possibly out of the cache."""
  17.     if cache.has_key(path):
  18.         return cache[path]
  19.     cache[path] = ret = os.stat(path)
  20.     return ret
  21.  
  22.  
  23. def reset():
  24.     """Reset the cache completely."""
  25.     global cache
  26.     cache = {}
  27.  
  28.  
  29. def forget(path):
  30.     """Remove a given item from the cache, if it exists."""
  31.     if cache.has_key(path):
  32.         del cache[path]
  33.  
  34.  
  35. def forget_prefix(prefix):
  36.     """Remove all pathnames with a given prefix."""
  37.     n = len(prefix)
  38.     for path in cache.keys():
  39.         if path[:n] == prefix:
  40.             del cache[path]
  41.  
  42.  
  43. def forget_dir(prefix):
  44.     """Forget about a directory and all entries in it, but not about
  45.     entries in subdirectories."""
  46.     if prefix[-1:] == '/' and prefix <> '/':
  47.         prefix = prefix[:-1]
  48.     forget(prefix)
  49.     if prefix[-1:] <> '/':
  50.         prefix = prefix + '/'
  51.     n = len(prefix)
  52.     for path in cache.keys():
  53.         if path[:n] == prefix:
  54.             rest = path[n:]
  55.             if rest[-1:] == '/': rest = rest[:-1]
  56.             if '/' not in rest:
  57.                 del cache[path]
  58.  
  59.  
  60. def forget_except_prefix(prefix):
  61.     """Remove all pathnames except with a given prefix.
  62.     Normally used with prefix = '/' after a chdir()."""
  63.     n = len(prefix)
  64.     for path in cache.keys():
  65.         if path[:n] <> prefix:
  66.             del cache[path]
  67.  
  68.  
  69. def isdir(path):
  70.     """Check for directory."""
  71.     try:
  72.         st = stat(path)
  73.     except os.error:
  74.         return 0
  75.     return S_ISDIR(st[ST_MODE])
  76.