[Python] Introduction and use of pyinstaller

I. Overview

1 Introduction

pyinstaller is a third-party library that can package Python source files under Windows, Linux, Mac OS X and other operating systems. By packaging source files, Python programs can be run in an environment where Python is not installed, or as an independent Files are convenient to transfer and manage.

PyInstaller supports Python 2.7 and Python 3.3+. It can be used on Windows, Mac OS X and Linux, but it is not cross-platform, but if you want to package it into an .exe file, you need to run PyInstaller on the Windows system for packaging; to package it into a mac app, you need to run it on the Mac OS used.

2. Installation and update

Install: pip install pyinstaller
update:pip install --upgrade pyinstaller

Note:
1. The PyInstaller library will automatically install the PyInstaller command into the Python interpreter directory, which is the same as the pip or pip3 command path, so it can be used directly.
2. Running PyInstaller on Windows also requires PyWin32 or pypiwin32, of which pypiwin32 will be installed automatically when you install PyInstaller.

2. Basic use

1. Example of use

Syntax: pyinstaller option python source file path

Regardless of whether the Python application is a single-file application or a multi-file application, you only need to compile the Python program used as the program entry when using the pyinstaller command.

The PyInstaller tool is cross-platform, it can be used on both the Windows platform and the Mac OS X platform. The method of using the PyInstaller tool is the same on different platforms, and the options they support are also the same.

For example, if you open the terminal in the directory of the python source file,
picture
after the input is successful, it will appear
picture

2. Common options

picture

The above table lists only the common options supported by the pyinstaller module. If you need to know the details of the Pyinstaller options, you can view them through pyinstaller -h

3. Multi-file packaging

1. Concept

This is packaged using Windows. Of course, the packaging parameters of other platforms are similar. You can go to the official website to learn.

Here, we need to learn how to use pyinstaller to package multiple py files into one EXE file for our use:

First of all, we need to learn, what is multi-file?


Multi-file means that there is a main file, and the main file depends on the rest of the py files to run. We need to use the .spec file to connect through import

First, we create a directory structure:
picture

2. Specification documents

Then, learn a command:

pyi-makespec main.py  # 运行 pyinstaller ,以main.py为主文件,生成一个spec文件,作为一个标准

This specification file can also be written by yourself. At the same time, when generating the specification file, those parameters that are directly packaged can be used

After running, it generates a main.spec file in the running directory, the content of which is:

# -*- mode: python ; coding: utf-8 -*-


block_cipher = None  #设置 加密,需要安装tinyaes第三方库,最多16位字符,此处在使用--key= 会有变化


a = Analysis(
    ['main.py'],  # 运行的所有py文件,包括依赖的py文件 
    pathex=[],  # 搜索导入的路径列表(此列表为项目绝对路径),包括选项给出的路径--paths,项目需要从什么地方导入自定义库
    binaries=[],  # 脚本需要的非python模块,包括--add-binary选项给出的名称,二进制数据
    datas=[],  # 应用程序中包含的非二进制文件,包括--add-data选项给出的名称,项目需要用到什么数据,比如图片,视频等。里面格式为tuple,第一个参数是文件路径,第二个是打包后所在的路径,其为一个元组:('image/*.png','data/image')
    hiddenimports=[],   # 假如打包后打开exe显示module not found,就要把该库添加到hiddenimports里面了
    hookspath=[],  
    hooksconfig={
    
    },  # 挂钩配置选项由一个字典组成
    runtime_hooks=[],  
    excludes=[],  # 假如你用的python有很多库,但是你不需要用到某个,那么就把它添加到里面去,可以压缩文件大小
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,  # 打包成EXE的脚本文件
    # a.binaries,  # 如果是单文件模式,则需要添加;多文件也可以添加
   	# a.zipfiles,
    # a.datas,
    [],
    exclude_binaries=True,  # 是否排除二进制文件,为True时,为排除二进制的文件,当文件交大时包含二进制文件运行较快,如果是单文件,则没有这个选项
    name='main',  # 打包程序的名字
    debug=False,  # 是否启用调试功能
    bootloader_ignore_signals=False,
    # runtime_tmpdir=None,  # 生成单文件时需要这个参数,定义运行时的临时文件夹
    strip=False,
    upx=True,  # 打包的时候进行压缩,False表示不压缩;要用到一个压缩程序UPX,用于压缩文件,需要单独下载
    console=True,  # 打包后的可执行文件双击运行时屏幕会出现一个cmd窗口,不影响原程序运行,等于是是否加-w参数
    disable_windowed_traceback=False,  
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
    
    """添加选项,初始化时没有的"""
    icon="",  # 指定应用程序的图标,传入路径,可以相对路径
    
)
coll = COLLECT(
    """
    如果是单文件模式,不需要这个COLLECT类,同时需要将:
        a.binaries,
    	a.zipfiles,
    	a.datas,
    这些数据文件添加到EXE中
    """
    exe,
    a.binaries,
    a.zipfiles,
    a.datas,
    strip=False,
    upx=True,
    upx_exclude=[],
    name='main',
)

If you need a more detailed packaging syntax, you can go to the official document: https://pyinstaller.org/en/stable/index.html
In single-file mode, COLLECT is not called, and the EXE instance receives all scripts, modules and binary files
For Analysis, we mainly need to

  • script: write all py files
  • pathex: write the address of the project, and the address of the custom library
  • datas: address of static file data
  • binaries: Binary file address, if there is an error, or add it when needed

The rest are not commonly used, and running directly will not affect the normal execution of the program, but if you want to be more precise, it is recommended to modify them according to the above comments

3. Project packaging

Then, we need to package our project:

We first write the main.spec file:

# -*- mode: python ; coding: utf-8 -*-


block_cipher = None


a = Analysis(
    ['main.py', "demo1.py"],  
    pathex=["D:\\35005\\桌面\\demoTest"],
    binaries=[],
    datas=[("config\\*.json", "config")],
    hiddenimports=[],
    hookspath=[],
    hooksconfig={
    
    },
    runtime_hooks=[],
    excludes=[],
    win_no_prefer_redirects=False,
    win_private_assemblies=False,
    cipher=block_cipher,
    noarchive=False,
)

pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)

exe = EXE(
    pyz,
    a.scripts,
    a.binaries,
    a.zipfiles,
    a.datas,
    [],
    name='main',
    debug=False,
    bootloader_ignore_signals=False,
    strip=False,
    upx=True,
    upx_exclude=[],
    runtime_tmpdir=None,
    console=True,
    disable_windowed_traceback=False,
    argv_emulation=False,
    target_arch=None,
    codesign_identity=None,
    entitlements_file=None,
)

Here is the packaging of a single file. After the packaging is completed, we need to move the config folder to the same directory as the executable program, and then it can run successfully!

The directory structure after successful operation is:
picture
Finally, we can send the generated program to others for use!

Guess you like

Origin blog.csdn.net/weixin_45953322/article/details/128774685