Example AppleScript interface running on Mac

import serial, os

ALLOWED_SCRIPTS = ["edit"]

ser = serial.Serial('/dev/tty.pybook')

print "Waiting for message..." while True:

msg = serial.readline().strip() if msg == "exit":

print >> serial, "bye!" break elif msg in ALLOWED_SCRIPTS:

print "Running script: " + msg os.system("osascript %s.script" % msg) print >> serial, "Script ok!"

The idea is that the phone client is used to choose one of the scripts to execute on the PC side. Once again, we can use Example 59 as the phone client. Again, echoing should be disabled by setting ECHO = False in the client.

In Python, the os.system() function is used to execute an external command. In this case, we execute the command osascript that is used to interpret AppleScripts on Mac OS X. However, the script name must exist on the allowed_SCRIPTS list before it can be executed. This makes sure that a malicious user cannot connect to the server and execute any command she likes, for instance to format the hard disk. If the phone sends the line exit, the connection is shut down. Otherwise the user can execute as many commands as she wishes.

Naturally, we need some AppleScripts to be executed. Without going into details, we give here a simple AppleScript example that first activates the Finder application on the Mac and then opens a new file in the

TextEdit application. Make sure you have no other TextEdit file open when you run it. Write the following code to a file called edit.script and save it to the same folder as the above server program.

tell application "Finder" activate open application file "TextEdit.app" of folder\

"Applications" of startup disk end tell

The server is executed similarly to the previous server example. Now, however, the only sensible message to send from the phone is 'edit', which corresponds to the AppleScript file name without the ending '.script'. Once the message is received by the PC, you should see the TextEdit application start up.

Based on this teaser, you can start developing AppleScripts of your own that may control various applications, such as iTunes, iPhoto, QuickTime, DVD Player, Keynote, iSync or iCal. Just save the new AppleScript to some file that ends with '.script' and add its name to the allowed_SCRIPTS list. For instance, by combining keyboard events from Chapter 5 to this example, you could control, say a DVD player, using the arrow keys on your phone.

0 0

Post a comment

  • Receive news updates via email from this site