pyinstaller for python packaging (packaged into exe)

1. Install pyinstaller

Direct pip online installation

pip install pyinstaller

2. Instruction introduction

common command

-h,–help View the help information for this module
-F,-onefile generate a single executable
-D,–onedir Generate a directory (contains multiple files) as an executable program
-w,–windowed Specifies that the command line window should not be displayed when the program is running (only valid for Windows)

It is recommended to generate a directory and remove the black box.
Generate a directory, which is less prone to errors.
If a single file is generated, if the third-party library is large in size, the final generated exe will be particularly large.

pyinstaller -D -w 源程序.py

3. Packing

3.1 Keep the black frame

1. Create the main.py program, in order to prevent the console window from flashing, and wait for 5s

from time import sleep


def print_hi(name):
    print(f'Hi, {
      
      name}')


if __name__ == '__main__':
    print_hi('PyCharm')
    sleep(5)

file structure:
insert image description here

2. Package
pycharm and switch to the terminal, then drop down on the right side of the "+" sign and select "Command Prompt". At this time, there will be (venv) in front of the command prompt, indicating that it is currently in a virtual environment.
The terminal opens locally by default, remember to change it to a virtual environment.

Packaging in a virtual environment will only package the third-party libraries that the project depends on, and will not package all the libraries installed by pip, and the final exe will be small in size.

Execute the following command to package:

pyinstaller -D main.py

insert image description here

The generated directory has more spec files and bulid and dist folders. In the dist, the final exe file is stored.
insert image description here
insert image description here

3. Run
Just double-click to run main.exe, that's it
insert image description here

3.2 Remove the black frame (recommended)

1. Create the ReadImg.py program.
Note: The cv2 module needs to be installed to use opencv-python.

import cv2 as cv

img = cv.imread('test.jpg', 0)
cv.imshow("ReadImg", img)
cv.waitKey(0)

2. Package
Execute the following command to package:

pyinstaller -D -w ReadImg.py

insert image description here

3. To run,
you need to copy the picture test.png to the directory where ReadImg.exe is located.
insert image description here

Double click to run:
insert image description here

Note: If input() is used in the code, -w cannot be added when packaging, and the black frame (console window) must be kept, otherwise the following error will be reported:

runtimeerror: input(): lost sys.stdin

Guess you like

Origin blog.csdn.net/gdxb666/article/details/127618346