在 Windows 10 上使用 python 3 部署的多处理 'Pool' 选项无法正常工作并出现错误

Multiprocessing 'Pool' option deployed with python 3 on windowns 10 not working giving error

我正在尝试为 Python 3 使用多处理库。模块已正确导入且未显示任何错误,但是在使用时出现错误。

这是我的代码:

from multiprocessing import Pool
import time

start_time = time.process_time()
p = Pool(10)

def print_range():
    for i in range(10000):
        print('Something')
end_time = time.process_time()
print(end_time-start_time)
p.map(print_range())

但是我得到这个错误:

ImportError: cannot import name 'Pool' from 'multiprocessing' (C: ...path file)

有没有人遇到过这个错误,有解决办法吗?谢谢

可能与安全导入有关 main。参见 this section in the documentation。具体来说,您需要像这样更改代码:

from multiprocessing import Pool
import time


def print_range():
    for i in range(10000):
        print('Something')

if __name__ == '__main__':
    start_time = time.process_time()
    p = Pool(10)
    end_time = time.process_time()
    print(end_time-start_time)
    p.map(print_range()) # incorrect usage

此外,您对map()的用法不正确。有关示例,请参阅文档,或改用 p.apply(print_range)