Python文件缓存 [英] Python file cache

查看:356
本文介绍了Python文件缓存的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从文件中创建一些对象(通过xsd模板中的模板验证器,以便将其他xsd文件绘制在一起),并且我想在磁盘上的文件更改时重新创建对象。

I'm creating some objects from files (validators from templates xsd files, to draw together other xsd files, as it happens), and I'd like to recreate the objects when the file on disk changes.

我可以创建以下内容:

def getobj(fname, cache = {}):
    try:
        obj, lastloaded = cache[fname]
        if lastloaded < last_time_written(fname):
           # same stuff as in except clause
    except KeyError:
        obj = create_from_file(fname)
        cache[fname] = (obj, currenttime)

    return obj

但是,我希望使用别人经过测试的代码(如果存在) 。

However, I would prefer to use someone else's tested code if it exists. Is there an existing library that does something like this?

更新:我正在使用python 2.7.1。

Update: I'm using python 2.7.1.

推荐答案

您的代码(包括缓存逻辑)看起来不错。

Your code (including the cache logic) looks fine.

考虑移动 cache 变量。这样便可以添加其他功能来清除或检查缓存。

Consider moving the cache variable outside the function definition. That will make it possible to add other functions to clear or inspect the cache.

如果您想查看执行类似操作的代码,请查看<一个href = http://docs.python.org/library/filecmp.html#module-filecmp rel = nofollow> filecmp 模块: http://hg.python.org/cpython/file/2.7/Lib/filecmp.py 有趣的部分是如何统计模块用于确定文件是否已更改。这是 signature 函数:

If you want to look at code that does something similar, look at the source for the filecmp module: http://hg.python.org/cpython/file/2.7/Lib/filecmp.py The interesting part is how the stat module is used to determine whether a file has changed. Here is the signature function:

def _sig(st):
    return (stat.S_IFMT(st.st_mode),
            st.st_size,
            st.st_mtime)

这篇关于Python文件缓存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆