将python 中的变量保存到本地

如何将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[key]

使用:

>>> cache = local_cache('var.pkl')
>>> cache['ok'] = 'okk'
>>> ok = cache['ok']
>>> print(ok)
>>> okk

本地保存文件:

在redis中保存python对象: xxxxxx

猜你喜欢

转载自www.cnblogs.com/gznb/p/12534593.html