Python code is packaged into an executable file (exe)

Article directory

    • ▍Overview
    • ▍Method 1: Direct packaging from the command line
    • ▍Method 2: Use spec packaging
    • ▍Recommended learning resources
      • 1.Python learning route
      • 2.Basic learning of Python
        • 01. Development tools
        • 02.Study notes
        • 03.Learning videos
      • 3. A must-have manual for Python beginners
      • 4. A complete set of resources for data analysis
      • 5.Python interview highlights
        • 01.Interview materials
        • 02.Resume template

[Foreword]: After we develop a small project, we want to release the project for others to use. Usually, the code is packaged into an exe and then given to others, instead of letting others install the running environment and then run the bare code. This article introduces how to use the pyinstaller tool to package python into an exe that can be run directly.

▍Overview

Before introducing pyinstaller, let’s briefly introduce several other tools that can be used to package python code:

  • cx_Freeze: Can convert Python scripts into independent executable files, supporting multiple platforms.

  • PyInstaller: Can convert Python scripts (or modules) into a single executable file or directory, supporting multiple platforms.

  • PyOxidizer: Functionally similar to PyInstaller, but it can generate self-contained binaries that can be used across platforms.

  • Py2exe: Available only on Windows platforms, it can convert Python scripts into .exe executable files.

The steps for Pyinstaller to package code are:

  1. Use the pip install pyinstaller command to install the pyinstaller library.

  2. pyinstaller provides two packaging methods;

    Method 1: In the cmd terminal, enter the directory where the Python file to be packaged is located, and use the pyinstaller xxx.py command to package the code.

    Method 2: In the cmd terminal, enter the directory where the Python file to be packaged is located, use the pyi-makespec xxx.py command to generate the spec file, then modify the areas that need to be modified in the spec, and then use pyinstaller xxx.spec Command packaging code.

  3. After successful packaging using pyinstaller, two folders are generated:

    build folder: This is where temporary files are stored during the packaging process. These files include Python source code, packaging scripts, and some other intermediate files. After successfully packaging the application, this directory can be safely deleted.

    dist folder: This is where the final generated executable file and its dependencies are stored.

▍Method 1: Direct packaging from the command line

Using command line packaging is usually suitable for simple projects that do not require complex configuration or custom settings, and there is no need to frequently repeat packaging; assuming our python code is as follows, the file name is demo.py.

#demo.py
import os
path=os.getcwd()
print(f'Current file path: {<!-- -->path}')
os.system('pause')

Packaging steps:

1. Enter the directory where the demo.py file is located in the cmd terminal.
2. Terminal execution: pyinstaller -F demo.py

Instruction explanation:

pyinstaller
[-F/-D] # [Generate an executable file/generate a directory (containing multiple files) as an executable file]
[-w/-c] # [Remove command line pop-ups/display command line pop-ups]
-i icon.ico # Specify exe display icon
demo.py #Packaged python file

result:

After packaging is completed, two folders, build and dist, are generated in the directory where the demo.py file is located. The demo.exe in the dist directory is our packaged executable file. Click the demo.exe file and a small black window will pop up, indicating that the packaging is successful.

▍Method 2: Use spec packaging

Spec file packaging is suitable for larger and more complex projects, as well as when custom configurations and frequently repeated packaging are required; situations where .spec files need to be used for packaging include:

  1. There are data files that need to be packaged together

  2. Package the dynamic link library together

  3. Add runtime options

  4. If you want to generate multiple executable programs, separate the common modules for other calls.

Assume that our project file structure is as shown below.

PackingExe
|_ core
    |_ __init__.py
    |_ dict.txt
  |_ demo.py

demo.py file

def resource_path(relative_path):
    """ Get the absolute path of the resource file when running the exe"""
    base_path = getattr(sys, '_MEIPASS', os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_path, relative_path)

def main():
    print(f'Current file path: {<!-- -->os.getcwd()}')
    abs_path = resource_path('core/dict.txt')
    with open(abs_path, 'r', encoding='utf-8') as file:
        content = file.readline()
        print(content)
    os.system('pause')

if __name__ == "__main__":
    main()

The resource path function (resource_path) is explained here; when the exe is running, a temporary folder will be generated. Data resources other than code need to be obtained by accessing the temporary folder through sys._MEIPASS.

Packaging steps:

1. Enter the PackingExe directory in the terminal.
2. Generate spec file: pyi-makespec -F demo.py # Generate apec file, support -F, --key and other parameters, do not support --upx-dir
3. Modify the spec file
4. Execute the packaging command: pyinstaller demo.spec # Use spec file packaging, external parameters are not supported

How to edit spec file correctly?

The spec file mainly contains four categories:

  • Analysis class: Used to analyze dependencies between Python modules and package what is needed.

  • PYZ class: It is a binary file composed of multiple Python files. The PYZ file contains inside the entire program’s code and standard library, as well as all third-party libraries used in the script code.

  • EXE class: Specify relevant information about the executable file to be generated, such as name, platform, icon, etc.

  • COLLECT class: Used to collect all files that need to be included in the executable file and copy them to the build directory for packaging and deployment. In -F mode, there is no COLLECT class.

**Bold style**

The spec file used to package the PackingExe project is as follows:

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

block_cipher = None

a = Analysis(
    ['demo.py'],
    pathex=[],
    binaries=[],
    datas=[('core\dict.txt', 'core')],
    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='demo',
    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,
)

result:

After packaging is completed, two folders, build and dist, are generated in the directory where the demo.py file is located. The demo.exe in the dist directory is our packaged executable file. Click the demo.exe file and a small black window will pop up, indicating that the packaging is successful.

▍Possible reasons for packaging failure

  • When there is a bug in the program, the packaged exe will crash instead of reporting an error in a small black window;

  • The python interpreter path used for packaging cannot contain Chinese characters or spaces; if necessary, you can modify the python.exe path in the scripts/pyinstaller-script.py file in the python installation directory;

  • It is best to add # -*- coding:utf-8 -*- in the first line of the py file, otherwise the exe is prone to coding errors;

▍Recommended learning resources

In addition to the above sharing, if you also like programming and want to get a higher salary by learning Python, here is a Python learning material to share with you.

Here I will show you the screenshots of the recent orders I placed.

private order

If friends are in need, you can click the link below to get it or scan the QR code below to get it, or you can recommend to the part-time group~

CSDN spree, when the QR code expires, click here to receive it:[Collection of learning materials &Related tools&How to obtain PyCharm permanent version]< font color="#66cc66">

Learning Python well is good whether you are getting a job or doing a side job to make money, but you still need to have a learning plan to learn Python. Finally, we share a complete set of Python learning materials to give some help to those who want to learn Python!

1.Python learning route

image-20230619144606466

python learning roadmap 1

2.Basic learning of Python

01. Development tools

02. Study Notes

03. Learning video

3. Essential manual for Python beginners

image

4. Complete set of data analysis resources

5.Python interview highlights

01.Interview information

02.Resume template

CSDN spree, when the QR code expires, click here to receive it:[Collection of learning materials &Related tools&How to obtain PyCharm permanent version]< font color="#66cc66">


Due to limited space, only part of the information is shown. Add it above to get it




—— ?♂? This article is reproduced from the Internet. If there is any infringement, please contact us to delete it?♂? ——< /font>
syntaxbug.com © 2021 All Rights Reserved.