Python 3.4的多进程无法与py2exe兼容。

5
这与此问题基本相同:这个问题,但那里给出的解决方案(调用freeze_support())对我不起作用。
我有一个名为start.py的脚本,我使用它来使用py2exe(版本0.9.2.2)构建独立可执行文件。我还在同一目录中拥有python.exe。
import multiprocessing

def main():
    print('Parent')
    p = multiprocessing.Process(target=new_process)
    multiprocessing.set_executable('python.exe')
    p.start()
    p.join()

def new_process():
    print('Child')

if __name__ == '__main__':
    multiprocessing.freeze_support()
    main()

在纯 Python 环境下运行时,一切正常。但是,当打包为可执行文件时,会出现以下错误:

Unknown option: --
usage: <path to start.exe> [option] ... [-c cmd | -m mod | file | -] [arg] ...
Try `python -h' for more information.

这显然是因为调用了某个函数。
python.exe --multiprocessing-fork

如果我不调用set_executable()和freeze_support(),子进程将仅启动exe并作为__main__运行,导致无限的新进程打印“Parent”,而“Child”从未被打印。唯一调用freeze_support()所做的事情似乎是导致子进程引发以下错误,如果我不调用multiprocessing.set_executable():
Traceback (most recent call last):
  File "start.py", line 17, in <module>
    multiprocessing.freeze_support()
  File "C:\Python34\Lib\multiprocessing\context.py", line 148, in freeze_support

    freeze_support()
  File "C:\Python34\Lib\multiprocessing\spawn.py", line 67, in freeze_support
    main()
NameError: name 'main' is not defined

我正在使用运行在Windows 8.1 64位上的Python 3.4 32位。我已经尝试了所有使用cx-Freeze的方法,但都没有获得相同的结果。如果有帮助,将不胜感激。 编辑:即使使用这个直接从文档中复制的示例:
from multiprocessing import Process, freeze_support

def f():
    print('hello world!')

if __name__ == '__main__':
    freeze_support()
    Process(target=f).start()

当子进程调用freeze_support()函数时,我会收到相同的NameError错误。


我的工具pynsist可能会有用。它不会将您的代码制作成exe文件,因此您不需要任何特殊技巧来使多进程工作。它会构建一个安装程序,设置Python本身以及您的代码。 - Thomas K
1
我能够使用Python 2.7.9和py2exe 0.6.9使其工作,只要我删除了对set_executable的调用,但仍然调用freeze_support()。我的最佳猜测是,在Python 3中,freeze_support()的功能存在问题。 - Mobious
1个回答

2

尝试在文档中建议的修复方法:

multiprocessing.set_executable(os.path.join(sys.exec_prefix, 'pythonw.exe'))

还要注意,在生成任何新进程之前,您需要调用此函数


这给了我与我当前拥有的相同的结果。我尝试将set_executable移动到初始化进程之前,并在if _name_ == '_main_'之下,在调用freeze_support()之前和之后,所有这些都没有效果。 - Mobious
1
另外需要注意的一点是:在打包后的可执行文件中,sys.exec_prefix实际上是一个空字符串。如果我没有在工作目录中包含python.exe,由于multiprocessing找不到python.exe,我将会得到一个FileNotFoundError。 - Mobious
我曾经遇到过这个问题。与其使用 python.exe,你应该使用 pythonw.exe,这似乎解决了 Unknown option: -- 的问题。 - Jonathan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接