PyXR

c:\python24\lib \ statcache.py



0001 """Maintain a cache of stat() information on files.
0002 
0003 There are functions to reset the cache or to selectively remove items.
0004 """
0005 
0006 import warnings
0007 warnings.warn("The statcache module is obsolete.  Use os.stat() instead.",
0008               DeprecationWarning)
0009 del warnings
0010 
0011 import os as _os
0012 from stat import *
0013 
0014 __all__ = ["stat","reset","forget","forget_prefix","forget_dir",
0015            "forget_except_prefix","isdir"]
0016 
0017 # The cache.  Keys are pathnames, values are os.stat outcomes.
0018 # Remember that multiple threads may be calling this!  So, e.g., that
0019 # path in cache returns 1 doesn't mean the cache will still contain
0020 # path on the next line.  Code defensively.
0021 
0022 cache = {}
0023 
0024 def stat(path):
0025     """Stat a file, possibly out of the cache."""
0026     ret = cache.get(path, None)
0027     if ret is None:
0028         cache[path] = ret = _os.stat(path)
0029     return ret
0030 
0031 def reset():
0032     """Clear the cache."""
0033     cache.clear()
0034 
0035 # For thread saftey, always use forget() internally too.
0036 def forget(path):
0037     """Remove a given item from the cache, if it exists."""
0038     try:
0039         del cache[path]
0040     except KeyError:
0041         pass
0042 
0043 def forget_prefix(prefix):
0044     """Remove all pathnames with a given prefix."""
0045     for path in cache.keys():
0046         if path.startswith(prefix):
0047             forget(path)
0048 
0049 def forget_dir(prefix):
0050     """Forget a directory and all entries except for entries in subdirs."""
0051 
0052     # Remove trailing separator, if any.  This is tricky to do in a
0053     # x-platform way.  For example, Windows accepts both / and \ as
0054     # separators, and if there's nothing *but* a separator we want to
0055     # preserve that this is the root.  Only os.path has the platform
0056     # knowledge we need.
0057     from os.path import split, join
0058     prefix = split(join(prefix, "xxx"))[0]
0059     forget(prefix)
0060     for path in cache.keys():
0061         # First check that the path at least starts with the prefix, so
0062         # that when it doesn't we can avoid paying for split().
0063         if path.startswith(prefix) and split(path)[0] == prefix:
0064             forget(path)
0065 
0066 def forget_except_prefix(prefix):
0067     """Remove all pathnames except with a given prefix.
0068 
0069     Normally used with prefix = '/' after a chdir().
0070     """
0071 
0072     for path in cache.keys():
0073         if not path.startswith(prefix):
0074             forget(path)
0075 
0076 def isdir(path):
0077     """Return True if directory, else False."""
0078     try:
0079         st = stat(path)
0080     except _os.error:
0081         return False
0082     return S_ISDIR(st.st_mode)
0083 

Generated by PyXR 0.9.4
SourceForge.net Logo