Python 搁置模块有问题吗?

Python 搁置模块有问题吗?,python,shelve,Python,Shelve,使用搁置模块给了我一些令人惊讶的行为。keys()、iter()和iteritems()不会返回工具架中的所有条目!代码如下: cache = shelve.open('my.cache') # ... cache[url] = (datetime.datetime.today(), value) 后来: cache = shelve.open('my.cache') urls = ['accounts_with_transactions.xml', 'targets.xml', 'profi

使用搁置模块给了我一些令人惊讶的行为。keys()、iter()和iteritems()不会返回工具架中的所有条目!代码如下:

cache = shelve.open('my.cache')
# ...
cache[url] = (datetime.datetime.today(), value)
后来:

cache = shelve.open('my.cache')
urls = ['accounts_with_transactions.xml', 'targets.xml', 'profile.xml']
try:
    print list(cache.keys()) # doesn't return all the keys!
    print [url for url in urls if cache.has_key(url)]
    print list(cache.keys())
finally:
    cache.close()
以下是输出:

['targets.xml']
['accounts_with_transactions.xml', 'targets.xml']
['targets.xml', 'accounts_with_transactions.xml']
[]
['trxns.xml', 'foobar.xml']
['foobar.xml', 'trxns.xml']

以前是否有人遇到过这种情况,在事先不知道所有可能的缓存键的情况下是否有解决方法?

看到您的示例,我的第一个想法是
缓存。Has_key()
有副作用,即此调用将向缓存添加键。你买什么

print cache.has_key('xxx')
print list(cache.keys())
根据报告:

…不幸的是,如果使用数据库,数据库也会受到dbm的限制-这意味着存储在数据库中的对象(pickle表示)应该相当小

这正确地复制了“bug”:

import shelve

a = 'trxns.xml'
b = 'foobar.xml'
c = 'profile.xml'

urls = [a, b, c]
cache = shelve.open('my.cache', 'c')

try:
    cache[a] = a*1000
    cache[b] = b*10000
finally:
    cache.close()


cache = shelve.open('my.cache', 'c')

try:
    print cache.keys()
    print [url for url in urls if cache.has_key(url)]
    print cache.keys()
finally:
    cache.close()
对于输出:

['targets.xml']
['accounts_with_transactions.xml', 'targets.xml']
['targets.xml', 'accounts_with_transactions.xml']
[]
['trxns.xml', 'foobar.xml']
['foobar.xml', 'trxns.xml']

因此,答案是不要像原始xml那样存储任何大数据,而是将计算结果存储在一个架子上。

您使用的是什么dbm模块?听起来像是个bug。whichdb.whichdb('my.cache')=>dbm(顺便说一句,这是mac上的Python2.5)您能展示一下put方法的代码吗?这不是标准搁置类的一部分,我用URLSTILL NOT compute的缩写版本更新了问题代码;将单个URL添加到缓存中,但在
具有\u key
之后,缓存有两个URL。一定有副作用。缓存中确实有两个URL。但是keys()在我显式地测试它们之前不会同时显示它们。你能发布has_key()吗?在Python 2.6中,我不能重现这个“bug”。你可能没有使用dbm,请尝试whichdb.whichdb('my.cache')。在我的mac上,它生成“dbm”。我还没有在其他系统上试用过。