Fix Python – Get the current git hash in a Python script

Question

Asked By – Victor

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?

Now we will see solution for issue: Get the current git hash in a Python script


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

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

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

This question is answered By – Greg Hewgill

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0