Getting Mercurial Tip Version in Python

March 31, 2010

I had a need to get hold of the version number of the Tip revision in my Mercurial repository. This was so that I could automatically generate a version number than included this number. This can be done with the following python code:

import os

lPut, lGet = os.popen4("hg tip")
lOutput = lGet.readline()
lTipRevision = lOutput[10:].strip()
lTipRevision = lTipRevision[:lTipRevision.find(":")].strip()
print "Repository tip version is %s" % lTipRevision

To get the currently checked out revision, rather than the latest repository revision, use hg parent rather than hg tip.

Update

os.popen4 is deprecated in python 2.6. Here's an updated version:

import subprocess

lProcess = subprocess.Popen(["hg","tip"], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
lOutput = lProcess.stdout.readline()
lTipRevision = lOutput[10:].strip()
lTipRevision = lTipRevision[:lTipRevision.find(":")].strip()
print "Repository tip version is %s" % lTipRevision