【问题标题】:Save and load entire module as pickle将整个模块保存并加载为泡菜
【发布时间】:2021-09-10 14:40:32
【问题描述】:

到目前为止,我成功地使用dill 保存了我的整个状态,但这会导致其他运行时变量出现一些问题。我只想保存一个用作全局变量容器的模块。

谷歌搜索导致我只找到有关 dill 模块的结果,而不是如何从中存储整个模块(或更好的变量)。

到目前为止,我已经尝试存储模块的字典,然后再次加载它。这会导致类型错误,并且看起来不是一种方便的处理方式。

我的“res”模块看起来像这样:

VAR1="asd"
VAR2=123

我的尝试:

import dill
import res

with open("test.pkl", 'wb') as pickle_file:
    dill.dump(res.__dict__,pickle_file)

res.VAR1="123"

with open("test.pkl", 'r') as pickle_file:
    res.__dict__ = dill.load(pickle_file)

非常感谢!

注意:我选择这种模块方法,因为我从多个线程访问该模块,并且信息需要在它们之间可用和共享。

【问题讨论】:

    标签: python pickle dill


    【解决方案1】:

    我是dill 作者。也许我不明白你想做什么,但它是这样的吗:

    Python 3.6.15 (default, Sep  5 2021, 03:31:49) 
    [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import dill
    >>> import res
    >>> res.VAR1
    'asd'
    >>> res.VAR2
    123
    >>> 
    >>> with open('test.pkl', 'wb') as f:
    ...   dill.dump(res, f)
    ... 
    >>>
    

    然后在新会话中...(注意负载中的“rb”):

    Python 3.6.15 (default, Sep  5 2021, 03:31:49) 
    [GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import dill
    >>> with open('test.pkl', 'rb') as f:
    ...   res = dill.load(f)
    ... 
    >>> res
    <module 'res' from './res.py'>
    >>> res.VAR1
    'asd'
    >>> res.VAR2
    123
    >>>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-18
      • 2018-12-18
      • 1970-01-01
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 2017-09-23
      相关资源
      最近更新 更多