在Python脚本中获取当前的git哈希

时间:2022-10-14 23:43:05

I would like to include the current git hash in the output of a Python script (as a the version number of the code that generated that output).

我想在Python脚本的输出中包含当前的git哈希(作为生成该输出的代码的版本号)。

How can I access the current git hash in my Python script?

如何在Python脚本中访问当前的git哈希?

4 个解决方案

#1


64  

The git describe command is a good way of creating a human-presentable "version number" of the code. From the examples in the documentation:

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

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

有了类似git.git当前树的东西,我得到:

[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.

即我的“父”分支的当前头部基于v1.0.4,但由于它上面有一些提交,因此describe添加了额外提交的数量(“14”)和提交的缩写对象名称本身(“2414721”)在最后。

From within Python, you can do something like the following:

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

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

#2


64  

This post contains the command, Greg's answer contains the subprocess command.

这篇文章包含命令,Greg的答案包含子进程命令。

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'])

#3


49  

No need to hack around getting data from the git command yourself. GitPython is a very nice way to do this and a lot of other git stuff. It even has "best effort" support for Windows.

无需自己从git命令获取数据。 GitPython是一个非常好的方法来做这个和许多其他git的东西。它甚至可以为Windows提供“尽力而为”的支持。

After pip install gitpython you can do

在pip安装gitpython后你可以做到

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

#4


4  

numpy has a nice looking multi-platform routine in its setup.py:

numpy在setup.py中有一个漂亮的多平台例程:

import os
import subprocess

# Return the git revision as a string
def git_version():
    def _minimal_ext_cmd(cmd):
        # construct minimal environment
        env = {}
        for k in ['SYSTEMROOT', 'PATH']:
            v = os.environ.get(k)
            if v is not None:
                env[k] = v
        # LANGUAGE is used on win32
        env['LANGUAGE'] = 'C'
        env['LANG'] = 'C'
        env['LC_ALL'] = 'C'
        out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0]
        return out

    try:
        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
        GIT_REVISION = out.strip().decode('ascii')
    except OSError:
        GIT_REVISION = "Unknown"

    return GIT_REVISION

#1


64  

The git describe command is a good way of creating a human-presentable "version number" of the code. From the examples in the documentation:

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

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

有了类似git.git当前树的东西,我得到:

[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.

即我的“父”分支的当前头部基于v1.0.4,但由于它上面有一些提交,因此describe添加了额外提交的数量(“14”)和提交的缩写对象名称本身(“2414721”)在最后。

From within Python, you can do something like the following:

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

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

#2


64  

This post contains the command, Greg's answer contains the subprocess command.

这篇文章包含命令,Greg的答案包含子进程命令。

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'])

#3


49  

No need to hack around getting data from the git command yourself. GitPython is a very nice way to do this and a lot of other git stuff. It even has "best effort" support for Windows.

无需自己从git命令获取数据。 GitPython是一个非常好的方法来做这个和许多其他git的东西。它甚至可以为Windows提供“尽力而为”的支持。

After pip install gitpython you can do

在pip安装gitpython后你可以做到

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

#4


4  

numpy has a nice looking multi-platform routine in its setup.py:

numpy在setup.py中有一个漂亮的多平台例程:

import os
import subprocess

# Return the git revision as a string
def git_version():
    def _minimal_ext_cmd(cmd):
        # construct minimal environment
        env = {}
        for k in ['SYSTEMROOT', 'PATH']:
            v = os.environ.get(k)
            if v is not None:
                env[k] = v
        # LANGUAGE is used on win32
        env['LANGUAGE'] = 'C'
        env['LANG'] = 'C'
        env['LC_ALL'] = 'C'
        out = subprocess.Popen(cmd, stdout = subprocess.PIPE, env=env).communicate()[0]
        return out

    try:
        out = _minimal_ext_cmd(['git', 'rev-parse', 'HEAD'])
        GIT_REVISION = out.strip().decode('ascii')
    except OSError:
        GIT_REVISION = "Unknown"

    return GIT_REVISION