我有一个Python应用程序,它执行以下操作:
with shelve.open(shelvefilename, flag='c')存储对象。with shelve.open(shelvefilename, flag='r')读取搁置文件。问题是,在某个时候,我得到了一个_gdbm.error: [Errno 11] Resource temporarily unavailable错误:
File "/path/to/myprog.py", line 755, in mymethod
with shelve.open(shelvefilename, flag='r') as shlvfile:
File "/usr/local/lib/python3.6/shelve.py", line 243, in open
return DbfilenameShelf(filename, flag, protocol, writeback)
File "/usr/local/lib/python3.6/shelve.py", line 227, in __init__
Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback)
File "/usr/local/lib/python3.6/dbm/__init__.py", line 94, in open
return mod.open(file, flag, mode)
_gdbm.error: [Errno 11] Resource temporarily unavailable我的猜测是,这是因为在某一时刻,我打开了搁置文件,用于读写操作,即定义为成问题。
是否可以在不干扰读取操作的情况下对搁置文件进行更新?
发布于 2019-11-30 01:25:33
我只是在一个小模块中使用搁置来缓存汇率,遇到了这个问题。您可以使用python线程和全局threading.Lock()对象来解决这个问题。
from threading import Lock
import shelve
mutex = Lock()
mutex.acquire()
db = shelve.open(db_name)
# write to db
db.close()
mutex.release()代码片段的原始源代码和这个想法的信用可以找到@ http://georg.io/2014/06/Python-Shelve-Thread-Safety。
`threading.Lock()对象通过阻塞其他python线程来工作,直到它被释放。请参阅https://docs.python.org/2/library/threading.html#lock-objects
发布于 2018-10-22 08:38:28
这更像是一个概念性的问题。如果一个进程同时修改文件中的数据,而另一个进程同时读取数据,则结果是不可预测的。
假设您读取了文件的一部分,此时只编写了某些值的一半。读取将简单地不能正确地解析条目,而且可能也无法解析所有后续条目。换句话说,它迟早会破裂。
我认为最好的方法是将“搁置”集中在一个进程中,或者使用一个数据库。
https://stackoverflow.com/questions/52381091
复制相似问题