Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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()

This code will throw a exception

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.

but after I add if __name__ == '__main__': freeze_support() It will throw anther exception, how to fix it? My os is window7

like image 805
lionyu Avatar asked Apr 17 '15 04:04

lionyu


1 Answers

This error message is displayed when using multiprocessing with the 'spawn' start method (default on platforms lacking fork like windows), and not protecting your code with a if __name__ = '__main__' guard.

The reason is that with the 'spawn' start method a new python process is spawned, which then in turn has to import the __main__ module before it can proceed to do it's work. If your program does not have the mentioned guard, that subprocess would try to execute the same code as the parent process again, spawning another process and so on, until your program (or computer) crashes.

The message is not ment to tell you to add the freeze_support() line, but to guard your program:

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!
like image 57
mata Avatar answered Nov 07 '22 15:11

mata