在 Python3 中腌制一个 GdkPixbuf.Pixbuf 对象

Pickle a GdkPixbuf.Pixbuf object in Python3

我想在 Python3 中 pickle 和 unpickle 一个 GdkPixbuf.Pixbuf。更具体地说,Python3 的 multiprocessing 包需要这样做,因为我通过 Queue.

在进程之间共享这些对象

问题是对象从

<GdkPixbuf.Pixbuf object at 0x7f8b9e9cfb88 (GdkPixbuf at 0x563b61725c60)>

<GdkPixbuf.Pixbuf object at 0x7f8b9e9eaea0 (uninitialized at 0x(nil))>

这是最小的工作示例。

>>> import gi
>>> from gi.repository import GdkPixbuf
__main__:1: PyGIWarning: GdkPixbuf was imported without specifying a version first. Use gi.require_version('GdkPixbuf', '2.0') before import to ensure that the right version gets loaded.

>>> pf = GdkPixbuf.Pixbuf.new_from_file('_icon.png')
>>> pf
<GdkPixbuf.Pixbuf object at 0x7f8b9e9cfb88 (GdkPixbuf at 0x563b61725c60)>

>>> import pickle
>>> pickle.dump(pf, open('p', 'wb'))

>>> pb2 = pickle.load(open('p', 'rb'))
>>> pb2
<GdkPixbuf.Pixbuf object at 0x7f8b9e9eaea0 (uninitialized at 0x(nil))>

我看不出有其他腌制方法。图标需要在一个单独的进程中加载​​(在不同的 CPU 内核上,然后是应用程序 main/first 进程),然后应该转移到主进程。这是通过 Queue 来完成的,它会腌制所有数据。

我的解决方案不是将 "icon" 作为内存中的 Pixbuf 对象,而是作为我从文件中读取的原始字节。

解开这些字节后,我将它们转换为 Pixbuf

>>> import gi
>>> from gi.repository import GdkPixbuf, Gio, GLib
__main__:1: PyGIWarning: GdkPixbuf was imported without specifying a version first. Use gi.require_version('GdkPixbuf', '2.0') before import to ensure that the right version gets loaded.
>>> with open('_icon.png', 'rb') as f:
...     icon_bytes = f.read()
... 
>>> 
>>> import pickle
>>> pickle.dump(icon_bytes, open('p', 'wb'))
>>> 
>>> pb = pickle.load(open('p', 'rb'))
>>> pb = GLib.Bytes(pb)
>>> pb = GdkPixbuf.Pixbuf.new_from_stream(Gio.MemoryInputStream.new_from_bytes(pb))
>>> pb
<GdkPixbuf.Pixbuf object at 0x7fc0858ac5e8 (GdkPixbuf at 0x55e0d8d08b60)>