Python 创建安装包

Version

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Author     : forward_huan
# @Time       : 2022-07-14 23:05
# @Description:

import json
import os

from src.utils.utils import get_config_dir


def get_version_config_path() -> str:
    """获取版本配置文件的路径"""
    return os.path.join(get_config_dir(), "version.conf")


def get_version_config(recreate: bool = False) -> dict:
    """
    获取版本信息

    :param recreate: 强制重新获取
    :return:
    """
    config_path = get_version_config_path()
    if not recreate and os.path.exists(config_path):
        with open(config_path, "r", encoding="utf8") as f:
            config: dict = json.load(f)
    else:
        commit_id, commit_date = get_commit_info()
        config = {
            "product_name": "*******",
            "file_version": commit_date,
            "product_version": "1.0.0.0",
            "commit_date": commit_date,
            "commit_id": commit_id,
            "file_description": f"******"}

    with open(config_path, "w", encoding="utf") as f:
        json.dump(config, f, indent=4, ensure_ascii=False)

    return config


def get_commit_info():
    """
    获取当前提交的commit信息

    :return: commit_id, commit_date
    """

    # noinspection PyBroadException
    try:
        cmd_id = "git log -1 --pretty=%H"
        cmd_date = "git log -1 --date=format:%Y.%#m.%#d.%#H --pretty=format:%cd"
        result = os.popen(f"{cmd_id} & {cmd_date}").read().splitlines()
        if len(result) != 2:
            return "", ""
        return result[0], result[1]
    except Exception:
        return "", ""

pack_exe

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Author     : forward_huan
# @Time       : 2022-07-14 23:05
# @Description:

import os
from datetime import datetime

from src.utils.utils import get_root_path, get_logo_path, get_config_dir
from src.utils.version import get_version_config
from PyInstaller.__main__ import run as start_pack

_ver_info = """# UTF-8
#
VSVersionInfo(
  ffi=FixedFileInfo(
    # filevers and prodvers should be always a tuple with four items:
    # (1, 2, 3, 4)
    # Set not needed items to zero 0.
    filevers=(-FileVers-),
    prodvers=(-ProductVers-),
    # Contains a bitmask that specifies the valid bits 'flags'r
    mask=0x3f,
    # Contains a bitmask that specifies the Boolean attributes of the file.
    flags=0x0,
    # The operating system for which this file was designed.
    # 0x4 - NT and there is no need to change it.
    OS=0x4,
    # The general type of file.
    # 0x1 - the file is an application.
    fileType=0x1,
    # The function of the file.
    # 0x0 - the function is not defined for this fileType
    subtype=0x0,
    # Creation date and time stamp.
    date=(0, 0)
    ),
  kids=[
    StringFileInfo(
      [
      StringTable(
        u'000004b0',
        [StringStruct(u'Comments', u'-Comments-'),
        StringStruct(u'CompanyName', u'-CompanyName-'),
        StringStruct(u'FileDescription', u'-FileDescription-'),
        StringStruct(u'FileVersion', u'-FileVersion-'),
        StringStruct(u'InternalName', u'-InternalName-'),
        StringStruct(u'LegalCopyright', u'-LegalCopyright-'),
        StringStruct(u'LegalTrademarks', u'-LegalTrademarks-'),
        StringStruct(u'OriginalFilename', u'-OriginalFilename-'),
        StringStruct(u'ProductName', u'-ProductName-'),
        StringStruct(u'ProductVersion', u'-ProductVersion-'),
        StringStruct(u'Assembly Version', u'-AssemblyVersion-')])
      ]), 
    VarFileInfo([VarStruct(u'Translation', [0, 1200])])
  ]
)
"""


def create_version_info(
        product_version: str, file_version: str, product_name="",
        assembly_version="", comments="", company_name="",
        file_description="", internal_name="", legal_copyright="",
        legal_trademarks="", original_filename="", *args, **kwargs):
    """创建版本文件内容"""
    print(args, kwargs)
    if not assembly_version:
        assembly_version = file_version
    return _ver_info \
        .replace("-ProductVersion-", product_version) \
        .replace("-ProductVers-", product_version.replace(".", ",")) \
        .replace("-FileVersion-", file_version) \
        .replace("-FileVers-", file_version.replace(".", ",")) \
        .replace("-ProductName-", product_name) \
        .replace("-AssemblyVersion-", assembly_version) \
        .replace("-Comments-", comments) \
        .replace("-CompanyName-", company_name) \
        .replace("-FileDescription-", file_description) \
        .replace("-InternalName-", internal_name) \
        .replace("-LegalCopyright-", legal_copyright) \
        .replace("-LegalTrademarks-", legal_trademarks) \
        .replace("-OriginalFilename-", original_filename)


def create_version_file(version_path):
    version_info = create_version_info(**get_version_config(True))
    dir_path = os.path.dirname(version_path)
    if os.path.exists(dir_path) is False:
        os.makedirs(dir_path)

    with open(version_path, "w", encoding="utf8") as f:
        f.write(version_info)


def delete_version_file(version_path):
    if os.path.exists(version_path):
        os.remove(version_path)


def build(dist_path=None, name=None, is_one_file=True):
    root_path = get_root_path()
    icon_path = get_logo_path()
    if name is None:
        name = "******_" + datetime.now().strftime("%Y_%m_%d")
    if dist_path is None:
        dist_path = os.path.join(root_path, "out")
    out_path = os.path.join(root_path, "out")
    build_path = os.path.join(out_path, "build")
    py_file = os.path.join(root_path, "startup.py")
    file_version_path = os.path.join(out_path, "file_version.txt")
    path_res = os.path.join(root_path, "src", "res")
    dest_path_res = os.path.join("src", "res")
    config_res = get_config_dir()
    dest_config_res = os.path.join("config")
    params = [
        "-y", py_file, "-n", name, "--distpath", dist_path,
        "--workpath", build_path, "--specpath", build_path,
        "--version-file", file_version_path, "-i", icon_path,
        "--add-data", f"{path_res};{dest_path_res}",
        "--add-data", f"{config_res};{dest_config_res}"]
    if is_one_file:
        params.append("-F")
    print(" ".join(params))
    create_version_file(file_version_path)
    start_pack(params)
    delete_version_file(file_version_path)
    print("打包完成")


if __name__ == '__main__':
    build()

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值