PyQt5 beginner test record (three): Pyinstaller packaging summary

Foreword : This record is a simple note during the author's self-study process. It explains the process from installing the library to finally packaging it into .exe. It is divided into three parts for beginners to refer to and exchange. Please readers if there are errors in the description. For advice, the third part of the list is below.

One, Pyinstaller packaging process

I have previously made a tool based on PyQt5 (see PyQt5 beginner test record for details ). In order to try to run on other computers without python-related environment, it needs to be packaged into an .exe file. After searching a lot of information, pyinstaller is recommended because it is easy to use. . But... the actual experience of TAT is extremely poor, probably due to personal talent and lack of learning, leading to the delay in solving various minor problems. After the needs are basically met, it is still time to write a summary and review, Let's go!

First install pyinstaller, enter the command on the command line:

pip install pyinstaller

After the installation is complete and it shows successful, you can start the packaging work, then enter on the command line:

cd /d Drive letter:\The directory of the packaged file

Enter the directory where the packaged xxx.py file is located, such as e:\filepath , and enter:

pyinstaller -w -D xxx.py

-wIt means that the packaged .exe will run without a Shell window. It -Dmeans that it will be packaged into a directory or folder, which contains an .exe and other related files. Generally, projects with multiple directories and multiple files are packaged in this way. A single .py can with -Fparameters;

After the packaging is completed, two folders, build and dist, and a xxx.spec file (used to configure packaging rules) will be generated in the root directory of xxx.py , and the generated .exe will be in the subdirectory of dist. Before ensuring that it is foolproof, it is recommended to call from the command line instead of double-clicking the .exe directly. This will prevent the program from crashing when an error occurs, and the error information can be displayed in the Shell for easy debugging.
【figure 1】

Execute again after modifying xxx.spec :

pyinstaller -w -D xxx.spec

2. Problems encountered in packaging (not completely resolved)

Let's take a look at the possible problems:

1、No moudle named

Pyinstaller will automatically search for the dependencies of xxx.py when packaging, but there are always deficiencies in foolish operations. It may still not find what it needs. At this time, the above configuration file xxx will be used . spec , the Analysis method to modify the file is as follows:

a = Analysis(['MainFunction.py',
              'E:\\NewSysCrawler\\GUI_Call\\MyCrawler.py',
              'E:\\NewSysCrawler\\GUI_Call\\getdetails.py',
              'E:\\NewSysCrawler\\GUI_Call\\getbase.py',
              'E:\\NewSysCrawler\\QtFile\\getXlsxWidget.py',
              'E:\\NewSysCrawler\\QtFile\\mainWidget.py'],
             pathex=['E:\\NewSysCrawler','E:\\NewSysCrawler\\venv\\Lib\\site-packages'],
             binaries=[],
             datas=[],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher,
             noarchive=False)

The first [] is the packaged xxx.py (the author’s is MainFunction.py ), continue to add the path of other .py files in the project, and note that the separator is a double slash \\. The second pathex is the search path when packaging, add the path of the library that the project depends on. In addition, data is other file data (or third-party .dll) used in the project. The author used other methods for association, so it is not filled in. In this way, the first wave of problems should be resolved.

2、No such file or directory

Local files related to the execution of the program ( such as the cookie required by the author’s crawler tool will load the history from the local .txt ). If there is no setting in the datas, this problem may occur. The author’s solution is to directly put the required files (folder) on the root .exe generated, in the source code to be noted that the specified path, such .\Filesas Filepath .exe file in the root directory folder ..\OtherFilesto another .exe files in a folder parent directory;

3、Permission deniede

Editing so far, the author has forgotten the circumstances under which this error occurred...It was solved inexplicably. It seems that there is insufficient permission. It is speculated that the author's crawler tool will output a .txt of the crawled data to the specified directory, but the directory where it is located does not exist. You can modify the code to create the directory ( or it should also be resolved in the above datas) ):

result =str(html.text) # 爬虫获取的内容
dirs = '..\\OtherFiles'
if not os.path.exists(dirs): # 判断目录是否存在,不存在则创建
    os.mkdir(dirs) # 
# open无法打开/创建不存在的目录,但可以自动新建.txt 
with open(dirs+"\\"+txt,'a',encoding="utf-8-sig") as file_handle:      
    file_handle.write(result)   # 写入

4、Not enough values to unpack

Check the parameter format input by pyinstaller;

5. The icon of .exe is displayed abnormally

The most troublesome problem with Pyinstaller is that it has certain requirements for icon settings and the windows system itself also has requirements for icons ( but I haven't figured out the details so far... ), the author has tried repeatedly and still failed to achieve the desired effect, which is used when packaging The parameters are:

pyinstaller -w -D xxx.py -i e:\icons\myIcon.ico

Pyinstaller can only process .ico files for setting icons. The following code can generate icon files of various sizes at one time (or use tools such as Png2Ico, Format Factory, or download on the icon website):

from PIL import Image

image_size = [128,64,48,32,16]
def create_icon():
    for size in image_size:
        pri_image = Image.open("Icon.png")
        pri_image.resize((size, size), Image.ANTIALIAS).save("Icon_%d.ico" % (size))

if __name__ == "__main__":
    create_icon()

The icon of the generated .exe is still not displayed ( not necessarily, it may succeed )! So I switched to shortcuts and manually changed the icons, but the shortcuts became invalid on other computers. After that, the author tried to write a launcher, specifically used to call the previously generated .exe, the code is as follows:

import os

def main():
    os.chdir(".\\NewSysCrawler20.4.23") # 更改工作目录
    os.system('NSCrawler.exe') # 执行

if __name__ == "__main__":
    main()

Use os.system()open while running the .exe Shell window, then switch to:

subprocess.call('NSCrawler.exe')

Also use pyinstaller to package the launcher's .py, and set the icon when packaging the launcher ( wow the icon is successfully displayed! ), and finally it becomes the situation where runNSC.exe is used to call the original tool's NSCrawler.exe in the original packaging directory ;
【figure 2】

At this point, the icon problem is barely resolved ( later found that the packaged single file seems to be successful... ).

In addition, I recommend Greenfish Icon Editor Pro, an icon drawing tool. Students who want to design patterns by themselves can try it (the author's crawler tool icon was originally a claw drawn by sai ).

6, antivirus software false positives

Probably because of os operation, think about how to optimize the code! ~

7. Compatibility

Programs written in 64-bit Python can only be run on other 64-bit computers after being packaged, and 32-bit computers can be run, but different systems such as XP/7/10 may also have problems ( I don’t understand the underlying things );

Three, about the migration of the Pycharm project

In addition to packaging and publishing, it is often necessary to transfer the entire project, change the directory on this machine or copy it to other computers. If you use Pycharm (or other IDE) for development, the most common problem is: importinvalidation;

In the case of Pycharm, first copy the project to other computers or import other people’s projects on this computer. After importing the project through open, open Settings in the upper left menu:

Method 1: Reinstall the relevant libraries (it will be time-consuming if there are many dependencies);

Method 2: If the venv directory is attached to the copied project, and Lib\site-packages contains the dependent libraries, then set the current python interpreter to Scripts\python.exe in the venv directory . The figure shows the interpreters for two different projects, NewSysCrawler and PyProjects. In different projects, they will search for packages in the corresponding site-packages.
【image 3】

The same is true for migrating projects on this machine, as long as the working environment is changed, the import path of related libraries can be automatically updated. If it is a .py written by import, right-click on the project folder on the left and click Mark Directory as-Source root.

Four, summary

1. cmd command:
cd /d X:\filedir enter the directory and
cd ..\return to the upper directory;

2. pyinstaller parameters:
-D package into a directory structure ( -Fpackage single file),
-iset the .exe icon,
-wand run without window;

3. Points to note: path designation, dependent files (folders);

4. Reference source:
Pyinstaller packaging and publishing experience summary
python project packaging (custom dll) anaconda3+pyinstaller
zoom implementation in Python pictures, and the generation of icons of various sizes.
Use PyQt5 to develop visual crawler software
PyInstaller packaging practical guide

5. Postscript:
From the development of interface tools to packaging, I really benefited a lot. As a novice, I learned a lot. However, I found that there are still many shortcomings in the review of the writing. Some irregular operations may not help the novice readers to "take the right way". It can only be said that it barely meets the personal functional needs. Haha, future sharing needs to strengthen professionalism and Be rigorous, add fuel to yourself! Later, the author discovered that qrc files can also be used for resource integration, so interested students can explore it by themselves. See you next time! ~

Guess you like

Origin blog.csdn.net/zohan134/article/details/106264783