URL handlers with PyObjC

Following up on my previous post about writing Cocoa applications to handle custom URL schemes, I wanted to add on how to do it with a PyObjC Python application. I'm definitely still getting up to speed on PyObjC so there may be an easier way to do this, but I was able to get it to work. All the scripting dictionary and Info.plist settings are the same, you just need to add a Python implementation of URLCommandHandler. The tricky part is getting the Python URLCommandHandler object to be made available to the Objective C runtime so that it can be linked up with the incoming apple event.

The way I did that was to create a Nib file that contained a subclass of NSScriptCommand named URLCommandHandler. NSScriptCommand is not part of the normal list of classes you can subclass in Interface Builder so you need to tell IB to read the header file for it, it's part of Foundation.framework. Once you have that defined you can use the Nib in the same way as usual for PyObjC and the Objective C runtime will be able to see your Python class. You just need to create the subclass, there aren't any other connections involved. Because of this, I'm guessing there's probably a way to do this without using IB to make the connection. I just haven't figured out how yet.

The Python class is really simple.


from PyObjCTools import NibClassBuilder, AppHelper
from Foundation import *
from AppKit import *

NibClassBuilder.extractClasses("MainMenu")

class URLHandlerCommand(NibClassBuilder.AutoBaseClass):  
    def performDefaultImplementation(self):
        urlString = self.directParameter()
    
        print "url = %s" % urlString

        return None

if __name__ == "__main__":
    AppHelper.runEventLoop()

  

It's actually very easy once you know how to do it. Doing this should also enable you to add general AppleScript support to Cocoa applications written in Python.

Posted by Kimbro Staken

Tuesday Dec 16, 2003 at 6:01 PM
Recommended Sites