Are there any easy ways to grab the git repository (on GitHub) version hash with Python code? I want to use this to handle versioning of 'dev' releases of my software on github.
Asked
Active
Viewed 2,734 times
2
-
1GutHub or Git repositories? http://stackoverflow.com/questions/5694389/get-the-short-git-version-hash – tMC Oct 10 '12 at 19:20
-
Sorry it wasn't clear, I meant git repositories (I store them on github). – Christopher Dorian Oct 10 '12 at 19:24
4 Answers
9
def git_version():
from subprocess import Popen, PIPE
gitproc = Popen(['git', 'rev-parse','HEAD'], stdout = PIPE)
(stdout, _) = gitproc.communicate()
return stdout.strip()

deddu
- 855
- 12
- 16
1
Like this ?
import subprocess
ref = subprocess.check_output("""
git 2>/dev/null show-ref | awk '/refs\/heads\/master/{print $1}'
""", shell=True)
print ref
Adapt it if you have something else than master

Gilles Quénot
- 173,512
- 41
- 224
- 223
-
Via python. run the `git` command via `Popen` and parse the output in python. – tMC Oct 10 '12 at 19:27
-
No need to pipe it to awk. Just read `stdout` from the `Popen` object and parse the text in Python. Python is very good as string handling! – tMC Oct 10 '12 at 19:31
-
Sorry, had to go with tMC's answer. check_output is from 2.7, I'de like backwards compatibility for now. – Christopher Dorian Oct 10 '12 at 23:40
1
from subprocess import Popen, PIPE
gitproc = Popen(['git', 'show-ref'], stdout = PIPE)
(stdout, stderr) = gitproc.communicate()
for row in stdout.split('\n'):
if row.find('HEAD') != -1:
hash = row.split()[0]
break
print hash

tMC
- 18,105
- 14
- 62
- 98