Skip to main content
 首页 » 编程设计

Python2.7 异常 "The "freeze_support( )"line can be omitted if the program"

2025年05月04日30cmt

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

请您参考如下方法:

当使用带有'spawn' 启动方法的多重处理时(默认在缺少fork 的平台上,比如windows),并且没有用if __name__ = '__main__' 守卫。

原因是使用 'spawn' 启动方法会生成一个新的 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!