2012-06-07 36 views
2

我讀過一些與動態創建python方法有關的主題,並且我遵循了他們的說明,但它不起作用。我不知道是否因爲我使用裝飾者@或其他東西。在python中動態創建DBus信號

代碼在這裏,很簡單。

運行此代碼時,沒有發生錯誤,但是當我使用D-feet(一種檢查dbus信息的工具)時,找不到我創建的新信號。

#!/usr/bin/python 

import dbus 
import dbus.service 
import dbus.glib 
import gobject 
from dbus.mainloop.glib import DBusGMainLoop 

import psutil 

class EventServer(dbus.service.Object): 
    i = 0 

    @dbus.service.signal('com.github.bxshi.event') 
    def singal_example(self,msg): 
     """ example of singals 
     """ 
     print msg 

    def __init__(self): 
     bus_name = dbus.service.BusName('com.github.bxshi.event', bus=dbus.SessionBus()) 
     dbus.service.Object.__init__(self, bus_name, '/com/github/bxshi/event') 

    def create(self): 
     self.i +=1 
     setattr(self.__class__, 'signal_'+str(self.i), self.singal_example) 


if __name__ == "__main__": 
    DBusGMainLoop(set_as_default=True) 
    bus = dbus.SessionBus() 
    eventserver = EventServer() 
    gobject.timeout_add(1000,eventserver.create) 
    loop = gobject.MainLoop() 
    loop.run() 

回答

0
  1. 你有一個錯字:的singal_example代替signal_example
  2. create - 方法您在高級應召setattr。我不知道你想做什麼,但你應該簡單地發出信號

這是固定的例子:

#!/usr/bin/python 

import dbus 
import dbus.service 
import dbus.glib 
import gobject 
from dbus.mainloop.glib import DBusGMainLoop 

#import psutil 

class EventServer(dbus.service.Object): 
    i = 0 

    @dbus.service.signal('com.github.bxshi.event') 
    def signal_example(self,msg): 
     """ example of singals 
     """ 
     print msg 

    def __init__(self): 
     bus_name = dbus.service.BusName('com.github.bxshi.event', bus=dbus.SessionBus()) 
     dbus.service.Object.__init__(self, bus_name, '/com/github/bxshi/event') 

    def create(self): 
     self.i +=1 
     #setattr(self.__class__, 'signal_'+str(self.i), self.singal_example) 
     self.signal_example('msg: %d' % self.i) 


if __name__ == "__main__": 
    DBusGMainLoop(set_as_default=True) 
    bus = dbus.SessionBus() 
    eventserver = EventServer() 
    gobject.timeout_add(1000,eventserver.create) 
    loop = gobject.MainLoop() 
    loop.run() 

在此之後,你可以連接到信號:

# ... 
bus = dbus.Bus() 
service=bus.get_object('com.github.bxshi.event', '/com/github/bxshi/event') 
service.connect_to_signal("signal_example", listener) 
# ... 
+1

我不想發射信號,我想要的是在運行時創建一個新的信號。我的意思是,起初我可能只有1個信號,並且在來自其他過程的請求之後,我會爲它創建一個新信號。 – bxshi