Quantcast
Viewing all articles
Browse latest Browse all 15

Using Python distutils.version to compare Mac OS X version numbers

After talking with Steve last Friday about how I really wanted a way to compare Mac OS X version numbers, I set off to find one myself. Determining if your script is running on an operating system version that meets your minimum requirements and finding out of if one version of the system is older/newer than another are very practical yet repetitive tasks for systems administrators. I thought I would have to code a common function for a module, so that we didn’t keep re-creating it in every script where it was needed.

It turns out that task is amazingly simple in Python … again, because batteries are included. The comparison is already there, because distutils.version lets you create version objects that can be compared easily with standard operators. I’ll stand on the shoulders of giants, sure! That’s the whole point of software development. (And you thought Perl programmers were lazy. Grin.)

Here’s an example, using the Python version that shipped with Mac OS X Tiger:


>>> from distutils import version
>>> a = version.StrictVersion('10.4.10')
>>> b = version.StrictVersion('10.4.9')
>>> c = version.StrictVersion('10.4.1')
>>> d = version.StrictVersion('10.4')
>>> e = version.StrictVersion('10.3.9')
>>> a > b
True
>>> a > c
True
>>> a > d
True
>>> a > e
True
>>> b > a
False
>>> b > c
True
>>> b > d
True
>>> b > e
True
>>> e > a
False
>>> d > e
True

As you can see, the mythical version “10.4.10” — were there to be one — would indeed show up as newer than “10.4.9” and all previous version objects I created with version.StrictVersion. Even if that version is never shipped by Apple, we’ve all wondered when or if they would jump past a .9 revision. If they do, distutils.version will still handle it: the 10.4.10 version here is greater than both 10.4.9 and 10.4.1, which are two important test cases.

Each greater than or less than test — using the standard comparison operators — came out as I would expect and hope. Using version.StrictVersion objects in such comparisons works quite well … and means I don’t have to code much logic at all. That’s less code for me and for a future maintenance programmer (read “harried systems administrator”) to review.

This should serve as a valid model for comparing version numbers throughout the entire Mac OS X line on a modern system, assuming you have Python with distutils (and I will readily admit that I don’t know how far back that goes).

Update: If you use the output of platform.version() for distutils.version objects, you can also compare version numbers for Microsoft Windows in Python. At least, the format for the Windows Vista version numbers appear to work, and what I recall of the numbering for earlier versions should match.


Viewing all articles
Browse latest Browse all 15

Trending Articles