Part V: Appendixes

 < Day Day Up > 

19.2. Python for Mac OS X Geeks

The following sections list a few of the Python extras that are available for or come with Mac OS X.

19.2.1. Carbon

As with Perl, you can access Carbon APIs from within Python. You can find a list of Carbon APIs with pydoc Carbon; short-named modules (such as CF) are usually the API you're interested in. The corresponding long-named module (such as CoreFoundation) will be the constants you need for the API. You can read documentation for a specific module with pydoc Carbon.MODULE, as in pydoc Carbon.CF.

Python also includes a number of other modules (have a look in /System/Library/Frameworks/Python.framework/Versions/2.3/lib/python2.3/platmac), including EasyDialogs, which you can use to produce a Python version of the Perl example we showed earlier:

     #!/usr/bin/pythonw     import EasyDialogs     import re     die_in_the_vacuum_of_space = 0     answer = \       EasyDialogs.AskString("Tell me how good you thought my poem was.", "")     s = "counterpoint the surrealism of the underlying metaphor"     if re.compile(s).search(answer):       die_in_the_vacuum_of_space = 1     print die_in_the_vacuum_of_space 

19.2.2. Apple Events

Appscript ( is a bridge between Python and Apple Events that lets you write Python scripts in a very AppleScript-eqsue fashion. For example, consider the following snippet of AppleScript:

     tell app "Finder" to get name of every folder of home 

Using Appscript, you could write this as the following Python script:

     #!/usr/bin/pythonw     from appscript import *     app('Finder') ) 

At the time of this writing, we could not get Appscript to work under Tiger. We suggest that you check the Appscript home page and grab the latest version.

19.2.3. PyObjC

PyObjC ( is a bridge between Python and Objective-C, and includes access to Cocoa frameworks, support for Xcode, and extensive documentation and examples. To install PyObjC, you can either download an installer from its web site, or grab the source code and run the command sudo python bdist_mpkg open, which builds a metapackage and launches the Mac OS X installer on it.

Here's a very simple example that creates an NSString and prints it out:

     #!/usr/bin/python     from Foundation import *     import objc     string = NSString.stringWithCString_("Hello, World")     print string # prints Hello, World 

Once you've got PyObjC installed, check out the documentation in /Developer/Python/PyObjC/Documentation and see the examples in /Developer/Python/PyObjC/Examples.

     < Day Day Up > 

    Mac OS X Tiger for Unix Geeks
    Mac OS X Tiger for Unix Geeks
    ISBN: 0596009127
    EAN: 2147483647
    Year: 2006
    Pages: 176 © 2008-2017.
    If you may any questions please contact us: