将python文件打包成exe,让没有python环境的人也能使用

将python文件打包成exe,让没有python环境的人也能使用

笔者用的是python3.10与anaconda环境

首先安装所需的库:

conda install pyinstaller

在代码所在的目录中,创建一个新的Python脚本(例如compress_pdf_app.py),并将原始代码放入其中。

例如:

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
# compress_pdf_app.py
import PyPDF2


def compress_pdf(input_path, output_path):
with open(input_path, 'rb') as file:
pdf = PyPDF2.PdfFileReader(file)
writer = PyPDF2.PdfFileWriter()

for page_num in range(pdf.getNumPages()):
page = pdf.getPage(page_num)
# 对页面内容进行压缩
page.compressContentStreams()
writer.addPage(page)

with open(output_path, 'wb') as output_file:
writer.write(output_file)


if __name__ == "__main__":
# 可以用相对路径或者绝对路径
input_pdf = "input.pdf"
output_pdf = "output_compressed.pdf"
compress_pdf(input_pdf, output_pdf)

基础命令

使用PyInstaller将compress_pdf_app.py打包成可执行文件。在命令行中进入该脚本所在的目录,然后运行以下命令:

pyinstaller --onefile compress_pdf_app.py

  1. PyInstaller将会在当前目录下生成一个dist文件夹,并在其中包含可执行文件。该可执行文件是与平台相关的,例如在Windows系统中会生成一个.exe文件,在Linux系统中会生成一个无后缀的文件。

现在,你可以将生成的可执行文件发送给没有Python环境的人,他们可以直接运行这个文件,无需安装Python,即可使用这个压缩PDF的功能。

给文件添加元信息

这个命令可以在生成exe文件的时候添加图标,作者,版本号,使用方法等信息

注意,还得多安装一个包:conda install pillow

  1. 创建一个图标文件(.ico),如果你已经有一个了,将它移到你的Python脚本同一个文件夹中。
  2. 用PyInstaller将你的Python脚本打包成一个exe文件。在你的命令行输入以下的命令:
1
pyinstaller --onefile --windowed --icon=fire.ico --name=compress_pdf_app --version-file=version.txt compress_pdf_app.py

在这个命令中,--onefile 参数表示生成单一的exe文件,--windowed 参数表示无控制台运行,--icon=fire.ico 表示使用你的ico文件作为应用程序图标,--name 参数用于指定生成的exe文件的名称,--version-file 用于指定版本信息文件。

  1. 你需要创建一个版本信息文件 version.txt,以下是一个简单的示例:
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
VSVersionInfo(
ffi=FixedFileInfo(
filevers=(1, 0, 0, 0),
prodvers=(1, 0, 0, 0),
mask=0x3f,
flags=0x0,
OS=0x4,
fileType=0x1,
subtype=0x0,
date=(0, 0)
),
kids=[
StringFileInfo(
[
StringTable(
'040904b0',
[StringStruct('CompanyName', 'guolin'),
StringStruct('FileDescription', '将pdf命名为input.pdf并放在与本文件同目录下即可'),
StringStruct('FileVersion', '1.0'),
StringStruct('InternalName', 'compress_pdf_app'),
StringStruct('OriginalFilename', 'compress_pdf_app'),
StringStruct('ProductName', 'compress_pdf_app'),
StringStruct('ProductVersion', '1.0')])
]),
VarFileInfo([VarStruct('Translation', [0, 1200])])
]
)

直接可运行的exe

分享一个我封装好的可执行文件,可以直接用来压缩pdf

https://github.com/guolinac/CompressPDF

-------------本文结束感谢您的阅读-------------