在Python scrip中获取当前git散列

2024-04-20 13:24:38 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

不需要自己从git命令获取数据。GitPython是一个很好的方法来做这个和很多其他的事情。它甚至对Windows提供了“尽力”支持。

pip install gitpython之后,您可以

import git
repo = git.Repo(search_parent_directories=True)
sha = repo.head.object.hexsha

This post包含命令,Greg's answer包含子进程命令。

import subprocess

def get_git_revision_hash():
    return subprocess.check_output(['git', 'rev-parse', 'HEAD'])

def get_git_revision_short_hash():
    return subprocess.check_output(['git', 'rev-parse', '--short', 'HEAD'])

^{}命令是创建代码的人类可呈现的“版本号”的好方法。从文档中的示例:

With something like git.git current tree, I get:

[torvalds@g5 git]$ git describe parent
v1.0.4-14-g2414721

i.e. the current head of my "parent" branch is based on v1.0.4, but since it has a few commits on top of that, describe has added the number of additional commits ("14") and an abbreviated object name for the commit itself ("2414721") at the end.

在Python中,您可以执行以下操作:

import subprocess
label = subprocess.check_output(["git", "describe"]).strip()

相关问题 更多 >