简体   繁体   English

Python Pickle 在 Windows 中加载时崩溃

[英]Python Pickle crashing on load in Windows

I've got a program that uses Pickle to save and load objects from disk.我有一个使用 Pickle 从磁盘保存和加载对象的程序。 The pickle saving and loading looks like this:泡菜保存和加载看起来像这样:

def saveData(self,obj):
    f = open(os.path.join(self.directory,obj.name),'wb')
    pickle.dump(obj, f)

def loadData(self,fname):
    f = open(os.path.join(self.directory,fname),'rb')
    ret = pickle.load(f)
    return ret

And I have a test method that simply makes an object, saves it, then immediately loads it.我有一个测试方法,它只是创建一个对象,保存它,然后立即加载它。 In Linux, the object works fine, but in Windows, the program crashes when it tries to load the object.在 Linux 中,对象工作正常,但在 Windows 中,程序在尝试加载对象时崩溃。 I've re-made the pickled file in Windows, so it isn't trying to open the Linux object dump (although if there's a way to do cross-platform pickling, I would like to know about it)我已经在 Windows 中重新制作了腌制文件,因此它不会尝试打开 Linux 对象转储(尽管如果有一种方法可以进行跨平台腌制,我想了解一下)

What could be causing this program to crash in Windows but not Linux?什么可能导致该程序在 Windows 中崩溃而不是在 Linux 中崩溃?

Pickle basically only stores the attributes of an object and the classname to recreate it. Pickle 基本上只存储对象的属性和类名来重新创建它。

If you happen to have a C/C++ wrapped object, the attributes might contain pointers to memory locations (aka C-Pointers).如果您碰巧有一个 C/C++ 包装对象,则属性可能包含指向内存位置的指针(又名 C 指针)。 So if you pickle that object, destory the old object and restore it, the pointers point somewhere invalid.因此,如果您腌制该对象,销毁旧对象并恢复它,则指针指向无效的某个地方。 If those are used during unpickling, you get a crash.如果在 unpickling 期间使用这些,则会发生崩溃。 And the crash will happen on one OS or the other depending on how the memory manager reused the address.崩溃将发生在一个操作系统或另一个操作系统上,具体取决于内存管理器如何重用地址。 Windows seems to be more eager to free things. Windows 似乎更渴望免费的东西。

So, does this happen for some extension object?那么,对于某些扩展对象会发生这种情况吗? It should not happen for a pure python class.对于纯 python 类,它不应该发生。

The issue here is related to the differences in the way Python handles certain objects (eg paths) depending on the OS.这里的问题与 Python 根据操作系统处理某些对象(例如路径)的方式的差异有关。

The nature of the underlying issue is described in this answer .此答案中描述了潜在问题的性质。

In short: pickled files are not transferable between OSes (most of the time).简而言之:腌制文件不能在操作系统之间传输(大部分时间)。

I had a similar issue that my Python interpreter simply crashed when trying to load a pickled data frame with Pandas pd.read_pickle() .我有一个类似的问题,我的 Python 解释器在尝试使用 Pandas pd.read_pickle()加载腌制数据帧时只是崩溃了。 I solved it by updating Pandas with pip install -U pandas (now version 1.2.4).我通过使用pip install -U pandas (现在是 1.2.4 版)更新 Pandas 解决了这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM