Safe URL System Service

Following on the previous post, I decided to try something new (for me). I wanted to turn my Safe URL Python script into a services extension. The easiest way I know to make a new services menu item is through Automator. I typically shy away from services because my list of text services is already quite long and disorganized. In this case, I really just wanted to try converting a Python script into a system service.

It turns out to be ridiculously easy. Here’s the process:

1. Create a new Automator document and choose “Service” as the type.

New Service

2. In this case I also checked the “Output replaces selected text” option

3. Next, add the Run Shell Script action.

4. From the “Shell” menu choose “/usr/bin/python” as the type

Shell Action

5. Replace the line that says “print f” with the Python code.

6. To get at the selected string, just use the variable “f” in the Python script.

Here’s an example of yesterday’s script as a system service:

URL Service

Here’s the script:

:::python

import sys
from urlparse import urlparse, urlunparse
import urllib

for f in sys.stdin:
    varUrl = f

    # Create a parsed url. See: http://docs.python.org/library/urlparse.html
    o = urlparse(varUrl)

    # Remove unsupported characters. '/' is a safe character
    newPath = urllib.quote(o.path, '/')

    newParams =  urllib.quote(o.params, '/')

    # Create a new tuple with our new quoted path as a replacement
    n = o[0:2] + (newPath ,) + o[3:]

    # Reassemble the entire url
    baseUrl = urlunparse(n)
    print baseUrl

A couple of points to note. There is no need to include the hash-bang as the first line of the Python code. That’s taken care of by the Shell Action. Also, the script needs to import the sys module so that it can get at the stdin (which is the selected text the services action acts on).

This isn’t ground-breaking. This is exactly how it is intended to be used. I just wanted to provide another option for people that don’t have Keyboard Maestro and show how many of the macros I discuss can be created using free tools that come with OS X. I do work with things other than Keyboard Maestro you know.