views:

179

answers:

3

I'd like to search for tracks on iTunes using a Python script on Mac OS/X. I found a way to access the iTunes application through:

iTunes = SBApplication.applicationWithBundleIdentifier_("com.apple.iTunes")

but I haven't figured out (yet) the way to perform searches. A little help appreciated.

Disclaimer: OS/X newbie here.

Note: I am not looking for ways to access the XML/plist database directly.

A: 

It might be useless answer, but i'd advise you to use AppleScript instead of Pyton. Take a look at this piece of code:

tell application "iTunes"
 repeat with bTrack in (every track of playlist 7 whose artist contains "Golden")
...

Perfect tutorials might be found here: http://macscripter.net/viewtopic.php?id=25631

dsa
Thanks but I'd rather stick with Python.
jldupont
and python using SBApplication is using the same calls Applescript makes so it is just a different syntax
Mark
A: 

What do you think of:


script = '''tell application "iTunes"
  repeat with bTrack in (every track of playlist 7 whose artist contains "Golden")
    print bTrack
  end repeat
end tell'''
tracks,_ = subprocess.Popen("osascript -e %s" % script, stdout=subprocess.PIPE).communicate()
trackList = tracks.split('\n')

I never tested this, though....

Krumelur
+1  A: 

You might want to check out appscript (note, you'll need ASDictionary for online help):

>>> import appscript
>>> iTunes = appscript.app("iTunes")
>>> lib = iTunes.playlists['Library']
>>> for trk in lib.tracks():
...     if re.search("test", trk.name()):
...         print trk.name()

This might give you the most control by iterating over each item, but there's a much faster way too, by using applescript hooks to do the searching:

>>> trks = lib.tracks[appscript.its.name.contains('test')]
>>> print trks.name()

Check out these appscript usage examples as well.

James Snyder
Cool! Thanks a lot! +1
jldupont
no problem. I didn't notice the objc answer mentioned a bit earlier, but I suspect this might provide a more covenient API to access scriptable applications.The docs are a bit sparse, but once you wrap your brain around how appscript is structured, it's not too hard to look at an applescript example and translate how one would do it with appscript.
James Snyder