python - 如果 __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。
请大家帮忙,我真的需要你们的帮助。
编辑:有些人告诉我添加字符串,我已经在我的脚本中将它作为字符串。我只是在这里没有很好地复制
解决方案
当您冻结到 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
依赖于在启动具有相同可执行文件的子进程时不知道在哪里停止执行代码。
推荐阅读
- javascript - NodeJS 将数据从当前页面传递到另一个页面
- javascript - 在减少之后按字段分组在 JavaScript 中不起作用
- node.js - 没有从 Axios 和 curl 调用到特定站点的数据
- javascript - 如何使用socket.io nodejs以角度8打开弹出窗口
- c++ - 将原始文件添加到 .gitignore
- mysql - 使用 mysql 查询从日期、间隔和期间的集合中计算订阅结束日期?
- ios - 如何从 Swift 5 中的资产文件夹创建图像数组?
- c - 无效 *ptr = (int *)&a; 它不是对指针进行类型转换吗
- javascript - jQuery:选择标签期望一个ID
- c# - 选择要使用的 .NET Core 版本