1

System Report will display the system's Hardware UUID in the format 01234567-89ab-cdef-0123-456789abcdef.

Using the shell we can retrieve the same UUID:

ioreg -rd1 -c IOPlatformExpertDevice | grep -E '(UUID)'

Is it possible to get this UUID in Python without resorting to executing a shell command?

1
  • Programming questions are off-topic here. Try StackOverflow instead.
    – Gerry
    Commented Nov 23, 2012 at 4:35

2 Answers 2

2

Short answer: not really.

Long answer: sort of, but it's probably more trouble than it's worth, unless you really can't used the shell command for some reason. OS X doesn't really expose much system configuration to Python. Most scriptable interfaces to configure OS X are shell-based or AppleScript-based (and of course the various Objective-C APIs).

Getting the UUID is possible in AppleScript:

tell application "System Information"
    set profile to system profile
    quit
end tell

set delim to AppleScript's text item delimiters
set AppleScript's text item delimiters to "Hardware UUID: "
set uuid to paragraph 1 of text item 2 of profile
set AppleScript's text item delimiters to delim
uuid

But as you can see, it's a bit convoluted (and is much slower than the ioreg method, as it has to process the entire system profile).

There is a way to bridge AppleScript to Python, known as Appscript, but it's no longer developed, and not recommended for new projects. However, if you're really determined, you could convert the above AppleScript into Python using Appscript. But to be honest, it seems like a lot of trouble to get a worse result.

1

I'm able to do it, but I use pyobjc as seen here:

https://gist.github.com/pudquick/c7dd1262bd81a32663f0

import objc
from Foundation import NSBundle

IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')

functions = [("IOServiceGetMatchingService", b"II@"),
             ("IOServiceMatching", b"@*"),
             ("IORegistryEntryCreateCFProperty", b"@I@@I"),
            ]

objc.loadBundleFunctions(IOKit_bundle, globals(), functions)

def io_key(keyname):
    return IORegistryEntryCreateCFProperty(IOServiceGetMatchingService(0, IOServiceMatching("IOPlatformExpertDevice".encode("utf-8"))), keyname, None, 0)

def get_hardware_uuid():
    return io_key("IOPlatformUUID".encode("utf-8"))

If your target for usage is the macOS system python, fortunately Apple already included pyobjc with every recent macOS release.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .