如何將python中的變量保存在本地?
將python 的一些代碼保存在本地, 特別是一些需要大量運算的結果,例如 機器學習里面的模型,,放在本地,還是比較好用的。下次就可以直接拿出來使用就好。
然后現在添加了一個刪除變量的小功能。
其實可以 我覺得可以把 python 中的變量 保存在 redis 中,好像很騷氣的樣子。現在的代碼是放在本地文件中。
參考博客:
https://blog.csdn.net/qq_27061325/article/details/82113883
參考鏈接:
https://www.thoughtco.com/using-shelve-to-save-objects-2813668
見代碼:
import shelve
from contextlib import closing
class local_cache:
def __init__(self, cache='var.pkl'):
self.cache = cache
def __setitem__(self, key, value):
"""
key: 變量名
value: 變量值
cache: 緩存名
"""
with closing(shelve.open(self.cache, 'c')) as shelf:
shelf[key] = value
def __getitem__(self, key):
"""
key : 變量名
return:變量值
"""
with closing(shelve.open(self.cache, 'r')) as shelf:
return shelf.get(key)
def remove(self, key):
"""
key: 變量名
如果 變量存在則刪除, 如果不存在,會拋出一個異常,由調用方去處理
"""
with closing(shelve.open(self.cache, 'r')) as shelf:
del shelf[key]
return True
if __name__ == '__main__':
# 保存變量和提取變量
# cache = local_cache('var.pkl')
# cache['ok'] = 'okk'
# ok = cache['ok']
# print(ok)
# 刪除變量
cache = local_cache('var.pkl')
cache.remove('ok')
ok = cache['ok']
print(ok)
本地保存文件:
在redis中保存python對象: xxxxxx