Windows freeze_support Error: An attempt has been made to start a new process

3,650 阅读1分钟

这个错误相信很多人都碰到过,就是,在Linux中可以很好运行的代码,在Windows中会给出这样的错误。

究其原因,往往出现在multiprocess上。当程序中调用 multiprocess函数,却不是在main中时,会出现这样的报错。

在stackoverflow上

stackoverflow.com/questions/1…

有这样的原因说明:

On Windows the subprocesses will import (i.e. execute) the main module at start.

minerl.io/docs/notes/…

也有详细的解释,怕翻译不准确,大家还是看英文原文吧!

The freeze_support error (multiprocessing)

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.

The implementation of multiprocessing is different on Windows, which uses spawn instead of fork. So we have to wrap the code with an if-clause to protect the code from executing multiple times. Refactor your code into the following structure.

import minerl
import gym

def main()
    # do your main minerl code
    env = gym.make('MineRLTreechop-v0')

if __name__ == '__main__':
    main()


大致解决方案就是: 写一个main函数,然后在if __name__ == '__main__':中运行这个main函数。

把那些引用multiprocessing的函数作都放到main()函数里去执行就OK了。