在Python中向dbus对象添加方法

2 投票
2 回答
1051 浏览
提问于 2025-04-16 05:50

我需要在Python中创建一个dbus对象,方法的名称是在运行时决定的。

我尝试的代码基本上是这样的:

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

DBusGMainLoop(set_as_default=True)
gobject.threads_init()

class greg(dbus.service.Object):
        def __init__(self):
                dbus.service.Object.__init__(self, bus, "/greg")

        @dbus.service.method(
                dbus_interface="com.blah.blah",
                in_signature="",
                out_signature="")
        def dance(self):
                print "*busts a move*"

def func(self):
    pass
func = dbus.service.method(
        dbus_interface="com.blah.blah",
        in_signature="",
        out_signature="")(func)
setattr(greg, "do_nothing", func)

bus = dbus.SystemBus()
busname = dbus.service.BusName("com.blah.blah", bus)
obj = greg()
loop = gobject.MainLoop()
loop.run()

在这个例子中,函数'dance'可以在接口上使用,但函数'do_nothing'却不能。我不明白为什么会这样?有没有办法实现我想要的效果?

2 个回答

0

func() 没有 dbus 服务头,所以它无法被识别。
当 greg 对象没有这个属性时,你怎么能把 "do_nothing" 设置给你的函数呢?

检查一下这个对象是否有这个属性,这样可以确保你的代码能顺利执行。

print(hasattr(greg, "do_nothing"))

另外,如果你能在将来更加注意 Python 的代码风格指南,那就太好了:
http://www.python.org/dev/peps/pep-0008/

0

我猜这个 do_nothing 方法是可以用的,但可能看不见。你有没有试着直接调用它?

能看见的东西是由 Introspect 方法返回的,而这个方法又依赖于 _dbus_class_table 这个类属性。所以你需要更新这个属性,才能让 Introspect 返回最新的 D-Bus 方法列表。

撰写回答