Python 打包代码为 .exe 文件(包括静态js、html打包)


准备工作

使用 pyinstaller 打包
pip install pyinstaller
详细用法可参考 https://realpython.com/pyinstaller-python/
pyinstaller 网上教程一堆,这里只列常用命令供快速查阅

参数说明

--name -n 重命名,不需要加后缀,自带.exe

pyinstaller cli.py --name realpython

--onefile -F 打包成一个文件。dist文件夹下只会出现一个exe文件

pyinstaller cli.py --onefile

--hidden-import 使函数内部的 import 依赖和 import() 方法可用
后面需要加模块名称,可以使用多次。如果是文件开头使用 import 没有影响。也就是说除非你在 main 函数里面写一些 import,需要用到这个命令,正常在文件开头 import 是不需要用的。

pyinstaller cli.py --hiddenimport=requests --hiddenimport=numpy

--add-data--add-binary 打包附加数据或者lib
例如打包 configuration files examples, or other non-code data
重要参数,解决你打包以后代码里面读写文件、引用js文件总是找不到路径的问题。
(以下信息来自 StackOverflow)

  • format: {source}{os_separator}{destination}(destination 是文件夹路径)
    • os_separator:
      • Windows: ;
      • Mac/Linux/Unix: :(Windows下是分号,Linux等是冒号)
    • source and destination
      • Logic:
        • source: path to single or multiple files, supporting glob syntax. Tells PyInstaller where to find the file(s).
        • destination file or files: destination folder which will contain your source files at run time. * NOTE: NOT the destination file name.
          • folder: destination folder path, which is RELATIVE to the destination root, NOT an absolute path.
  • Examples:
    • Single file: src/README.txt:.(打包单个文件,相对路径)
    • multiple files: /mygame/sfx/*.mp3:sfx(打包多个依赖文件)
    • folder: /mygame/data:data(打包文件夹)

打包外部 js、html的时候需要在py文件中使用相对路径。(复制下面的代码即可)

import os
import sys
# 获取资源路径
def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

# 使用后,会自动获取临时文件夹下的资源文件,而不再需要外置静态资源文件C:\Users\vana\AppData\Local\Temp\_MEI286322\./ids-encrypt.js
# windows系统下,当前文件夹内资源打包
pyinstaller cli.py --add-data ids-encrypt.js;.

--exclude-module 排除模块
例如一些开发时依赖,比如 pytest 等

pyinstaller cli.py --exclude-module=pytest

-w 去掉运行时的cmd窗口。有界面的程序可使用,cmd程序勿用

pyinstaller cli.py -w


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM