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:
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
The generated directory has more spec files and bulid and dist folders. In the dist, the final exe file is stored.
3. Run
Just double-click to run main.exe, that's it
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
3. To run,
you need to copy the picture test.png to the directory where ReadImg.exe is located.
Double click to run:
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