Pyinstaller packaging FAQ
"TLDR: This article introduces common problems and solutions encountered when using PyInstaller to package Python programs. First, the article provides an explanation of the basic commands and parameters of PyInstaller, such as -Fw for generating a single executable file and hiding the console window, and --add-data for adding resource files. Next, the article discusses two main problems: one is the problem that the packaged program is too large due to the use of Anaconda, which is recommended to be solved by creating a virtual environment and installing only necessary libraries; the other is the problem of missing resource files after packaging, and two solutions are proposed: one is to write a hook script to specify the resource folder or file that needs to be included; the other is to use the --add-data option to directly specify the data path and target location to be added in the command line."
Common commands
pyinstaller -Fw main.py --add-data "source address; target address"
-F is the main file, -w means that the command line does not appear, and --add-data mainly adds resource files.
FAQ
The size is too large due to the use of anaconda
pyinstaller will not package libraries on demand, but will directly package all libraries in the environment into exe. Therefore, in order to only package the required libraries, you can use virtualenv to create a new virtual environment, where only the required libraries will be installed and finally packaged.
Resource files are missing after packaging
Generally speaking, the resource files used by some libraries will not be packaged by pyinstaller, and an error will be displayed when running.
There is a solution on the Internet that is to add the "hook-xxx.py" file and put it in the hooks folder of pyinstaller. The content is generally as follows:
from PyInstaller.utils.hooks import collect_data_files
datas = collect_data_files('jieba') # Note that this is the name of the library, not the name of the missing resource file
When running the exe generated by pyinstaller, it will be in C:\Users\xxxx\AppData\Local\Temp\_MEI367082 A similar place stores all running files, so the hook file above means to put jieba's entire library in this _MEI367082 folder. This can certainly solve the problem of jieba's resource files not being recruited. However, it seems that putting an entire jieba library (30MB) in order to find a stopwords.txt (5MB) is not worth the gain.
What if add-data is used? For example, run
pyinstaller main.py \
-i "res\logo.ico" \
--add-data=".\*.txt;." \
--add-data=".\*.json;."\
--add-data="res\*.*;.\res"\
--add-data="dist\models\*.*;.\models"
The above method can be solved very well. Pay attention to the writing method of adding multiple resource files, the writing method of adding icons, and the most important writing method of the location of resource files "source address; target address"