1、shelve模塊是一個簡單的key,value將內存數據通過文件持久化的模塊
2、shelve模塊可以持久化任何pickle可支持的python數據格式
3、shelve就是pickle模塊的一個封裝
4、shelve模塊是可以多次dump和load
?
https://docs.python.org/3.6/library/shelve.html
1、該模塊底層使用dbm模塊做存儲,具體使用的是dbm.gnu
還是dbm.ndbm,由運行時看哪個裝了就用哪個,否則用
dbm.dumb
2、不支持并發讀寫,但是支持并發讀
#!/usr/bin/env python #coding=utf-8 import shelve import threadingclass A(object):
"""一個用于測試的類 其中只打印出hello和bye
"""def __init__(self, name):self.name = nameself.__actions = ['hello', 'bye']
def _hello(self):print ('hello, %s' % self.name)
def _bye(self):print ('bye, %s' % self.name)
def act(self):for a in self.__actions:if callable(getattr(self, '_'+a)):getattr(self, '_'+a)()FILENAME = 'shelve_test' KEY = 'myobj' DATA = A('qx')def test1():
"""基本用法
"""with shelve.open(FILENAME) as d:d[KEY] = DATAdata = d[KEY]print ('type(data)=%s' % type(data))del d[KEY]try:data = d[KEY]except KeyError:print ('key=%s not found' % KEY)d[KEY] = DATAdef test2():
"""當沒有使用write_back=True時 shelve無法檢測到可變對象的更新
"""with shelve.open(FILENAME) as d:d['xx'] = [0, 1, 2]print ("d['xx']=", d['xx']) # [0, 1, 2]d['xx'].append(3)print ("d['xx']=", d['xx']) # [0, 1, 2]def test3():
"""繼續test2 只能通過重新賦值來更新d['xx']
"""with shelve.open(FILENAME) as d:d['xx'] = [0, 1, 2]print ("d['xx']=", d['xx']) # [0, 1, 2]data = d['xx']data.append(3)d['xx'] = dataprint ("d['xx']=", d['xx']) # [0, 1, 2, 3]def test4(flag=None):
"""不支持并發讀寫 這是由Unix文件系統的文件鎖保證的 但是支持多線程并發讀
"""if flag is None: flag = 'c'def _test():d = shelve.open(FILENAME, flag=flag)try:data = d[KEY]except Exception as exc:print ('exception:%s' % exc)else:data.act()print (d['xx'])finally:d.close()
t1 = threading.Thread(target=_test)t2 = threading.Thread(target=_test)t1.start();t2.start()t1.join();t2.join()def split(seq):
"""打印分隔線
"""print ('====test %d====' % seq)if __name__ == '__main__':split(1);test1() # key=myobj not foundsplit(2);test2()split(3);test3()split(4);test4('r') # 如果調用test4() 會報異常 Resource temporarily unavailable
python常用庫有哪些。?