使用PyInstaller 将python程序 .py转为 .exe
最近经常用到一个.py程序,但是每次在不同电脑上用,希望能把Python脚本发布为脱离Python平台运行的可执行程序,比如单个exe。PyInstalle满足要求。
PyInstaller本身并不属于Python包。在安装 pyinstaller之前需把python环境配置好。
安装pyinstaller
下载pyinstaller
解压到F:\PyInstaller-2.1(自选)项目地址: PyInstaller
安装pywin32
pywin32-217.win32-py2.7.exe:点击下载
安装pyinstaller
1、进入cmd1
cd F:\PyInstaller-2.1
1
python pyinstaller.py --console --onefile test.py
如果提示:1
2Usage: python pyinstaller.py [opts] <scriptname> [ <scriptname> ...] | <specfile>
pyinstaller.py: error: Requires at least one scriptname file or exactly one .spec-file
则说明安装完成了。
测试打包
1、文件放在当前目录的pyinstaller-2.1文件夹里面1
cd F:\PyInstaller-2.1
1
python pyinstaller.py --console --onefile test.py
2、命令运行成功后会生成一个test文件夹。在这个文件夹下面会有一个名为dist的文件夹,此文件夹下面有转换好的test.exe
3、上面编译出来的exe能够正常运行了,但带一个黑色的console,以下重新编译,加入–windowed –icon,取消–console1
python pyinstaller.py -w --onefile --icon="my.ico" test.py
其中my.ico是你要给他加的自定义图标文件。
2023-10-25更新:
使用 Github Actions 打包 Python 可执行文件到多个平台下
Github Actions pipeline 参考:.github/workflows/build.yaml
:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48name: CI
# Controls when the workflow will run
on:
# Triggers the workflow on push or pull request events but only for the "main" branch
push:
branches: [ "master" ]
paths-ignore:
- '**.md'
- 'LICENSE'
pull_request:
branches: [ "master" ]
paths-ignore:
- '**.md'
- 'LICENSE'
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
CI:
strategy:
matrix:
python-version: [ "3.10" ]
os-version: [ "macos-latest", "windows-latest", "ubuntu-20.04" ]
runs-on: ${{ matrix.os-version }}
steps:
- uses: actions/checkout@v3
with:
submodules: recursive
- uses: actions/setup-python@v4
with:
python-version: ${{ matrix.python-version }}
architecture: x64
- name: Build
run: |
pip install -r requirements.txt
pip install pyinstaller
python -m PyInstaller -F -n jenkins-tools main.py
- name: upload
uses: actions/upload-artifact@v3
with:
name: jenkins-tools-${{ matrix.os-version }}
path: dist