简体   繁体   中英

if __name__ == __main__ not working after compilation

i'm actually working on a script using multiprocessing library, everything is working perfectly from my text editor ( 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()

so in my text editor when i run the code it output this :

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

but after I compile it to .exe using pyinstaller, something very strange happens, the code starts getting looped infinitely, its like if after i compiled it, the processes were considered as the main session, it means that in if __name__ == "__main__" processes were considered as main .

Please guys help, i really need your help.

EDIT : some guys told me to add string, I have already had it as a string in my script.I just didnt copy well here

You need to use multiprocessing.freeze_support appropriately when you're freezing to a Windows executable:

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

Without it, the Windows "fork-like" behavior multiprocessing relies on doesn't know where to stop executing code when it launches subprocesses with the same executable.

It is a string:

if __name__ == "__main__":
    pass

Note the double quotes instead of __main__ as an object (?).

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

You have to compare __name__ to string __main__

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM