10.5 came bundled with PyObjC, but in 10.6 it’s actually usable since we now have Python 2.6.1 (with “batteries included”). This makes Python more and more the language of choice for your everyday Cocoa hacking needs.
One of the problems you’ll run into quite early on is accessing the Keychain which is still firmly in Carbon aka procedural C land. Maybe the PyObjC bridge also allows calling C stuff, I don’t know, but lucky for us, we don’t have to. There’s been posts about this elsewhere but I think I’ve found a more simple solution. One that doesn’t involve ancient frameworks or changes to your Python imports.
So, to access the Keychain from your PyObjC app:
- Download Extendmac’s EMKeychain classes and add them to your PyObjC project
- Add the Carbon and Security frameworks
Edit “main.m” and add these import statements:
#import "EMKeychainProxy.h" #import "EMKeychainItem.h"
Test it. For instance, to add a password to the keychain from your Python code:
kp = EMKeychainProxy.sharedProxy() kp.addGenericKeychainItemForService_withUsername_password_("someservice", "filipp", "test")
which should result in this in Keychain Access:
And reading a password is just as simple:
ki = kp.genericKeychainItemForService_withUsername_("someservice", "filipp") pw = ki.password()
And that’s it! All kudos and many thanks to Brian Amerige of Extendmac for sharing his Keychain code!