TweetFollow Us on Twitter

Mac in the Shell: Accessing AddressBook with PyObjC

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

Mac in the Shell: Accessing AddressBook with PyObjC

Using a specific Cocoa API from Python

by Edward Marczak

Introduction

Last month, we covered some basic text parsing using Python. I personally love the topic, as it's really applicable across a wide range of problems. But it was also fairly generic: that code will run on any platform with Python installed. Better yet: we can combine the text processing of standard Python with the OS X-specific PyObj-C libraries that let us tie into Cocoa APIs. This month, we'll look at AddressBook.

Accessing Address Book

First thing to remember: PyObj-C support is only built-in to OS 10.5 and above and with Python v2.5 and greater. If you're on a 10.4 system, this will not work out of the box. You'll need to get pyobjc support installed for 10.4 for yourself (further information and instructions can be found at http://pyobjc.sourceforge.net/downloads.html). This works just fine under 10.5 and, ummmmm... a certain future operating system.

The AddressBook framework in OS X is well documented by Apple. The developer site has plenty of information. A good starting point can be found at http://developer.apple.com/documentation/userexperience/Conceptual/AddressBook/AddressBook.html. All of the code presented in this article was written based on this documentation.

The code we'll look at this month is a small snippet of code that I actually use. As Executive Editor for MacTech, I send out a 'nag' message each month to authors that due dates are coming up. (Yes, I'm looking to automate this, but honestly like the personal touch that sending it out manually provides). I keep a group in AddressBook with the authors that have requested that I send them a reminder. Sometimes I use Mail.app, but sometimes I'm using a web-based mail interface that does not contain my contacts. Thanks to the magic of MobileMe, I tend to have my AddressBook no matter which machine I'm logged into. So then, what I need each month is a list of each address in the group I call "MacTech Editorial".

Like last month, I marvel at how little code we need to accomplish this. Here's the entire listing:

Listing 1 – MTDumpABGroup.py

#!/usr/bin/python2.5
import sys
from AddressBook import *
def GetAllABGroups(abref):
  groupdict = {}
  abgroups = abref.groups()
  for abgroup in abgroups:
    groupdict[abgroup.name()] = [abgroup.uniqueId()]
  return groupdict
def GetAllABListEmails(abref, abgroupid):
  address_dict = {}
  abgroup = abref.recordForUniqueId_(abgroupid)
  card = abgroup.members()
  for entity in card:
    emails = entity.valueForProperty_(kABEmailProperty)
    if emails is not None:
      address_dict[entity.uniqueId()] = emails.valueAtIndex_(0)
  return address_dict
def main():
  ab = ABAddressBook.sharedAddressBook()
  groups = GetAllABGroups(ab)
  groupid = None
  for group in groups:
    if group == "MacTech Editorial":
      groupid = groups[group][0]
      break
  if groupid is None:
    print "Group not found"
    sys.exit(1)
  addresses = GetAllABListEmails(ab, groupid)
  for i in addresses:
    print addresses[i] + ",",
if __name__ == '__main__':
  main()

Analyzing the code

Despite the brevity of the code involved, there's still some explaining to do. I'll follow the code as it executes, rather than go line-by-line from the top to the bottom. The only exceptions to that is the import statement at the top of the file (which does execute first). We need to import the AddressBook library for any of this to work, which is what make our job easy: Apple has already done the grunt work and we just need to exploit it.

The first statement to execute is the second to last: "if __name__..." This is the standard Python-ism that we've discussed in the past. This allows another Python app to import our program without running it. If we are running stand-alone, though, main() gets called.

First, in main(), we need a reference to the system's shared AddressBook. We instantiate a new copy of the ABAddressBook class and assign it to ab. Next, that reference gets passed into our GetGroups() function.

GetGroups() is more of a convenience function than anything, as we're really only going to use it once, but it's a decent illustration on pulling out all groups listed in the current user's address book. How do we obtain the list of groups in the address book? We ask! The groups() method returns an array of each group. In turn, each group has properties that can be obtained. In our case, we only care about the name, because as humans, that how we tend to identify things, and the group's unique ID, as we'll need to use that to request the members of the group. This function simply defines a dictionary that we fill with the requisite information. Once filled, we return that value from the function.

Back in main(), we simply loop though the groups that were returned, by name, and look for the one we're interested in. In our case, as mentioned, we're after the group named "MacTech Editorial". Once we find what we're looking for, we break out of the loop.

You'll notice that we set groupid to None prior to entering the loop. This just makes it easier for us to test if groupid has a value or not. Since it only gets set if we found the group we're looking for we use that in an if conditional:

if groupid is None:
    print "Group not found"
    sys.exit(1)

If groupid is still None when we exit the loop, we haven't found the group we're looking for and print a message and then exit with an exit code. It's useful to set a proper exit code so you can test for this in a shell script.

As an aside, another way to accomplish this would be to use a try block, but I found that a little more cumbersome for this program. Using a try block would eliminate the need to set groupid to None prior to entering the loop:

try:
  groupid
except NameError:
  print "Group not found"
  sys.exit(1)

For this particular endeavor, either method will suffice, however, I've gone with the "define as None" method above.

Once we've found the unique ID for the group we want to dump, we pass that off to GetAllListEmails(). First, we define a dictionary, addressdict, that will hold the addresses. Next, retrieve the address book group record that matches the given unique ID with recordForUniqueId. From there, we can gather all of the members of the group. How? We ask! The AddressBook Group class reference documentation lists the member method. The remainder of this function relies on the results returned from this call. A simple Python for loop allows us access to each person retrieved. Now, an AddressBook card may contain an entry that does not have an e-mail address, which is all we're really interested in. So, we retrieve all e-mail addresses associated with the card with the line:

emails = entity.valueForProperty_(kABEmailProperty)

This returns a multi-value of e-mail addresses attached to the card. For the purposes here, I'm only interested in one, and I'll take the first that's returned. But first, we need to see if any addresses were returned at all. The if conditional checks for addresses, and if some were returned, we'll take the first and add it to our dictionary:

address_dict[entity.uniqueId()] = emails.valueAtIndex_(0)

Once we've looped through all people returned, we have the dictionary we need. Time to return that back to the calling function.

Delivering the Results

Now for the easy part: printing out the results. We've covered looping through a Python dictionary plenty of times before, and that's all that's happening here:

for i in addresses:
  print addresses[i] + ",",

So, time to run the application! Naturally, you'll need to substitute an appropriate group name on line 31 (if group == "MacTech Editorial":) for a group that you have in your address book. Don't forget to chmod it as executable (chmod 770 MTDumpABGroup.py), and then go for it:

./MTDumpABGroup.py

bob@example.com, scott@example.net, bruce@mactech.com, wendel@example.org, alice@example.co.uk,

Thanks to one of OS X's many integrations between the shell and GUI, we can make our lives easier by piping the output into pbcopy:

./MTDumpABGroup | pbcopy

...and then just paste it into the To: field in your e-mail application (if it does indeed accept the address-comma-address format. I'm hard pressed to think of an e-mail client that doesn't, but I won't say one doesn't exist). You may need to drop the trailing comma, but since I've been using Gmail which just ignores the trailing comma, I just past the whole thing in.

Conclusion

In just 43 lines, including the stylistic spacing, we have a script that will dump all of the e-mail addresses associated with a particular group in Address Book. This example should illustrate several things: first, it's not difficult to get Cocoa via Python. It's well documented. Second, you don't have to spend a lifetime trying to find a solution. My itch (getting a list of e-mail addresses from a particular group) was easily scratched.

Media of the month: My reading list has become incredibly long...so much to read! But I gravitated toward a particular book in my pile (by the way – I really do prefer books. As in the real, physical variety. Perhaps it's just tactile, but, no Kindle for me yet). "Brewing Up a Business: Adventures in Entrepreneurship" by Sam Calagione seemed to be beckoning. Now, this may be the first book that I'm recommending before I actually finish it. I'm about three-fifths of the way through. It's so far really enjoyable. It's targeted at people starting their own business, so, for the consultants and potential consultants out there, it seems like something that should be on your reading list.

Until next month, keep practicing Python!

References

Address Book Class Reference: http://developer.apple.com/documentation/userexperience/Reference/AddressBook/Classes/ABAddressBook_Class/Reference/Reference.html#//apple_ref/occ/instm/ABAddressBook/people

Address Book Group Reference: http://developer.apple.com/documentation/UserExperience/Reference/AddressBook/Classes/ABGroup_Class/Reference/Reference.html

Address Book Person Reference: http://developer.apple.com/documentation/UserExperience/Reference/AddressBook/C/ABPersonRef/Reference/reference.html


Ed Marczak is the Executive Editor of MacTech Magazine. He has written for MacTech since 2004.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.