Accessing power status using PyObjC in Mac OS X

IOKit is an important framework in Mac OS X, providing almost all kernel and driver specific functions and structures. Since all of this stuff is very low level, IOKit is mostly implemented using plain C and therefore cannot be be used in PyObjC and RubyCocoa through normal bridging.

The good news is that the functions responsible for getting power status are written using CoreFoundation types and can therefore be bridged. PyObjC does not support them by default, but all we have to do is to generate a .bridgesupport and load it into PyObjC manually.

Thanks to Apple that’s easy:

  1. Generate .bridgesupport file:

    gen_bridge_metadata -c '-l/System/Library/Frameworks/IOKit.framework/IOKit -I/System/Library/Frameworks/IOKit.framework/Headers/ps/' /System/Library/Frameworks/IOKit.framework/Headers/ps/IOPowerSources.h /System/Library/Frameworks/IOKit.framework/Headers/ps/IOPSKeys.h
    
  2. Read the file into Python. We’ll read it into a variable called IO_POWER_SOURCES_BRIDGESUPPORT for this example.

  3. Load it into PyObjC:

    objc.parseBridgeSupport(IO_POWER_SOURCES_BRIDGESUPPORT, globals(), objc.pathForFramework("/System/Library/Frameworks/IOKit.framework"))
    

A full example can be found here.

Update: the current version of PyObjC (2.4, distributed via PyPI) does not have an implementation of parseBridgeSupport. More information here. parseBridgeSupport works again in PyObjC 2.5, or you can just install the latest version from BitBucket by following the instructions here.

Subscribe Tweet This
Written by Ilya Kulakov on 2012 Nov 22 .
Tagged .