我正在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)
这解决了问题,但我不希望这成为用户与这个类交互的方式.