Python DBus Example

Here is an attempt to read the messages being sent out as notifications by DBUS. I was not successful in actually reading the messages as it doesn't seem like the messages are being sent directly over DBUS. Anyhow, I thought I would post it here, perhaps someone might find it being useful.

# You must initialize the gobject/dbus support for threading
# before doing anything.
import gobject
gobject.threads_init()
from pprint import pprint

from dbus import glib
glib.init_threads()

# Create a session bus.
import dbus
bus = dbus.SessionBus()

from dbus.mainloop.glib import DBusGMainLoop

DBusGMainLoop(set_as_default=True)


import gobject


def dump(obj):
  '''return a printable representation of an object for debugging'''
  newobj=obj
  if '__dict__' in dir(obj):
    newobj=obj.__dict__
    if ' object at ' in str(obj) and not newobj.has_key('__type__'):
      newobj['__type__']=str(obj)
    for attr in newobj:
      newobj[attr]=dump(newobj[attr])
  return newobj


# Create an object that will proxy for a particular remote object.
remote_object = bus.get_object("org.freedesktop.Notifications", # Connection name
                               "/org/freedesktop/Notifications" # Object's path
                             )

# Introspection returns an XML document containing information
# about the methods supported by an interface.
print ("Introspection data:\n")
print remote_object.Introspect()


# Get the power management object
power = bus.get_object('org.freedesktop.Notifications',
                       '/org/freedesktop/Notifications')
iface = dbus.Interface(power, 'org.freedesktop.Notifications')

# Hibernate the system
if iface.GetCapabilities():
    print iface.GetCapabilities()

def play(a, b, member=None):
  pprint(dump(a))
  pprint(dump(b))
  pprint(dump(member))

def catchall_signal_handler(*args, **kwargs):
    #pprint(dump(kwargs))

    print kwargs['message'].get_args_list()
 
    #print ("Caught signal (in catchall handler) " + kwargs['dbus_interface'] )
#    for arg in args:
#        print "        " + str(arg)


#bus.add_signal_receiver(catchall_signal_handler, interface_keyword='dbus_interface', member_keyword='member')
#bus.add_signal_receiver(my_func,
bus.add_signal_receiver(catchall_signal_handler, dbus_interface = "org.freedesktop.Notifications", signal_name='Notify')
#dbus_interface = "com.example.TestService", message_keyword='dbus_message'
iface.connect_to_signal(None, catchall_signal_handler,  message_keyword='message', sender_keyword = 'send', destination_keyword = 'dest', interface_keyword 
= 'iface', member_keyword = 'mem', path_keyword = 'path')


loop = gobject.MainLoop()
loop.run()