我已经阅读了一些与动态创建python方法相关的主题,并且按照它们的说明进行操作,但是它不起作用。我不知道是否是因为我使用装饰器@
或其他东西。
代码在这里,非常简单。
运行此代码时,未发生任何错误,但是当我使用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()
最佳答案
您有错别字:singal_example
而不是signal_example
在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)
# ...