在 Windows 10 的 Visual Studio Code 笔记本中运行时,python并发.futures.ProcessPoolExecutor 会导致 BrokenProcessPool 错误

问题描述 投票:0回答:1

concurrent.futures.ProcessPoolExecutor()

官方文档
中的示例代码:

import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()

在 ubuntu 系统中的 jupyter 笔记本中运行没有任何问题,但失败并显示 “BrokenProcessPool:进程池中的进程在 future 正在运行或挂起时突然终止。” Visual Studio Code 中的 jupyter 笔记本中出现错误在 Windows 10 系统中。
“Python 3.10.10 | 由 Anaconda, Inc. 打包 | (主要,2023 年 3 月 21 日,18:39:17)[MSC v.1916 64 位 (AMD64)] 在 win32 上”

我查阅了几篇讨论此问题的帖子。
所以是的,我从这篇文章和我自己的测试中知道,我可以将代码放入 .py 脚本中并从笔记本中调用它。这有效。
是的,我(模糊地)知道 Windows 在创建进程、线程等方面的行为与其他系统不同; 这篇文章简要提到了它;但似乎没有结论/解决方案。

因此,重点仍然是:鉴于据称该代码应该在 Windows 中运行,是否可以采取任何措施来运行该代码按照官方文档,在 jupyter 笔记本中,在 Visual Studio Code 中,在Windows 10?

与在笔记本单元中运行代码相比,使用单独的 .py 脚本有很多不便。

在我看来很奇怪的是,官方文档应该有明显无法在主要操作系统中工作的代码,迫使每个遇到此错误的人去寻找解决方法并找到N种不同且相当不方便的解决方案。除非我的Python安装或设置有问题,但大多数其他代码都可以正常工作,所以...
顺便说一句,作为记录,我也尝试了一些建议使用

multiprocessing
Pool
和类似的解决方案;这导致笔记本电池永远冻结。


编辑经过大量进一步浏览后,我找到了一个可能的解决方案,仍然允许在笔记本中运行多处理部分,仅将worker函数移动到.py

https://medium.com/@grvsinghal/speed-up-your-python-code-using-multiprocessing-on-windows-and-jupyter-or-ipython-2714b49d6fac

上面帖子中显示的示例适用于 Visual Studio Code。

我想对于

concurrent.futures.ProcessPoolExecutor()
中的示例,必须将
is_prime
的定义移至 .py 并导入它;不确定
with
部分。有待尝试。


编辑2

是的,它有效。请参阅下面我的回答。

python jupyter-notebook parallel-processing
1个回答
0
投票

根据我的OP中的编辑,并解释如下:

https://medium.com/@grvsinghal/speed-up-your-python-code-using-multiprocessing-on-windows-and-jupyter-or-ipython-2714b49d6fac

解决方案是将“worker”函数移动到单独的.py中,然后可以在我描述的环境中从笔记本运行多处理代码。

因此官方文档中的代码将在 Visual Studio Code、Windows 10 中运行,前提是:

1.这段代码:

import math

def is_prime(n):
    if n < 2:
        return False
    if n == 2:
        return True
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

保存在

worker_function_definition.py
找到的目录中的
sys.path
文件中,并替换为:

import worker_function_definition

2.这段代码:

executor.map(is_prime, PRIMES)

替换为:

executor.map(worker_function_definition.is_prime, PRIMES)

我希望通过在这里发布此内容可以减轻其他用户的痛苦。
发布该解决方案的人很好地总结了这种情况(请参阅他在哪里写“你曾经尝试过吗......”)。显然不仅仅是我。
也许有一天,有人会怜悯我们可怜的 Windows 用户,并在官方文档中提到这个小但哦如此重要的细节。

© www.soinside.com 2019 - 2024. All rights reserved.