Compiling python project into EXE

Posted by fodder on Thu, 19 Mar 2020 15:11:16 +0100


After python is compiled into an EXE file, it can be used independently. Pro testing, a complex python project contains multiple packages and multiple modules, which can generate exe files.


Compile the whole python project into a single EXE or a single directory with EXE file under windows


PyInstaller (windows, source code Python 3.6)


      1. New from? under the root directory of the project
        1. Freeze path (prevent relative path not found after compiling to exe)
          # -*- coding: utf-8 -*-
          import sys
          import os
          # Freeze paths, all paths are based on this, and can only be used after packaging
          def app_path():
              """Returns the base application path."""
              if hasattr(sys, 'frozen'):
                  # Handles PyInstaller
                  return os.path.dirname(sys.executable).replace("\\", "/")
              return os.path.dirname(__file__).replace("\\", "/")
      2. Path reference
        1. import frozen_dir
          root_path = frozen_dir.app_path()
          path = os.path.join(root_path, default_path)
      3. Create a new entry file in the root directory

        1. from test import main
          if __name__ == '__main__':
      4. Create a new file in the root directory

        1. # -*- coding: utf-8 -*-
          import PyInstaller.__main__
          import frozen_dir
          SETUP_PATH = frozen_dir.app_path()
          def build():
                  '--name=%s' % "main",  # Generated exe file name
                  ['--onedir', '--onefile'][0],  # Single directory or Single file
                  '--noconfirm',  # Replace output directory without asking for confimation
                  ['--windowed', '--console'][1],
                  '--add-binary=./python3.dll;.',  # External package introduction 
                  '--add-binary=%s' % SETUP_PATH + '/config/logging.yaml;config', # Configuration item
          '--add-data=%s' % SETUP_PATH + '/config/config.ini;config', # Separated by semicolons, the path to be added is in front and the directory to be added is in the back '--hidden-import=%s' % 'sqlalchemy.ext.baked',
          '--hidden-import=%s' % 'frozen_dir', # Manually add a package to handle module not found '', # Entrance file ]) if __name__ == '__main__': build()
      5. Run the build file. dist/main/main.exe in the root directory is an executable file. Double click to run it. If you want to run flash back, you can use cmd to run main.exe in the relevant path. For the missing package, add the hidden imports item in the file.   



Topics: Python Windows