Getting SVN revision number into a program automatically

I'm not sure about the Python specifics, but if put the string $Revision$ into your file somewhere and you have enable-auto-props=true in your SVN config, it'll get rewritten to something like $Revision: 144$. You could then parse this in your script.

There are a number of property keywords you can use in this way.

This won't have any overhead, e.g. querying the SVN repo, because the string is hard-coded into your file on commit or update.

I'm not sure how you'd parse this in Python but in PHP I'd do:

$revString = '$Revision: 144$';
if(preg_match('/: ([0-9]+)\$/', $revString, $matches) {
    echo 'Revision is ' . $matches[1];
}

Similar to, but a little more pythonic than the PHP answer; put this in your module's __init__.py:

__version__ = filter(str.isdigit, "$Revision: 13 $")

and make sure you add the Revision property:

svn propset svn:keywords Revision __init__.py

Or you can do like this:

import re,subprocess

svn_info = subprocess.check_output("svn info")

print (re.search(ur"Revision:\s\d+", svn_info)).group()

it prints "Revision: 2874" in my project

Or like this:

print (subprocess.check_output("svnversion")).split(":")[0]

it prints "2874" in my project

Edit

For newer python versions (>=3.4) and for explicit file path:

import re,subprocess

file_path = 'c:/foo'

svn_info = subprocess.check_output('svn info ' + file_path)

revision_string = re.search(r"Revision:\s\d+", str(svn_info)).group()
revision = revision_string.split(': ')[1]
print(revision)

Prints for example

'8623'


The file hooks/pre-commit in your repository is a script or program which will be executed before a successful commit. Simply make this a script which updates your file with the proper version number as it is being committed (the revision number is passed to your script as it's run). Here's a tutorial with an example of writing a pre-commit hook: http://wordaligned.org/articles/a-subversion-pre-commit-hook