Can you create an Mac OS X Service with Python? How? Can you create an Mac OS X Service with Python? How? python python

Can you create an Mac OS X Service with Python? How?


  • Open Automator.app and create a new service.

  • Select "Utilities" from the left-hand actions list, then drag the "Run Shell Script" action into the workflow.

  • Choose /usr/bin/python as your shell.

  • Type some python. For example:

:

import sysfor f in sys.stdin:     print "Hello World: " + f,
  • Save the service as, say, "Test"

  • Try it out in TextEdit.app. Type some text, select the text, then choose TextEdit -> Services -> Test from the menu. It should prepend "Hello World: " to each line of the text (as per the python code for f in sys.stdin)

The above example works with text. Presumably, it could be modified to work with other data types provided through the OS X Services system.


One way to build an OS X service using Python is to bundle your Python app with py2app and edit the Info.plist file to provide the menu entries you need in the Service menu.A sample plist file can be found at https://pyobjc.readthedocs.io/en/latest/examples/Cocoa/AppKit/SimpleService/index.htmlYou need to build the functionality to accept the commands you defined in the Info.plist's NSMessage section (see link mentioned above). You can use PyObjC to do this.This is a little bit trickier than using Automator, but has the advantage that you can bundle the whole functionality into a single App.


How to implement - I would say that there are three possibilities:

  1. You could use the Automator and create a service from a run shell script action.
  2. You could write an Automator action yourself using Xcode and use this in the Automator and create a new service out of it. The benefit would be that you could write an UI for it. You use bindings to bind it to the file's owner object. The binding keys are then reflected in the script as environment variables.
  3. Create a stand-alone service or a service going along with an application. I have implemented one included in the application. There you can also define a separate UI just for the service.

Input types - If you want to define the service to only show up if certain things are selected, such as text or URLs, you would define this in the Info.plist of that service. I think it should be possible to edit the Info.plist that was generated by the Automator if you want to further customize it.


Apple's Services Implementation Guide has a great example of debugging a service using TextEdit. It gives great help for debugging why a service is not showing up in the menu. See the Providing a Service | Testing section of the docs.