如果__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之后,发生了非常奇怪的事情,代码开始无限循环,就像在我编译它之后,将这些进程视为主要会话一样,这意味着在{{1 }}进程被视为主要

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

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

解决方法

冻结为Windows可执行文件时,需要适当地use 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的“叉状”行为multiprocessing所依赖的在启动具有相同可执行文件的子进程时不知道在哪里停止执行代码。

,

它是一个字符串:

if __name__ == "__main__":
    pass

请注意双引号而不是__main__作为对象(?)。

,

我真的不知道为什么它在那里没有引发错误,但是__main__应该是字符串'__main__'

,

您必须将repo.local.dir=/PATH/TO/DIR def fill_in_numbers(lst): i=0 while True: if lst[-1] - lst[i] !=1: if lst[i]+1 not in lst: lst.insert(i+1,lst[i]+1) i+=1 if lst[-1] - lst[i]== 1: break return lst def fill_in_numbers(lst): return list(range(lst[0],lst[-1]+1))

进行比较
__name__