#!/usr/bin/env python #coding:utf-8 import sys import os def getlist(width, is_reload, list_name): if os.path.isfile('/tmp/vimitunes_playlist') and not is_reload: playlist_str = open('/tmp/vimitunes_playlist', 'r').read() else: playlist_temp = open('/tmp/vimitunes_playlist', 'w') applescript = open('/tmp/vimitunes_script', 'w') applescript.write(r''' on run {} tell application "iTunes" set Output to "" set myTracks to (tracks of playlist "%s") repeat with myTrack in myTracks set myTitle to (name of myTrack) set myAlbum to (album of myTrack) set myArtist to (artist of myTrack) set myID to (database ID of myTrack) set Output to Output & myID & "\t" & myTitle & "\t" & myAlbum & "\t" & myArtist & "\n" end repeat return Output end tell end run ''' % list_name) applescript.close() playlist_str = os.popen('osascript /tmp/vimitunes_script').read() os.unlink('/tmp/vimitunes_script') playlist_temp.write(playlist_str) playlist_temp.close() playlist = playlist_str.decode('utf-8').split('\n') tracks = [line.split('\t') for line in playlist if line] if len(tracks): col_width = width / (len(tracks[0]) - 1) for track in tracks: for col in track[1:]: print col[:col_width].ljust(col_width, ' ').encode('utf-8'), print def play(num, list_name): songs = open('/tmp/vimitunes_playlist','r').read().split('\n') song = songs[num - 1].split('\t') ID = song[0] applescript = open('/tmp/vimitunes_script', 'w') applescript.write(r''' tell application "iTunes" play (item 1 of (tracks of playlist "%s" whose database ID is %s)) end tell ''' % (list_name, ID)) applescript.close() os.popen('osascript /tmp/vimitunes_script') os.unlink('/tmp/vimitunes_script') if __name__ == '__main__': if sys.argv[1] == 'getlist': getlist(int(sys.argv[2]), sys.argv[3] == '1', sys.argv[4]) elif sys.argv[1] == 'play': play(int(sys.argv[2]), sys.argv[3]) exit(0)