gpt4 book ai didi

python-3.x - Jupyter notebook 永远不会使用多处理(Python 3)完成处理

转载 作者:行者123 更新时间:2023-12-03 13:28:17 26 4
gpt4 key购买 nike

enter image description here

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 笔记本上)我看到以下内容
Process SpawnPoolWorker-5:
Process SpawnPoolWorker-1:
AttributeError: Can't get attribute 'prime_factor' on <module '__main__' (built-in)>

我不知道为什么单元格永远不会结束运行?

最佳答案

似乎 Jupyter 笔记本中的问题与不同 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笔记本中我写了以下几行
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))

这解决了我的问题

enter image description here

关于python-3.x - Jupyter notebook 永远不会使用多处理(Python 3)完成处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47313732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com