Python - create an EXE that runs code as written, not as it was when compiled

大兔子大兔子 提交于 2019-11-27 15:01:34

After some experiments I've found a solution.

  1. Create a separate folder source in the main folder of the application. Here will be placed source files. Also place file __init__.py to the folder. Lets name a main file like main_module.py.

  2. Add all of its contents as a data files to the py2exe configuration setup.py. Now after compiling the program, these files will be placed in the dist folder.

    data_files += [('source', glob('source/*.py'),)]
    setup(
          data_files=data_files,
          ....  # other options
         windows=[
              {
                "script": "launcher.py",
                "icon_resources": [(0, "resources/favicon.ico")]
              }
         )
    
  3. Make launcher.py - it's task is to import all system and required libraries like pygame, pyqt and so on. Then run you program:

    import sys, time, os, hashlib, atexit  # std modules
    import PyQt5, ...   # foreign libraries
    sys.path.insert(0, 'source')
    exec('import main_module')
    
  4. Now main_module.py will be imported, if it imports your modules, they will be imported too in their places in hierarchy. For example head of the main_module.py can be like this:

     import user_tweaks
     from user_data import parser
    

    These files user_tweaks.py and user_data.py should be located in source folder at appropriate paths relative to main_module.py.

You may change contents of source folder without recompilation program itself. Any time program runs it uses fresh contents of source.

As a result you have an application folder with:

  • A separate launcher - simple .exe file
  • All required modules
  • Your application with all its modules.
Eugene Lisitsky

Last summer I have been struggling with the same problem - build single .exe from python script. However there was no PyGame, but there was a PyQt5, which added some problems alike. None of the pure standard tools helped me.

Finally I'd solved the problem with a chaine: make + Py2exe + 7Zip + Resource Hacker. This set gave me single .exe with all the resources onboard, which don't require installaton - so you can put it everywhere on windows box and run.

Here's detailed article: exe built with cx_Freeze, PyQt5, Python3 can't import ExtensionLoader_PyQt5_QtWidgets.py and run

Please, feel free to ask any questions.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!