Skip to content

Instantly share code, notes, and snippets.

@pudquick
Last active April 20, 2023 06:06
Show Gist options
  • Save pudquick/134acb5f7423312effcc98ec56679136 to your computer and use it in GitHub Desktop.
Save pudquick/134acb5f7423312effcc98ec56679136 to your computer and use it in GitHub Desktop.
Accessing battery details via python and pyobjc on macOS / OS X
import objc
from Foundation import NSBundle
IOKit = NSBundle.bundleWithIdentifier_('com.apple.framework.IOKit')
functions = [("IOServiceGetMatchingService", b"II@"),
("IOServiceMatching", b"@*"),
("IORegistryEntryCreateCFProperties", b"IIo^@@I"),
("IOPSCopyPowerSourcesByType", b"@I"),
("IOPSCopyPowerSourcesInfo", b"@"),
]
objc.loadBundleFunctions(IOKit, globals(), functions)
# matches information pulled by: pmset -g rawbatt
def raw_battery_dict():
battery = IOServiceGetMatchingService(0, IOServiceMatching("AppleSmartBattery"))
if (battery != 0):
# we have a battery
err, props = IORegistryEntryCreateCFProperties(battery, None, None, 0)
return props
# matches information pulled by: pmset -g batt
def adjusted_battery_dict():
try:
battery = list(IOPSCopyPowerSourcesByType(0))[0]
except:
battery = 0
if (battery != 0):
# we have a battery
return battery
def raw_battery_percent():
d = raw_battery_dict()
if d:
curc = d['CurrentCapacity']
maxc = d['MaxCapacity']
perc = 100.*curc/maxc
return perc
def adjusted_battery_percent():
d = adjusted_battery_dict()
if d:
return d["Current Capacity"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment