Python 3.4 多重处理不适用于 py2exe

2024-04-30

这与以下内容几乎相同这个问题 https://stackoverflow.com/questions/26001133/python-multiprocessing-process-executes-a-wrong-target-packaged-with-py2exe,但是那里给定的解决方案(调用 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”永远不会打印。

如果我不调用 multiprocessing.set_executable() ,调用 freeze_support() 的唯一作用似乎是导致子进程引发以下错误

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 尝试了上述所有操作,得到了相同的结果。任何帮助将非常感激。

编辑:即使使用这个例子直接从文档中取出 https://docs.python.org/3.4/library/multiprocessing.html#multiprocessing.freeze_support:

from multiprocessing import Process, freeze_support

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

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

当子进程调用 freeze_support() 时,我得到相同的 NameError 。


尝试建议的修复在文档中 https://docs.python.org/2/library/multiprocessing.html#multiprocessing.set_executable:

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

另请注意,您需要调用此方法before产生任何新进程。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 3.4 多重处理不适用于 py2exe 的相关文章

随机推荐