首页 > 解决方案 > 如果 __name__ == __main__ 在编译后不起作用

问题描述

我实际上正在使用多处理库编写脚本,一切都在我的文本编辑器(VSC)中完美运行:

import multiprocessing

def example_func():
    print("This is a targeted function for multiprocessing")
    
if __name__ == "__main__":
    print("This is the main session, starting multiprocessing")
    multiprocessing.Process(target=example_func).start()

所以在我的文本编辑器中,当我运行代码时,它会输出:

This is the main session, starting multiprocessing
This is a targeted function for multiprocessing

但是在我使用 pyinstaller 将其编译为 .exe 之后,发生了一些非常奇怪的事情,代码开始无限循环,就像在我编译它之后,进程被认为是主会话,这意味着 inif __name__ == "__main__"进程被认为是main

请大家帮忙,我真的需要你们的帮助。

编辑:有些人告诉我添加字符串,我已经在我的脚本中将它作为字符串。我只是在这里没有很好地复制

标签: pythonpyinstallerpython-multiprocessing

解决方案


当您冻结到 Windows 可执行文件时,您需要适当地使用:multiprocessing.freeze_support

if __name__ == "__main__":
    multiprocessing.freeze_support()  # Required for PyInstaller
    print("This is the main session, starting multiprocessing")
    multiprocessing.Process(target=example_func).start()

没有它,Windows“类似fork”的行为multiprocessing依赖于在启动具有相同可执行文件的子进程时不知道在哪里停止执行代码。


推荐阅读