Skip to content

Instantly share code, notes, and snippets.

@inureyes
Forked from achimnol/cache_file.py
Created June 5, 2013 12:51
Show Gist options
  • Save inureyes/5713632 to your computer and use it in GitHub Desktop.
Save inureyes/5713632 to your computer and use it in GitHub Desktop.
import os, time, shutil, heapq
MAX_CACHE_MB = 200
_CACHED_FILES = []
_CACHED_SIZE = None # in bytes
def cache_file(filename):
'''
Automatically maintain a cached version of the given filename.
It assumes that there is a RAM-disk cache at ~/ramdisk, and puts the
cached files as the same path as in the original file system. The
cache size is limited (configurable) and it automatically removes
oldest one if the size limit is exceeded like LRU.
'''
global _CACHED_FILES, _CACHED_SIZE
assert os.path.isfile(filename)
homedir = os.environ['HOME']
ramdir = os.path.join(homedir, 'ramdisk')
if not os.path.isdir(ramdir):
return filename
cachedir = os.path.join(ramdir, 'myscriptname')
if _CACHED_SIZE is None:
# update the current cache size when first called.
_CACHED_SIZE = 0
for root, dirs, files in os.walk(cachedir):
for name in files:
filepath = os.path.join(root, name)
_CACHED_SIZE += os.path.getsize(filepath)
heapq.heappush(_CACHED_FILES, (os.path.getmtime(filepath), filepath))
print('cache_file: Initial status: {0:.3f} MB'.format(_CACHED_SIZE / 1024 / 1024))
# NOTE: we need different path split mechanism for Windows.
filename = os.path.abspath(filename)
origdir, origname = os.path.split(filename)
targetdir = os.path.join(cachedir, origdir[1:])
cached_filename = os.path.join(targetdir, origname)
os.makedirs(targetdir, exist_ok=True)
# if the cached file does not exist or outdated, update it.
if not (os.path.exists(cached_filename) and
os.path.getmtime(cached_filename) >= os.path.getmtime(filename)):
add_size = os.path.getsize(filename)
timestamp = time.clock_gettime(time.CLOCK_REALTIME)
while _CACHED_SIZE + add_size > MAX_CACHE_MB * 1024 * 1024:
try:
_, old_filename = heapq.heappop(_CACHED_FILES)
_CACHED_SIZE -= os.path.getsize(old_filename)
os.unlink(old_filename)
except IndexError:
break
heapq.heappush(_CACHED_FILES, (timestamp, cached_filename))
shutil.copyfile(filename, cached_filename)
_CACHED_SIZE += add_size
return cached_filename
# Example usage
filename = cache_file(filename)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment