Skip to content

Instantly share code, notes, and snippets.

@pudquick
Created November 3, 2016 16:29
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pudquick/5a9f5f02c53b3fa648c5704e34b1db8a to your computer and use it in GitHub Desktop.
Save pudquick/5a9f5f02c53b3fa648c5704e34b1db8a to your computer and use it in GitHub Desktop.
Get nvram values via python and pyobjc on macOS
import objc
from Foundation import NSBundle
IOKit_bundle = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')
functions = [
("IORegistryEntryFromPath", b"II*"),
("IORegistryEntryCreateCFProperty", b"@I@@I"),
]
objc.loadBundleFunctions(IOKit_bundle, globals(), functions)
def nvram(keyname):
raw = IORegistryEntryCreateCFProperty(IORegistryEntryFromPath(0, "IODeviceTree:/options"), keyname, None, 0)
# This returns the raw bytes
# For string values, this will be what you're looking for
# For more complex/structured values, you may need to parse the bytes
return raw.bytes().tobytes()
# example usage:
# Look up a macOS device serial number via nvram
def serialnumber():
return nvram("4D1EDE05-38C7-4A6A-9CC6-4BCCA8B38C14:SSN")
@Chalcahuite
Copy link

Chalcahuite commented Feb 24, 2020

On python 3.8.1 with pyObjC 6.1 I get the following:
Traceback (most recent call last): File "/Users/user/Documents/GitHub/Tests/nvram.py", line 34, in <module> print(serialnumber()) File "/Users/user/Documents/GitHub/Tests/nvram.py", line 31, in serialnumber return nvram("4D1EDE05-38C7-4A6A-9CC6-4BCCA8B38C14:SSN") File "/Users/user/Documents/GitHub/Tests/nvram.py", line 18, in nvram raw = IORegistryEntryCreateCFProperty(IORegistryEntryFromPath( ValueError: depythonifying 'charptr', got 'str'
Such are the pitfalls of using code you don't fully understand. -_-;

@n8felton
Copy link

n8felton commented Dec 7, 2021

@Chalcahuite This needs to be slightly modified to work with Python 3. I've updated my fork of this code over at https://gist.github.com/n8felton/649f66baf51c2c4c33d46b8c25433a7f and was tested working with Python 3.9.5 and objc 7.1

@Chalcahuite
Copy link

@n8felton Nice! That works for me too, on same build of Python 3 and ObjC. Time to update functions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment