TweetFollow Us on Twitter

Mac in the Shell-Python on the Mac: PyObjC

Volume Number: 25
Issue Number: 06
Column Tag: Mac in the Shell

Mac in the Shell-Python on the Mac: PyObjC

Writing native Cocoa apps using Python

by Edward Marczak

Introduction

Over the last few months, we've been covering the basics of Python. Aside from a few OS X-specific issues raised in the first article (how to get the built-in docs working, etc.), you could really take the lessons learned anywhere - Linux, Windows, or any platform where you find a Python runtime. We needed those basics - and we have more to cover, certainly. However, this is MacTech. There's plenty that one can do with some very basic Python and Python/Objective-C bridge, letting you tap into Cocoa. Cocoa? Isn't that reserved for Obj-C developers? Nope. While MacTech has covered this concept before (Scott Corely, "Python Cocoa: Delicious," February 2009), I'd like to put together the lessons learned in this column along with a more utilitarian approach.

Read The Fine Manual

Anytime we're working with Cocoa and the technologies in OS X, we'll probably be pouring through the developer references at http://developer.apple.com. You'll need an ADC account to do so. Even the free variety will do, so, go sign up now if you haven't already!

Once you're logged into the Developer Connection, head to the developer docs at http://developer.apple.com/documentation/. More often than not, you'll search on the topic you're after. Sometimes, you find good documentation spread out over several categories. Today, we'll be looking at getting information out of Address Book. True to form, the docs are somewhat spread out. I'll make reference to each as I use it. In short, for now, just search on "address book".

Translating Obj-C

First, why would we want to do this? There are certainly cases when developing for OS X where straight Obj-C is the right choice. However, I'm taking this from a System Administrator's point of view. Often, a System Administrator is already writing basic scripts in bash. I love bash, but there's only so far that it'll get you without becoming painful. If you're writing a script in bash and it passes the 4 functions milestone, it may be time to consider a language more suited to your task. For example, bash isn't really great with databases.

Sure, you can use the mysql binary, pipe the output to awk, and manipulate results from there. But is that the best use of your time and talent? Ever deal with arrays in bash? Pain. While I may recommend Python or Ruby as a step up in general, these languages are made even more special under OS X thanks to Apple's inclusion of an Obj-C bridge. BridgeSupport opens up OS X's native APIs to Python, Ruby and JavaScript. This is available and standard on every Mac running 10.5 or higher. (10.4 support is available, but you'll need to install it yourself, which is outside the scope of this article). BridgeSupport deals with all of the behind-the-scenes work of converting between Python and the native frameworks. The first challenge to this technique is interpreting the documentation. We're going to code all of this in Python, and the docs are directed at people writing in C and Objective-C. Anyone remember having to translate Mac Toolbox API calls from Pascal to C? I digress...

Now that we've covered Python classes, you know about sending a message to an object using dot notation. In last month's column, the BankClass example class contained deposit and withdraw methods. A new class could be created and a method called in the following manner:

acct = Account('Joan', 'Smith')    # Create new account
acct1.Deposit(50)       # Note use of class method here

However, if we got this information from Apple's developer documentation, you'd see something like this:

[acct1 Deposit:50]

This was covered in depth in the "Python Cocoa: Delicious" article referenced earlier, but I'll cover the basic rules here.

As you can see, Obj-C uses square brackets to send messages to objects. The easiest call to translate is a simple message with no parameters. This:

[object message];

in Python becomes:

object.message()

When a method takes parameters, Obj-C places them in-line:

[object message:40 key:50];

Python keeps its usual format here, separating the method name and parameters. Each message and parameter gains a trailing underscore character:

object.message_key_(40,50)

Essentially, each colon is replaced by an underscore - even if there's only one parameter. For example:

object.message_(40)

To instantiate an objective-c class in the first place is fairly straightforward.

object = NSObject.alloc().init()

Let's see all of this in action.

Reading the Address Book

The beauty of using a language like Python is that you can author in any editor you like, save and run. This skips the compile/link phase so familiar to Obj-C developers. So, pull up your favorite editor-remember, too, that most editors will be able to recognize Python code and syntax color, indent properly and so on, for you-and let's go.

Contained in /System/Library/Frameworks/Python.frame-work/ are the modules that Python uses for BridgeSupport. These can simply be imported into Python. First thing is first, our magic shebang line:

#!/usr/bin/env python

(Remember, if you have multiple versions of python on your system for some reason, under 10.5, the built-in BridgeSupport only works with Python 2.5. If you need you need to explicitly call that version, then do so). From here, we'll import the AddressBook framework:

from AddressBook import *

It's rare that I like or use the 'from blah import *' style, but there are times when it makes perfect sense. This, I feel, is one of them. We talked extensively about imports and namespaces in previous articles.

Let's create a new instance of an address book object:

aBook = ABAddressBook.sharedAddressBook()

Painless, right? This returns the address book for the logged-in user. Keeping this simple, let's grab the 'me' card for the logged in user and print it out:

myRecord = aBook.me()
print myRecord

That's it! In 3 lines of code, we get a good amount of information. Here's the output:

ABPerson (0x1ab0a40) {
   ABPersonFlags  : 0
   ABRelatedNames : {
      *  child  Edward R Marczak
}
   Address       : {
      *  work  {
    City = Anytown;
    Country = USA;
    CountryCode = us;
    State = AA;
    Street = "555 Any Street";
    ZIP = 11111;
}
}
   AIMInstant     : {
      *  home  myaim
}
   Creation       : 2005-10-28 09:45:40 -0400
   Email          : {
      *  work  marczak@radiotope.com
}
   First          : Edward
   JobTitle       : Owner
   Last           : Marczak
   Middle         : R
   Modification   : 2009-01-14 11:11:25 -0500
   Organization   : Radiotope
   Phone          : {
      *  mobile  555-555-5185
        home    555 555-5370
        main    555-555-5489
}
   Title          : Mr.
   Unique ID      : B3AD0F6B-4AB8-4E84-82C4-BF1EB7475659:ABPerson
}

Each of the properties in the record can be accessed and iterated over individually. Each property has a unique name used for this purpose. An illuminating method of discovering this, besides the Apple documentation is to use the dir() function that we've seen previously. Save your work and open a new document that contains this simple code:

#!/usr/bin/env python
import AddressBook
x = dir(AddressBook)
for i in x:
  print i

When you run it, you'll get an absolute ton of output, so pipe it through less or use a GUI editor that can run the code in its own window. It'll look like this:

ABACE
ABACL
ABAccessibilityMockUIElement
ABAddPropertiesAndTypes
ABAddRecord
ABAddToGroupCommand
ABAddressAttributedString
ABAddressBook
...
kABAIMHomeLabel
kABAIMInstantProperty
kABAIMWorkLabel
kABAddressCityKey
kABAddressCountryCodeKey
kABAddressCountryKey
kABAddressHomeLabel
kABAddressProperty
kABAddressStateKey
...
kCFXMLTreeErrorLocation
kCFXMLTreeErrorStatusCode
kEventABPeoplePickerDisplayedPropertyChanged
kEventABPeoplePickerGroupDoubleClicked
kEventABPeoplePickerGroupSelectionChanged
kEventABPeoplePickerNameDoubleClicked
kEventABPeoplePickerNameSelectionChanged
kEventABPeoplePickerValueSelectionChanged
kEventClassABPeoplePicker
kEventParamABPickerRef
objc
protocols
super

This lists every function and constant definition in the framework. In this case, we're interested in the block where each constant has the 'kAB' prefix. Each of these properties represents a potential field in the address book record - not all must be present. So, how can we tell which fields are present in a given record? We can ask. Back to our original code!

Here's a complete Python solution to dumping the current user's Address Book, I'll explain the parts not yet covered after this code listing.

Listing 1: dumpAB.py

#!/usr/bin/env python
from AddressBook import *
aBook = ABAddressBook.sharedAddressBook()
for person in aBook.people():
  properties = person.allProperties()
  for prop in properties:
    if prop == "com.apple.ABPersonMeProperty":
      continue
    elif prop == "com.apple.ABImageData":
      continue
    print prop, ":", person.valueForProperty_(prop)
  print '-'*60
  print

The people() method returns an array (an NSArray, specifically-the Obj-C Bridge deals with converting between the Obj-C types and Python types). We've previously covered Python for loops, and this one is no different. This loop iterates over each entry returned by the people() method, assigning it to person in each iteration.

With each person, we use the allProperties() method to determine the properties contained in that record. Then, we use another for loop to print only those properties. Note the if statement in this block: there are two properties present in each record that we're really not going to do anything with. Using a continue statement lets us restart the loop at the top.

Now, this isn't going to win any coding competitions, but look at how simple it is. No compiler or special IDE was needed to generate or run any of this.

What Happened? (Maybe)

Some of you may have seen an error pop up while running this program. Something about a "UnicodeDecodeError". What happened? This, partially, is the old-school Unix ASCII-ness colliding with modern sensibilities. You'll only see this error if one of your address book entries has Unicode characters in it (accent marks, Asian/Hebrew/Russian character sets and so on). Well, OS X is built to deal with this. Now, this depends on the environment in which you ran this. Terminal.app should actually have no problem as it's Unicode compliant. Surprisingly, some GUI text editors still don't handle Unicode properly, or, just need a little help. One thing you can do is give the interpreter a little hint: immediately following the magic shebang line (#!/usr/bin/env python), include the following:

# encoding: utf-8

This explicitly sets the encoding of the document. Additionally, Python itself has built-in support for Unicode strings. When printing a string, prefix it with 'u' to specify Unicode output. Like this:

print u'This is a Unicode string'

If you're printing a variable, it's similarly easy:

print u'%s' % (variable)

This is just one of those things that OS X users expect, and script authors need to bear in mind. Kind of like spaces in filenames...

Conclusion

There are actually a few more things we can cover about the Obj-C Bridge and its use in Python. However, we accomplished our goal for this month, and I hope you can see how easy some of these basic tasks are. You'll find that there are often several ways of approaching the code when using BridgeSupport. The methods used in this article are the most appropriate for the task at hand. See the References section below for the specific AddressBook documentation that I used to determine the bulk of this.

If we were more ambitious here, we could certainly do more with the data returned. Like write it out as a CSV file. AddressBook also supports group information, which I actually use fairy often, but that's a topic for next month.

Media of the month: I know, I usually suggest a good book, movie or music CD here, but this month is a little different. This month's suggestion is the outdoors - don't forget about it! Seriously, I'm not really a 'sun person,' but it is nice to take a walk with no laptop/phone/electronic device. Take a bike ride. Have a picnic. Take a (real) hike. Experience it. Just don't forget that there's a world outside of the LCD that we often sit a foot or two away from.

Hopefully, you're reading this at Apple's (sold out, again!) WWDC. Most of us from MacTech are here too (and you may have received this issue while on line for the Keynote - welcome!). Ping us, stop us in the halls - just say hello! See you next month.

References

"Address Book Programming Guide for Mac OS X," http://developer.apple.com/documentation/userexperience/Conceptual/AddressBook/AddressBook.pdf

"ABAddressBook Class Objective-C Reference," hhttp://developer.apple.com/documentation/UserExperience/Reference/AddressBook/Classes/ABAddressBook_Class/ABAddressBook_Class.pdf

"ABPerson C Reference," http://developer.apple.com/documentation/UserExperience/Reference/AddressBook/C/ABPersonRef/ABPersonRef.pdf


Ed Marczak is the Executive Editor for MacTech Magazine, and has been lucky enough to have ridden the computing and technology wave from early on. From teletype computing to MVS to Netware to modern OS X, his interest was piqued. He has also been fortunate enough to come into contact with some of the best minds in the business. Ed spends his non-compute time with his wife and two daughters.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.