gpt4 book ai didi

python - Python 的 shelve.open 可以嵌套调用吗?

转载 作者:太空狗 更新时间:2023-10-29 21:46:21 27 4
gpt4 key购买 nike

我正在尝试编写一个使用 shelve 的内存库持久存储返回值。如果我有内存函数调用其他内存函数,我想知道如何正确打开 shelf 文件。

import shelve
import functools


def cache(filename):
def decorating_function(user_function):
def wrapper(*args, **kwds):
key = str(hash(functools._make_key(args, kwds, typed=False)))
with shelve.open(filename, writeback=True) as cache:
if key in cache:
return cache[key]
else:
result = user_function(*args, **kwds)
cache[key] = result
return result

return functools.update_wrapper(wrapper, user_function)

return decorating_function


@cache(filename='cache')
def expensive_calculation():
print('inside function')
return


@cache(filename='cache')
def other_expensive_calculation():
print('outside function')
return expensive_calculation()

other_expensive_calculation()

除了这行不通

$ python3 shelve_test.py
outside function
Traceback (most recent call last):
File "shelve_test.py", line 33, in <module>
other_expensive_calculation()
File "shelve_test.py", line 13, in wrapper
result = user_function(*args, **kwds)
File "shelve_test.py", line 31, in other_expensive_calculation
return expensive_calculation()
File "shelve_test.py", line 9, in wrapper
with shelve.open(filename, writeback=True) as cache:
File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/shelve.py", line 239, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/shelve.py", line 223, in __init__
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
File "/usr/local/Cellar/python3/3.4.1/Frameworks/Python.framework/Versions/3.4/lib/python3.4/dbm/__init__.py", line 94, in open
return mod.open(file, flag, mode)
_gdbm.error: [Errno 35] Resource temporarily unavailable

您对解决这类问题的建议是什么。

最佳答案

不,你可能没有嵌套 shelve具有相同文件名的实例。

The shelve module does not support concurrent read/write access to shelved objects. (Multiple simultaneous read accesses are safe.) When a program has a shelf open for writing, no other program should have it open for reading or writing. Unix file locking can be used to solve this, but this differs across Unix versions and requires knowledge about the database implementation used.

https://docs.python.org/3/library/shelve.html#restrictions

关于python - Python 的 shelve.open 可以嵌套调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24939403/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com