if __name__ == "__main__": => doesn't work in freezed app with cx_Freeze V5.0

Issue #211 resolved
Harald Hanöfner
created an issue

My environment is Windows 10, python 3.5 and cx_Freeze 5.0.

The code

if __name__ == "__main__":
    ...

doesn't works in a freezed executable.

I have to change it to:

if __name__.endswith('__main__'):
    ...

That is, because the name of the executable is added internally at freezing.

Is that intended? How can we avoid the problem that above code doesn't works?

Comments (6)

  1. Harald Hanöfner reporter

    If the variable __name__ of the main module is not '__main__' another problem appears with pickle. If you have a class in your main module and you do pickle and unpickle it you have a different internal naming in pickle between the unfreezed and the freezed version of the app. For instance, if you pickle such a class with the unfreezed version of the app you will get an error if you want to unpickle it with the freezed version. That is, because in the freezed app the variable __name__ is module_name+'__main__' instead '__main__'!

    I think that behavior isn't good.

    My suggestion is to replace following code in the init scripts

    m = __import__("__main__")
    name, ext = os.path.splitext(os.path.basename(os.path.normcase(FILE_NAME)))
    moduleName = "%s__main__" % name
    scriptModule = __import__(moduleName)
    m.__dict__.update(scriptModule.__dict__)
    

    with this code

    import runpy
    
    ...
    
    name, ext = os.path.splitext(os.path.basename(os.path.normcase(FILE_NAME)))
    moduleName = "%s__main__" % name
    runpy._run_module_as_main(moduleName, alter_argv=False)
    

    The function runpy._run_module_as_main() runs the main module properly.

  2. Kjartan Fredrik Kvamme

    I'm having the same issue. Initially I thought cx_Freeze was just broken for python 3.5 as none of my apps gave any output when built with it, but then I found to my surprise that when I set up a test script with a print() in the root scope it actually printed it. It just never enters the main function because name is wrong.

    Hope this gets fixed so I can start using cx_Freeze 5.0 and Python 3.5.

  3. Kjartan F. Kvamme

    Yeah, it's an issue with cx_Freeze, so it would affect all Python versions. It's just that earlier versions of cx_Freeze don't work with Python 3.5 at all - for Python 3.4 you could use an earlier cx_Freeze version until it gets fixed.

  4. Log in to comment