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

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.