Python 使用多处理构建字典

标签 python dictionary tkinter multiprocess

我对多处理模块还很初学者。在我的代码中,我尝试使用给定路径中的图像构建字典。我编写了以下代码:

from multiprocessing import Pool
from PIL import Image, ImageTk
import glob

def process(path):
    print path
    im=ImageTk.PhotoImage(Image.open(path).resize((600, 600), Image.ANTIALIAS))
    name = (path.split('/')[1]).split('.')[0]
    return (name, im)

p = Pool(4)
input = glob.glob('./*.jpg')
image_list = dict(p.map(process, input))

如果代码正常工作,我会期望类似以下内容:

{'-22': PIL.ImageTk.PhotoImage object at 0x7f6b66507150,

'-23': PIL.ImageTk.PhotoImage object at 0x7f6b66507190, ... and so on}

...但我收到以下错误:

`multiprocessing.pool.MaybeEncodingError: Error sending result:`
`'[('-51', PIL.ImageTk.PhotoImage object at 0x7f6b664f6990),`
`('-47', PIL.ImageTk.PhotoImage object at 0x7f6b664f6fd0),`
`('-54', PIL.ImageTk.PhotoImage object at 0x7f6b66507050),`
`('-13', PIL.ImageTk.PhotoImage object at 0x7f6b665070d0),`
`('-45', PIL.ImageTk.PhotoImage object at 0x7f6b66507110),`
`('-49', PIL.ImageTk.PhotoImage object at 0x7f6b66507150),`
`('-48', PIL.ImageTk.PhotoImage object at 0x7f6b66507190),`
`('-26', PIL.ImageTk.PhotoImage object at 0x7f6b665071d0),`
`('-10', PIL.ImageTk.PhotoImage object at 0x7f6b66507210)]'.`
`Reason: 'UnpickleableError(tkapp object at 0x7f6b67c88e30,)'`

我该如何解决这个问题?

最佳答案

多处理不是线程。这是一个完全独立的过程,有自己的解释器。这有一些优点 - 您不会意外创建共享可变状态,这很棒!但它有一些缺点 - 这是其中之一。

所有传入或传出多处理进程的数据结构都必须进行序列化/反序列化。因此,该函数的返回值必须在幕后进行腌制 - 正如您所看到的,这是不可能的。

根据您当前的设计,使用线程而不是多处理。

关于Python 使用多处理构建字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47720439/

相关文章:

python - 如何在 GUI 程序中对齐标签和输入框?

python - 如何使用 Pillow 显示图像?

python多维列表..如何抓取一维?

python - 如何在 python 中为 OrderedDict 列表中的重复值抛出 AssertionError

python - 列表到列表字典(Python 优化)

ios - 我们可以使用 google api 绘制路线(没有多段线)吗?

python - 如何分别控制两个不同的对象(两人乒乓球游戏)?

python - 在 Jupyter Notebook 中使单元格彼此独立

python - Pandas 日期和文本条件

python - 使用其索引对 Pandas Dataframe 列进行操作