Example from documentaion doesn't work in Jupiter Notebook

笑着哭i 提交于 2021-01-29 05:11:41

问题


I had looked at the documentaion. And there was an example

from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(f, [1, 2, 3]))

The problem is: it is not working. I run this code in Jupiter Notebook cell. And this the cell doesn't raise any exception. But Jupiter's terminal does. And it says: AttributeError: Can't get attribute 'f' on <module '__main__' (built-in)>

As written here the problem may be because I don't use __name__ == '__main__' condition. But I do.

I had literally copy and paste example from the documention and it's not working. What should I do?


回答1:


I suspect you are running on Windows. If so, this is a known issue. See this article. You need to add your function f to a file, such as worker.py:

worker.py

def f(x):
    return x*x

Then you jupyter notebook code becomes:

from multiprocessing import Pool
import worker


if __name__ == '__main__':
    with Pool(5) as p:
        print(p.map(worker.f, [1, 2, 3]))


来源:https://stackoverflow.com/questions/63936096/example-from-documentaion-doesnt-work-in-jupiter-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!