我正在try 在一个更大的Python类中运行一个多进程作业(job).在一个简单的形式中,类如下所示:

class Thing:
    def test(self):
        with mp.Pool() as p:
            yield from p.map(str, range(20))

当我将此类导入到脚本时,例如:

from x import Thing

t = Thing()
for item in t.test():
    print(item)

我遇到了一个众所周知的问题:

RuntimeError:
        An attempt has been made to start a new process before the
        current process has finished its bootstrapping phase.

        This probably means that you are not using fork to start your
        child processes and you have forgotten to use the proper idiom
        in the main module:

            if __name__ == '__main__':
                freeze_support()
                ...

        The "freeze_support()" line can be omitted if the program
        is not going to be frozen to produce an executable.

我的问题是,我如何防止这种行为,而不要求我的类的用户编写

if __name__ == "__main__":

每次他们运行我的类函数?有没有一种方法可以在类定义中执行此操作?

我试过写作

from x import Thing

t = Thing()
if __name__ == "__main__":
    for item in t.test():
        print(item)

这解决了问题,但我不希望这成为用户与这个类交互的方式.

推荐答案

由于所派生的子进程的主模块中的值__name__'__mp_main__'(如所讨论的here),因此您可以在派生子进程的函数中设置保护,方法是判断是否有任何祖先的框架在全局名称空间中具有值为'__mp_main__'__name__,在这种情况下,当前进程是子进程,并且执行应该停止,以便不再派生更多的子进程:

# x.py
import sys
import multiprocessing as mp

class Thing:
    def test(self):
        frame = sys._getframe(1)
        while frame:
            if frame.f_globals['__name__'] == '__mp_main__':
                return
            frame = frame.f_back
        with mp.Pool() as p:
            yield from p.map(str, range(20))

Python相关问答推荐

将numpy矩阵映射到字符串矩阵

强制venv在bin而不是收件箱文件夹中创建虚拟环境

如何从FDaGrid实例中删除某些函数?

Pandas 填充条件是另一列

Pandas 第二小值有条件

pandas DataFrame GroupBy.diff函数的意外输出

使用FASTCGI在IIS上运行Django频道

Python daskValue错误:无法识别的区块管理器dask -必须是以下之一:[]

连接两个具有不同标题的收件箱

在Python中处理大量CSV文件中的数据

log 1 p numpy的意外行为

在Mac上安装ipython

如何在表中添加重复的列?

如何在turtle中不使用write()来绘制填充字母(例如OEG)

寻找Regex模式返回与我当前函数类似的结果

从列表中获取n个元素,其中list [i][0]== value''

使用python playwright从 Select 子菜单中 Select 值

数据框,如果值在范围内,则获取范围和

为什么dict. items()可以快速查找?

Seaborn散点图使用多个不同的标记而不是点