Python2.7异常“如果程序”,则可以省略“freeze_support()”行“

时间:2015-04-17 04:08:12

标签: python

import Queue
from multiprocessing.managers import BaseManager

BaseManager.register('get_queue', callable=lambda:  Queue.Queue())

manager = BaseManager(address=('', 5000), authkey='abc')
manager.start()
manager.shutdown()

此代码将引发异常

RuntimeError: 
        Attempt to start a new process before the current process
        has finished its bootstrapping phase.

        This probably means that you are on Windows 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 a Windows executable.

但在我添加if __name__ == '__main__': freeze_support()之后 它会抛出另一个异常,如何修复它? 我的操作系统是window7

1 个答案:

答案 0 :(得分:6)

使用'spawn'启动方法进行多处理时会显示此错误消息(默认情况下,在缺少fork窗口的平台上),而不是使用if __name__ = '__main__'警卫来保护您的代码。

原因是使用'spawn' start方法生成一个新的python进程,然后它必须导入__main__模块才能继续执行它。如果您的程序没有提到的防护,那么该子进程将尝试再次执行与父进程相同的代码,生成另一个进程,依此类推,直到您的程序(或计算机)崩溃。

该消息并不是告诉您添加freeze_support()行,而是为了保护您的程序:

import Queue
from multiprocessing.managers import BaseManager

def main():
    BaseManager.register('get_queue', callable=lambda:  Queue.Queue())

    manager = BaseManager(address=('', 5000), authkey='abc')
    manager.start()
    manager.shutdown()

if __name__ == '__main__':
    # freeze_support() here if program needs to be frozen
    main()  # execute this only when run directly, not when imported!