Jupyter 笔记本永远不会使用多处理(Python 3)完成处理

Jupyter 笔记本
我基本上在使用多处理模块,我仍在学习多处理的功能。我正在使用 Dusty Phillips 的这本书,这段代码属于它。

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 notebook 上)我看到以下内容

Process SpawnPoolWorker-5:
Process SpawnPoolWorker-1:
AttributeError: Can't get attribute 'prime_factor' on
我不知道为什么单元格永远运行不完?

已邀请:
似乎 Jupyter notebook 和不同 ide 中的问题是设计特征。因此,我们必须将函数 (prime_factor) 写入不同的文件并导入模块。此外,我们必须注意调整。例如,就我而言,我已将函数编码到一个名为 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 notebook 中我写了以下几行

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

要回复问题请先登录注册