簡體   English   中英

在凍結的 Python 腳本 (Cx_Freeze) 中顯示 git commit hash

[英]Display git commit hash in frozen Python script (Cx_Freeze)

我有一個 python 項目並使用 git 作為版本控制軟件。 該軟件將使用 Cx_Freeze 進行部署。

我想在我的應用程序的“關於”對話框中顯示在構建過程(凍結腳本)期間捕獲的版本和作者(以及可能的其他元數據)。

這是設置腳本的示例:

import sys
import subprocess

from cx_Freeze import setup, Executable

build_exe_options = {}
base = "Win32GUI"
version = subprocess.run(['git', 'describe', '--abbrev=4', '--dirty', '--always', '--tags'],
                         capture_output=True, encoding='utf-8').stdout.strip()

setup(
    name="XY",
    version=version,
    author="My Name",
    description="Mysterious GUI application",
    options={"build_exe": build_exe_options},
    executables=[Executable("XY.py", base=base)],
)

關於對話框的簡單示例:

from tkinter import messagebox

def on_about():
    messagebox.showinfo(f'About', 'Software XY, written by {author}, version {version}')
    # Should display e.g. 'Software XY, written by My Name, version 4b06-dirty'

有誰知道這是否可能以及如何實現? 提前感謝大家!

我想出了第一個解決方案,在執行安裝腳本時,我在應用程序的主 package 中創建了一個子模塊。 我將 __version__ 變量導入到那個 package 的 __init__.py 中,只有當它被凍結並且子模塊存在時:

安裝程序.py:

import subprocess
import os.path

import mymodule

from cx_Freeze import setup, Executable


def create_versionmodule(packagepath: str):
    """
    creates a file packagepath/_version.py which defines a __version__ variable
    which contains the stripped output of "git describe --dirty --always --tags"
    """
    
    version = subprocess.run(['git', 'describe', '--dirty', '--always', '--tags'],
                             capture_output=True, encoding='utf-8').stdout.strip()
    with open(os.path.join(packagepath, '_version.py'), mode='w', encoding='utf-8') as file:
        file.write(f'__version__: str = {version!r}\n')


build_exe_options = {}
base = "Win32GUI"

create_versionmodule(packagepath=os.path.dirname(mymodule.__file__))

setup(
    name="XY",
    description="Mysterious GUI application",
    options={"build_exe": build_exe_options},
    executables=[Executable("XY.py", base=base)],
)

我的模塊/__init__.py:

import sys as _sys

__version__ = 'UNKNOWN'
if getattr(_sys, "frozen", False):
    try:
        from mymodule._version import __version__
    except ModuleNotFoundError:
        pass

現在我可以從我的代碼中的任何地方訪問版本變量:

import mymodule

from tkinter import messagebox

def on_about():
    messagebox.showinfo(f'About', 'Software XY, version {mymodule.__version__}')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM