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

Combo Quest (Games)
Combo Quest 1.0 Device: iOS Universal Category: Games Price: $.99, Version: 1.0 (iTunes) Description: Combo Quest is an epic, time tap role-playing adventure. In this unique masterpiece, you are a knight on a heroic quest to retrieve... | Read more »
Hero Emblems (Games)
Hero Emblems 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: ** 25% OFF for a limited time to celebrate the release ** ** Note for iPhone 6 user: If it doesn't run fullscreen on your device... | Read more »
Puzzle Blitz (Games)
Puzzle Blitz 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Puzzle Blitz is a frantic puzzle solving race against the clock! Solve as many puzzles as you can, before time runs out! You have... | Read more »
Sky Patrol (Games)
Sky Patrol 1.0.1 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0.1 (iTunes) Description: 'Strategic Twist On The Classic Shooter Genre' - Indie Game Mag... | Read more »
The Princess Bride - The Official Game...
The Princess Bride - The Official Game 1.1 Device: iOS Universal Category: Games Price: $3.99, Version: 1.1 (iTunes) Description: An epic game based on the beloved classic movie? Inconceivable! Play the world of The Princess Bride... | Read more »
Frozen Synapse (Games)
Frozen Synapse 1.0 Device: iOS iPhone Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: Frozen Synapse is a multi-award-winning tactical game. (Full cross-play with desktop and tablet versions) 9/10 Edge 9/10 Eurogamer... | Read more »
Space Marshals (Games)
Space Marshals 1.0.1 Device: iOS Universal Category: Games Price: $4.99, Version: 1.0.1 (iTunes) Description: ### IMPORTANT ### Please note that iPhone 4 is not supported. Space Marshals is a Sci-fi Wild West adventure taking place... | Read more »
Battle Slimes (Games)
Battle Slimes 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: BATTLE SLIMES is a fun local multiplayer game. Control speedy & bouncy slime blobs as you compete with friends and family.... | Read more »
Spectrum - 3D Avenue (Games)
Spectrum - 3D Avenue 1.0 Device: iOS Universal Category: Games Price: $2.99, Version: 1.0 (iTunes) Description: "Spectrum is a pretty cool take on twitchy/reaction-based gameplay with enough complexity and style to stand out from the... | Read more »
Drop Wizard (Games)
Drop Wizard 1.0 Device: iOS Universal Category: Games Price: $1.99, Version: 1.0 (iTunes) Description: Bring back the joy of arcade games! Drop Wizard is an action arcade game where you play as Teo, a wizard on a quest to save his... | Read more »

Price Scanner via MacPrices.net

14-inch M4 Pro/M4 Max MacBook Pros on sale th...
Don’t pay full price! Get a new 14″ MacBook Pro with an M4 Pro or M4 Max CPU for up to $320 off Apple’s MSRP this weekend at these retailers…they are the lowest prices available for these MacBook... Read more
Get a 15-inch M4 MacBook Air for $150 off App...
A couple of Apple retailers are offering $150 discounts on new 15″ M4 MacBook Airs this weekend. Prices at these retailers start at $1049: (1): Amazon has new 15″ M4 MacBook Airs on sale for $150 off... Read more
Unreal Mobile is offering a $100 discount on...
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, 13, and SE phones... Read more
16-inch M4 Pro MacBook Pros on sale for $250-...
Don’t pay full price! Amazon has 16-inch M4 Pro MacBook Pros (Silver or Black colors) on sale right now for up to $300 off Apple’s MSRP. Shipping is free. These are the lowest prices currently... Read more
Get a 14-inch M4 MacBook Pro for up to $240 o...
Amazon is offering a $150-$250 discount on Apple’s 14-inch M4 MacBook Pros right now. Shipping is free. Be sure to select Amazon as the seller, rather than a third-party seller: – 14″ M4 MacBook Pro... Read more
Clearance 14-inch M3 Pro MacBook Pros availab...
B&H Photo has clearance 14″ M3 Pro MacBook Pros (in Black or Silver) on sale for $500 off original MSRP, only $1499. B&H offers free 1-2 day delivery to most US addresses: – 14″ 11-Core M3... Read more
Sams Club is offering a $50 discount on Titan...
Sams Club has Titanium Apple Watch Series 10 models on sale for $50 off Apple’s MSRP. Sams Club Membership required. Note that sale prices are for online orders only, in-store prices may vary. Choose... Read more
Sunday Sale: Apple’s latest 13-inch M4 MacBoo...
Amazon has new 13″ M4 MacBook Airs on sale for $150 off MSRP right now, starting at $849. Sale prices apply to most colors and configurations. Be sure to select Amazon as the seller, rather than a... Read more
Apple’s M4 Mac minis on sale for record-low p...
B&H Photo has M4 and M4 Pro Mac minis in stock and on sale right now for up to $150 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses. Prices start at only $469: – M4... Read more
Week’s Best Deals: 14-inch M4 MacBook Pros fo...
Don’t pay full price! These retailers are offering $200-$250 discounts on new 14-inch M4 MacBook Pros this week…they are the lowest sale prices available for new MacBook Pros: (1): Amazon is offering... Read more

Jobs Board

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