你如何在Mac上收听来自iTunes的通知(使用NSDistributedNotificationCenter)

ism*_*ail 5 python macos notifications pyobjc

寻找帮助/教程/示例代码使用python来监听来自mac上的应用程序的分布式通知.我知道py-objc lib是python和mac/cocoa类之间的桥梁,Foundation库可用于添加观察者,但是查找有关如何使用它来监视iTunes的示例或教程.

ism*_*ail 11

如果有人来到这个问题,我想出了如何倾听,下面的代码工作.但是,访问属性似乎不像标准的python属性访问那样工作.

更新:您不像在python中那样访问属性,即(.x),代码已在下面更新,它现在生成一个名为song_details的字典.

Update3:更新代码,现在继承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()
Run Code Online (Sandbox Code Playgroud)