【问题标题】:Example from documentaion doesn't work in Jupiter Notebook文档示例在 Jupyter Notebook 中不起作用
【发布时间】:2020-09-17 10:26:25
【问题描述】:

我看过文档。还有一个例子

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]))

问题是:它不工作。我在 Jupiter Notebook 单元中运行此代码。这个单元格不会引发任何异常。但木星的终点站确实如此。它说:AttributeError: Can't get attribute 'f' on <module '__main__' (built-in)>

正如here 所写,问题可能是因为我没有使用__name__ == '__main__' 条件。但我愿意。

我从文档中复制并粘贴了示例,但它不起作用。我该怎么办?

【问题讨论】:

    标签: python multithreading jupyter-notebook


    【解决方案1】:

    我怀疑您在 Windows 上运行。如果是这样,这是一个已知问题。见this article。你需要将你的函数f添加到一个文件中,比如worker.py

    worker.py

    def f(x):
        return x*x
    

    那么你的 jupyter notebook 代码就变成了:

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

    【讨论】:

      猜你喜欢
      • 2023-04-02
      • 2017-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多