Jupyter Notebook永远不会完成使用多处理的处理(Python 3) [英] Jupyter notebook never finishes processing using multiprocessing (Python 3)

查看:428
本文介绍了Jupyter Notebook永远不会完成使用多处理的处理(Python 3)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我基本上是在使用多处理模块,但我仍在学习多处理功能.我正在使用达斯蒂·菲利普斯(Dusty Phillips)编写的书,而这则代码属于该书.

I am using multiprocessing module basically, I am still learning the capabilities of multiprocessing. I am using the book by Dusty Phillips and this code belongs to it.

import multiprocessing  
import random
from multiprocessing.pool import Pool

def prime_factor(value):
    factors = []
    for divisor in range(2, value-1):
        quotient, remainder = divmod(value, divisor)
        if not remainder:
            factors.extend(prime_factor(divisor))
            factors.extend(prime_factor(quotient))
            break
        else:
            factors = [value]
    return factors

if __name__ == '__main__':
    pool = Pool()
    to_factor = [ random.randint(100000, 50000000) for i in range(20)]
    results = pool.map(prime_factor, to_factor)
    for value, factors in zip(to_factor, results):
        print("The factors of {} are {}".format(value, factors))

在Windows PowerShell上(不在jupyter笔记本上),我看到以下内容

On the Windows PowerShell (not on jupyter notebook) I see the following

Process SpawnPoolWorker-5:
Process SpawnPoolWorker-1:
AttributeError: Can't get attribute 'prime_factor' on <module '__main__' (built-in)>

我不知道为什么该单元永远不会停止运行?

I do not know why the cell never ends running?

推荐答案

在Jupyter笔记本电脑中,问题似乎与设计理念不同.因此,我们必须将函数(prime_factor)写入另一个文件,然后导入该模块.此外,我们必须注意调整.例如,就我而言,我已将该函数编码到一个名为defs.py

It seems that the problem in Jupyter notebook as in different ide is the design feature. Therefore, we have to write the function (prime_factor) into a different file and import the module. Furthermore, we have to take care of the adjustments. For example, in my case, I have coded the function into a file known as defs.py

def prime_factor(value):
    factors = []
    for divisor in range(2, value-1):
        quotient, remainder = divmod(value, divisor)
        if not remainder:
            factors.extend(prime_factor(divisor))
            factors.extend(prime_factor(quotient))
            break
        else:
            factors = [value]
    return factors

然后在jupyter笔记本中我写了以下几行

Then in the jupyter notebook I wrote the following lines

import multiprocessing  
import random
from multiprocessing import Pool
import defs



if __name__ == '__main__':
    pool = Pool()
    to_factor = [ random.randint(100000, 50000000) for i in range(20)]
    results = pool.map(defs.prime_factor, to_factor)
    for value, factors in zip(to_factor, results):
        print("The factors of {} are {}".format(value, factors))

这解决了我的问题

这篇关于Jupyter Notebook永远不会完成使用多处理的处理(Python 3)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆