Python shelve module question

后端 未结 3 2140
忘了有多久
忘了有多久 2020-12-17 01:48

Does the Python shelve module have any protection built in to make sure two processes aren\'t writing to a file at the same time?

3条回答
  •  生来不讨喜
    2020-12-17 02:02

    As per the top answer, it's not safe to have multiple writers to the shelve. My approach to making shelves safer is to write a wrapper that takes care of opening and accessing shelve elements. The wrapper code looks something like this:

    def open(self, mode=READONLY):
        if mode is READWRITE:
            lockfilemode = "a" 
            lockmode = LOCK_EX
            shelve_mode = 'c'
        else:
            lockfilemode = "r"
            lockmode = LOCK_SH
            shelve_mode = 'r'
        self.lockfd = open(shelvefile+".lck", lockfilemode)
        fcntl.flock(self.lockfd.fileno(), lockmode | LOCK_NB)
        self.shelve = shelve.open(shelvefile, flag=shelve_mode, protocol=pickle.HIGHEST_PROTOCOL))
    def close(self):
        self.shelve.close()
        fcntl.flock(self.lockfd.fileno(), LOCK_UN)
        lockfd.close()
    

提交回复
热议问题