Get the current git hash in a Python script


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

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

12/18/2016 4:07:22 PM

Accepted Answer

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

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

[torvalds@g5 git]$ git describe parent

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.

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

import subprocess
label = subprocess.check_output(["git", "describe"]).strip()
3/13/2018 1:23:10 PM

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.

After pip install gitpython you can do

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow