Thursday, September 8, 2011

Adding buttons(actions) while using python-notify (libnotify) + An example

Python wrapper for libnotify ie python-notify lacks any documentation.

Well, the only thing for documentation is to read pynotify.defs and pynotify.c from the /src directory of source code.

I made a script while ago to delete current song in mpd in bash. I then thought of using libnotify for the same script in python.

There is not much information about adding buttons to notifications while using python-notify so hopefully it will help someone :)

#!/usr/bin/python2

import gtk
import pynotify
import os

MPD_LIBRARY_LOCATION = "/var/lib/mpd/music/"

class DelSongMPD:
        
    def __init__(self):
        #Initing the pynotif
        pynotify.init("mpd")
        n = pynotify.Notification("Deleting a song", "Do you really want to delete the song")
        n.set_urgency(pynotify.URGENCY_LOW)
        n.add_action("action_delete", "Delete", self.deleteSong)
        n.add_action("no_dontdelete", "No delete", self.doNothing)
        n.show()
        gtk.main()

    def deleteSong(self, notifyObj, action):
        print "Deleting the song"
        mpcProcess = os.popen("mpc -f %file%")
        try:
            # [:-1] to delete the trailing newline
            os.remove(MPD_LIBRARY_LOCATION+mpcProcess.readline()[:-1])
            #Deleting song from playlist
            os.popen("mpc del $(mpc -f %position% | head -n 1)")
        except:
            print "Something really went wrong"
        notifyObj.close()
        gtk.main_quit()

  
    def doNothing(self,notifyObj, action):
        print "Do not delete"
        notifyObj.close()
        gtk.main_quit()

if __name__ == "__main__":
    obj = DelSongMPD()

1 comment:

  1. You should add n.connect("closed", gtk.main_quit) before the gtk.main(), otherwise the main loop does not terminate if the notification is closed without the user pressing either button.

    ReplyDelete