Quick update to the README file. For intros and books we now point to
[python/dscho.git] / Lib / statcache.py
blobb5147c233dc545952790a88e3f014d6427565c01
1 """Maintain a cache of stat() information on files.
3 There are functions to reset the cache or to selectively remove items.
4 """
6 import os
7 from stat import *
9 # The cache.
10 # Keys are pathnames, values are `os.stat' outcomes.
12 cache = {}
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
23 def reset():
24 """Reset the cache completely."""
25 global cache
26 cache = {}
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]
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]
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]
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]
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])