【发布时间】:2019-07-19 00:01:30
【问题描述】:
在我的 Windows 10 机器上(似乎还有其他人的机器),Jupyter Notebook 似乎无法处理一些基本的multiprocessing 功能,例如pool.map()。我似乎无法弄清楚为什么会这样,即使已经建议了一种解决方案来调用要映射为来自另一个文件的脚本的函数。我的问题是 为什么 这不起作用?除了保存在另一个文件中之外,还有更好的方法来做这种事情吗?
请注意,该解决方案已在类似问题 here 中提出。但是我想知道为什么会出现这个错误,以及是否有另一个更简单的修复方法。为了说明出了什么问题,我在下面包含了一个非常简单的版本,它挂在我的计算机上,当使用内置函数 map 时,相同的函数运行没有问题。
import multiprocessing as mp
# create a grid
iterable = [3, 5, 10]
def add_3(iterable):
a = iterable + 3
return a
# Below runs no problem
results = list(map(add_3, iterable))
print(results)
# multiprocessing attempt (hangs)
def main():
pool = mp.Pool(2)
results = pool.map(add_3, iterable)
return results
if __name__ == "__main__": #Required not to spawn deviant children
results = main()
编辑:我刚刚在 Spyder 中尝试过这个,我已经成功地让它工作了。不出所料,运行以下命令不起作用。
if __name__ == "__main__": #Required not to spawn deviant children
results = main()
print(results)
但是按以下方式运行它确实有效,因为 map 使用 yield 命令并且在调用之前不会被评估,这会给出典型的问题。
if __name__ == "__main__": #Required not to spawn deviant children
results = main()
print(results)
编辑编辑:
从我读到的关于这个问题的内容来看,事实证明这个问题很大程度上是因为 jupyter 使用的 ipython shell。我认为设置 name 可能存在问题。无论使用 spyder 还是其他 ide 都可以解决问题,只要您不在 iPython shell 中运行多处理功能。
【问题讨论】:
标签: python-3.x jupyter-notebook python-multiprocessing