我想在Python3中腌制和解开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内核上),然后应转移到主进程中。这是通过Queue
来腌制所有数据来完成的。
答案 0 :(得分:0)
我的解决方案不是将“图标”作为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)>