2009-12-19 50 views
5

尋找使用Python從一個Mac應用程序聽distributed notifications幫助/教程/示例代碼聽通知。我知道py-objc lib是python和mac/cocoa類之間的橋樑,Foundation庫可以用來添加觀察者,但需要查找關於如何使用它來監控iTunes的示例或教程。你如何從Mac上的iTunes(使用NSDistributedNotificationCenter)

+0

的iTunes是否實際上交的分佈式通知,這些天? – 2009-12-19 15:03:49

+0

是的,它確實....在com.apple.iTunes.player下,使用通知表我可以看到它們。 – ismail 2009-12-19 16:26:29

回答

11

若有人通過對這個問題,我想通了,怎麼聽,下面的代碼可以工作,但是訪問屬性似乎不像標準python屬性訪問那樣工作。

更新:你不像python ie(.x)那樣訪問屬性,代碼已被更新到下面,現在它生成一個名爲song_details的字典。

向上date3:更新到現在繼承NSObject的代碼,刪除了從類中添加addObserver。將保持代碼更新github,這裏沒有更新的更新。

import Foundation 
from AppKit import * 
from PyObjCTools import AppHelper 

class GetSongs(NSObject): 
    def getMySongs_(self, song): 
     song_details = {} 
     ui = song.userInfo() 
     for x in ui: 
      song_details[x] = ui.objectForKey_(x) 
     print song_details 

nc = Foundation.NSDistributedNotificationCenter.defaultCenter() 
GetSongs = GetSongs.new() 
nc.addObserver_selector_name_object_(GetSongs, 'getMySongs:', 'com.apple.iTunes.playerInfo',None) 

NSLog("Listening for new tunes....") 
AppHelper.runConsoleEventLoop()