为什么不能用Python中的dbus调用org.freedesktop.NetworkManager中的方法?

时间:2012-12-06 14:22:52

标签: python ubuntu dbus

我在交互式python shell中尝试了下面的代码并在代码的第3行得到了跟随错误,使用D-Feet我看到路径和接口存在于总线中,并且使用命令dbus-send我能够获取设备,请参阅此消息的结尾。为什么不在python中使用这段代码? PS:我使用ubuntu 12.04,在ubuntu 11中也尝试过,同样的问题。

代码:

import dbus
bus = dbus.SessionBus()
obj = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
t = dbus.Interface(obj, "org.freedesktop.NetworkManager")
t.GetDevices()

输入错误输入代码的第3行:

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 244, in get_object
    follow_name_owner_changes=follow_name_owner_changes)
  File "/usr/lib/pymodules/python2.7/dbus/proxies.py", line 241, in __init__
    self._named_service = conn.activate_name_owner(bus_name)
  File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 183, in activate_name_owner
    self.start_service_by_name(bus_name)
  File "/usr/lib/pymodules/python2.7/dbus/bus.py", line 281, in start_service_by_name
    'su', (bus_name, flags)))
  File "/usr/lib/pymodules/python2.7/dbus/connection.py", line 630, in call_blocking
    message, timeout)
DBusException: org.freedesktop.DBus.Error.ServiceUnknown: The name org.freedesktop.NetworkManager was not provided
 by any .service files

运行的Shell命令:

dbus-send --system --print-reply --reply-timeout=2000 --type=method_call --dest=org.freedesktop.NetworkManager /org/freedesktop/NetworkManager org.freedesktop.NetworkManager.GetDevices

输出:

method return sender=:1.2 -> dest=:1.69 reply_serial=2
   array [
      object path "/org/freedesktop/NetworkManager/Devices/0"
   ]

这只是一个例子,我想知道为什么不工作,如果我改变第3行(注意第一个参数中的DBus名称):

obj = bus.get_object('org.freedesktop.DBus', '/org/freedesktop/NetworkManager')

不会发生错误,但在此界面中,方法GetDevices不存在。

1 个答案:

答案 0 :(得分:5)

在命令行示例中,您要求系统总线:

dbus-send --system ...

在你的Python代码中,你要求的是会话总线:

bus = dbus.SessionBus()

如果您通过系统总线尝试请求,我认为您会发现它有效:

>>> import dbus
>>> bus = dbus.SystemBus()
>>> obj = bus.get_object('org.freedesktop.NetworkManager', '/org/freedesktop/NetworkManager')
>>> t = dbus.Interface(obj, "org.freedesktop.NetworkManager")
>>> t.GetDevices()
dbus.Array([dbus.ObjectPath('/org/freedesktop/NetworkManager/Devices/0'), dbus.ObjectPath('/org/freedesktop/NetworkManager/Devices/1')], signature=dbus.Signature('o'))
>>>