Victor P Victor P - 1 year ago 84
Python Question

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?

Answer Source

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