gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:38:03 30 4
gpt4 key购买 nike

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!

关于Python2.7 异常 "The "freeze_support( )"line can be omitted if the program",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29690091/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com