首页 > 解决方案 > 如何从 Python 将无符号值发送到 dBus

问题描述

我正在尝试使用 PyQt5 的 DBus 模块与 KDE PowerManagerAgent 进行交互。调用 AddInhibition 方法时,我需要将第一个参数作为 uint32(无符号整数)发送,但代码将值作为单整数整数发送。

代码使用 Python 3 编写

self.dBus = QtDBus.QDBusConnection.sessionBus()
msg = QtDBus.QDBusMessage.createMethodCall(self.dBusService, self.dBusPath,self.dBusInterface,'AddInhibition')
msg << 1 << who << reason
reply = QtDBus.QDBusReply(self.dBus.call(msg))

查看 dbus-monitor 的输出,我可以看出代码确实联系了 powermonitor,但由于第一个参数的类型为 int32,因此无法找到正确的 AddInhibition 方法

尝试调用 AddInhibition 时 dbus-monitor 的输出

称呼

方法调用时间=1549706946.073218 发件人=:1.172 -> 目的地=org.kde.Solid.PowerManagement.PolicyAgent 串行=5 路径=/org/kde/Solid/PowerManagement/PolicyAgent;接口=org.kde.Solid.PowerManagement.PolicyAgent;member=AddInhibition int32 1 字符串“这个”字符串“失败”

回复

错误时间=1549706946.073536 发件人=:1.29 -> 目的地=:1.172 error_name=org.freedesktop.DBus.Error.UnknownMethod reply_serial=5 字符串“在接口 'org.kde.Solid.PowerManagement.PolicyAgent' 中没有这样的方法 'AddInhibition'对象路径'/org/kde/Solid/PowerManagement/PolicyAgent'(签名'iss')"

使用 QDBusViewer 应用程序时 dbus-monitor 的输出

称呼

方法调用时间=1549723045.320128 发件人=:1.82 -> 目的地=org.kde.Solid.PowerManagement.PolicyAgent 串行=177 路径=/org/kde/Solid/PowerManagement/PolicyAgent;接口=org.kde.Solid.PowerManagement.PolicyAgent;member=AddInhibition uint32 1 字符串“This” 字符串“Works”

回复

方法返回时间=1549723045.320888 发件人=:1.29 -> 目的地=:1.82 序列=1370 回复序列=177 uint32 30

由于 Python 不是强类型的,我如何指定参数必须输入为无符号整数?

标签: pythonqt5dbusqtdbus

解决方案


您可以DBusArgument通过指定参数的 来使用该类来执行此操作QMetaType

例如,假设您想使用RequestNamefrom 的方法org.freedesktop.DBus(请参阅规范)。参数是一个无flags符号整数,所以你会遇到这个问题:

>>> from PyQt5.QtDBus import QDBusConnection, QDBusInterface
>>> sessionbus = QDBusConnection.sessionBus()
>>> iface = QDBusInterface("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", sessionbus)
>>> c = iface.call('RequestName', 'com.mydomain.myapp', 4)
>>> c.arguments()
['Call to RequestName has wrong args (si, expected su)\n']

所以,它说它有一个字符串和一个整数 ( si),但它想要一个字符串和一个无符号整数 ( su)。因此,我们将使用QDBusArgument该类并指定QMetaType.UInt

>>> from PyQt5.QtCore import QMetaType
>>> from PyQt5.QtDBus import QDBusConnection, QDBusInterface, QDBusArgument
>>> sessionbus = QDBusConnection.sessionBus()
>>> iface = QDBusInterface("org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", sessionbus)
>>> a1 = QDBusArgument()
>>> a1.add('com.mydomain.myapp', QMetaType.QString)
>>> a2 = QDBusArgument(4, QMetaType.UInt)
>>> c = iface.call('RequestName', a1, a2)
>>> c.arguments()
[1]

由于字符串很好,因此不必是QDBusArgument. 我只是想展示构造它的两种方法(使用.add()方法和仅使用构造函数)。


推荐阅读