阡陌 发表于 2024-3-2 14:59:12

使用 pyinstaller 打包程序为单 exe 应用


一般的程序打包:

```
pyinstaller -F main.py
```

如果包含 html、js 等文件需要特别处理一下。



待打包示例源代码 main.py:

```
#!/usr/bin/python
# -*- coding: UTF-8 -*-

# 生成资源文件目录访问路径
def resource_path(relative_path):
    if getattr(sys, 'frozen', False):# 是否Bundle Resource
      base_path = sys._MEIPASS
    else:
      base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

filename = resource_path(os.path.join("web", "mesh.html"))
# 访问 html 文件用 filename 就可以了
print(filename)

```



打包文件:

首先生成 spec 文件:

```
pyi-makespec -F main.py
```

会生成 main.spec 文件,编辑它:

datas 添加 ('web', 'web'),web 文件夹存放了 html、js 等文件,这个文件夹会被打包进去。

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

block_cipher = None

a = Analysis(['main.py'],
             pathex=['E:\\projects\\python\\test'],
             binaries=[],
             datas=[('web', 'web')],
             hiddenimports=[],
             hookspath=[],
             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='main',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=True )
```



开始打包:

```
pyinstaller -F main.spec
```



页: [1]
查看完整版本: 使用 pyinstaller 打包程序为单 exe 应用