tags:

views:

391

answers:

3

My application is assumed to be running on a Mac OS X system. However, what I need to do is figure out what version of Mac OS (or Darwin) it is running on, preferably as a number. For instance,

  • "10.4.11" would return either 10.4 or 8
  • "10.5.4" would return 10.5 or 9
  • "10.6" would return 10.6 or 10

I found out that you could do this, which returns "8.11.0" on my system:

import os
os.system("uname -r")

Is there a cleaner way to do this, or at least a way to pull the first number from the result? Thanks!

+8  A: 
>>> import platform
>>> platform.mac_ver()
('10.5.8', ('', '', ''), 'i386')

As you see, the first item of the tuple mac_ver returns is a string, not a number (hard to make '10.5.8' into a number!-), but it's pretty easy to manipulate the 10.x.y string into the kind of numbers you want. For example,

>>> v, _, _ = platform.mac_ver()
>>> v = float('.'.join(v.split('.')[:2]))
>>> print v
10.5

If you prefer the Darwin kernel version rather than the MacOSX version, that's also easy to access -- use the similarly-formatted string that's the third item of the tuple returned by platform.uname().

Alex Martelli
+1 for `platform`
Jed Smith
That's perfect! Thanks for your help!
Chris Long
A: 

If you want to run a command - like 'uname' - and get the results as a string, use the subprocess module.

import subprocess
output = subprocess.Popen(["uname", "-r"], stdout=subprocess.PIPE).communicate()[0]
Shane C. Mason
A: 

You could parse the output of the /usr/bin/sw_vers command.

agregoire
The uname command will give him the version - his problem is in how to get this value into a variable.
Shane C. Mason
Well, at least it gives the kernel version - but he seems to have an overall problem of being able to read command output into a variable.
Shane C. Mason