Preface
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.
objective
Compile the whole python project into a single EXE or a single directory with EXE file under windows
tool
PyInstaller (windows, source code Python 3.6)
step
- New from? Dir.py under the root directory of the project
- 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("\\", "/")
- Freeze path (prevent relative path not found after compiling to exe)
- Path reference
-
import frozen_dir root_path = frozen_dir.app_path() path = os.path.join(root_path, default_path)
-
-
Create a new entry file main.py in the root directory
-
from test import main if __name__ == '__main__': main()
-
-
Create a new build.py file in the root directory
-
# -*- coding: utf-8 -*- import PyInstaller.__main__ import frozen_dir SETUP_PATH = frozen_dir.app_path() def build(): PyInstaller.__main__.run([ '--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 'main.py', # Entrance file ]) if __name__ == '__main__': build()
-
-
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 build.py file.