Skip to main content
 首页 » 编程设计

python之使用 Python-dbus 在 dbus 上发射信号

2025年05月04日13cmt

我希望能够首先调用一个简单的脚本来启用或禁用上网本的外部显示器。我正在使用 XFCE 作为我的桌面运行 Fedora 17。我看到我应该能够使用 python 和 python-dbus 来打开和关闭切换开关。我的问题是我无法弄清楚如何发出信号以使新设置生效。不幸的是,Python 不是我经常使用的语言。我的代码是:

import dbus 
item = 'org.xfce.Xfconf' 
path = '/org/xfce/Xfconf' 
channel = 'displays' 
base = '/' 
setting = '/Default/VGA1/Active' 
 
bus = dbus.SessionBus() 
remote_object = bus.get_object(item, path) 
remote_interface = dbus.Interface(remote_object, "org.xfce.Xfconf") 
 
if remote_interface.GetProperty(channel, setting): 
  remote_interface.SetProperty(channel, setting, '0') 
  remote_object.PropertyChanged(channel, setting, '0') 
else: 
  remote_interface.SetProperty(channel, setting, '1') 
  remote_object.PropertyChanged(channel, setting, '0') 

它正在失败并被踢出:

Traceback (most recent call last):   File "./vgaToggle", line 31, in <module> 
remote_object.PropertyChanged(channel, setting, '0')    
File "/usr/lib/python2.7/site-packages/dbus/proxies.py", line 140, in __call__ 
**keywords)    
File "/usr/lib/python2.7/site-packages/dbus/connection.py", line 630, in call_blocking 
message, timeout) dbus.exceptions.DBusException:  
org.freedesktop.DBus.Error.UnknownMethod: Method "PropertyChanged" 
with signature "sss" on interface "(null)" doesn't exist 

我花了一些时间进行搜索,但没有找到很多 python 示例来做任何与此接近的事情。提前致谢。

请您参考如下方法:

PropertyChanged 是一个信号,而不是一个方法。您与之通信的服务负责发出信号。在这种情况下,只要相应对象或接口(interface)上的属性值发生变化,PropertyChanged 就应该隐式触发。

这应该在您调用 remote_interface.SetProperty(...) 时隐式发生,您不需要像方法一样显式“调用”信号。

如果您有兴趣接收信号,您需要设置一个 glib 主循环并调用 connect_to_signal在您的代理对象上,将回调方法传递给它以进行调用。