gpt4 book ai didi

python : How to read pickle dump?

转载 作者:太空宇宙 更新时间:2023-11-04 09:10:21 25 4
gpt4 key购买 nike

我有一个 pickle 堆,是我从一个 friend 那里得到的,他让我像这样读它:

f = open('file.pickle')
import pickle
l = pickle.loads(f.read())

但是我得到一个 ImportErrorno module named sql.models

有人可以帮助我了解发生了什么吗?

最佳答案

您缺少重建 pickle 对象所需的代码。

Pickles 存储可以从中导入类的位置以及实例属性。仍然需要原始模块来重新创建模块。来自documentation :

Note that functions (built-in and user-defined) are pickled by “fully qualified” name reference, not by value. This means that only the function name is pickled, along with the name of the module the function is defined in. Neither the function’s code, nor any of its function attributes are pickled. Thus the defining module must be importable in the unpickling environment, and the module must contain the named object, otherwise an exception will be raised. [4]

Similarly, classes are pickled by named reference, so the same restrictions in the unpickling environment apply. Note that none of the class’s code or data is pickled, so in the following example the class attribute attr is not restored in the unpickling environment:

class Foo:
attr = 'a class attr'

picklestring = pickle.dumps(Foo)

These restrictions are why picklable functions and classes must be defined in the top level of a module.

换句话说,用于创建 pickle 的原始数据至少包括一个自定义类的实例,该实例源自名为 sql.models 的模块。 .

一定要小心阅读随意的 pickle ,即使是来自 friend 的。 pickle 只是一种重新创建任意 Python 结构的堆栈语言。只要有足够的决心和技巧,您就可以构建一个 pickle,在您的计算机上生成一个 secret 的后门服务器。 pickle文档明确警告您:

Warning: The pickle module is not intended to be secure against erroneous or maliciously constructed data. Never unpickle data received from an untrusted or unauthenticated source.

这有 been a problem in the past ,即使对于经验丰富的开发人员也是如此。

关于 python : How to read pickle dump?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16045864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com