栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python 创建安装包

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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()

暑期编程PK赛 得CSDN机械键盘等精美礼品!
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1015788.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号