Automation with Python

KosmicTask Help

Automation with Python

Automation with Python

Now that we have seen that automation is possible from Ruby there is going to be no stopping us. The following example implements our Pages task in Python using PyObjC. The approach is exactly the same as in the Ruby implementation.

import ScriptingBridge
import os
import sys

# get application - for more information see the Python Usage document
app = ScriptingBridge.SBApplication.applicationWithBundleIdentifier_("com.apple.iWork.pages")

pagesDocFilePath = sys.argv[1]
rtfDocFilePath = pagesDocFilePath + ".rtf"

# open pages
myDoc = app.open_(pagesDocFilePath)

# save document
myDoc.saveAs_in_("SLDocumentTypeRichText", rtfDocFilePath)

# close document
myDoc.closeSaving_savingIn_(False, None)

# define our result file
resultFile = "result.html"

# convert our file
command = "textutil -convert html -output \"%s\" \"%s\"" % (resultFile, rtfDocFilePath)
os.system(command)

# return a YAML inline format dictionary with filename
print "--- {kosmicFile: %s, kosmicInfo: file returned}" % resultFile

This Python implementation performs just like all our other versions. Again, note that we explicitly import the ScriptingBridge.