Reputation: 71
Here's the gist of my little program
One python script that checks if there is a new file (movie file) in a certain directory and update an sqlite3 database accordingly, thus queuing files to be processed. Running every minute with launchctl.
Another python script that does the actual processing of converting the files with HandBrake command line interface. Also running every minute with launchctl.
In that second script, once the conversion is done, I want to start an applescript that will import the file into iTunes with certain metadata.
So, new movie file in directory -> file gets queued -> file gets converted -> file gets imported in iTunes.
The problem I have is with the applescript part. If I run my second python script (the one that converts then import) through the terminal, everything runs smoothly. The file gets converted and then the applescript imports it into iTunes. But if it's launchctl that is launching the script, it seems it's skipping the applescript part.
Here's the bit with the applescript in python
import subprocess, shlex
cmd = "/usr/bin/osascript /Users/alexis/Developer/Media/import_iTunes.scpt '{0}' ".format(file)
subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
And the applescript (I've removed some part for simplicity)
on run argv
set newTrackPath to posix file (item 1 of argv)
tell application "iTunes"
activate
set newTrack to add newTrackPath
end tell
end run
I've tried using subprocess.call(cmd), os.system(cmd) and subprocess.Popen(cmd).
The problem seems to be that you can't start osascript from python when that very python script is launched with launchctl.
Anyone has an explanation or a work around?
Thank you
Upvotes: 1
Views: 1103
Reputation: 3259
What user is launchd
running the Python script under? I assume you're running it as a User Agent for the current user; if not, you should.
Your shlex
code is both redundant and unsafe (e.g. consider what'll happen when you try to import I Wanna Be Bobby's Girl.mp3
). Just assemble the list of arguments directly.
Your Python code doesn't bother to wait for the subprocess to complete or check its return code, so any failures are going to pass silently. You need to address that: it'll be a lot easier to troubleshoot any subprocess errors if you actually know what they are.
If you don't care about the AppleScript's output, you can just use the check_call
convenience function, which'll throw an exception if the AppleScript fails:
subprocess.check_call(["/usr/bin/osascript",
"/Users/alexis/Developer/Media/import_iTunes.scpt", file])
(Or, if you've got an actual reason to be using Popen
directly and have elided relevant code for 'simplicity', show it so we can see what you're actually doing.)
You might also want to tweak your launchd
XML so that your Python script's stderr gets written to a file for easy review.
Upvotes: 2