python - 如何从 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 不是强类型的,我如何指定参数必须输入为无符号整数?
解决方案
您可以DBusArgument
通过指定参数的 来使用该类来执行此操作QMetaType
。
例如,假设您想使用RequestName
from 的方法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()
方法和仅使用构造函数)。
推荐阅读
- reactjs - PATCH 请求似乎没有到达 Express.js 服务器
- android - Google Play 商店推出问题 - 如何替换现有的实时应用
- javascript - 根据键值对将对象数组连接成一个新对象
- linux - Linux内核“BUG: bad page state in process..”理解
- c# - 不起作用 - ASP.NET MVC
- r - 使用自定义轴标题编写 ggplot2 函数
- docker - 如何使用 jenkinsfile 将 docker 镜像部署到部署服务器?
- oracle - ORA-01481: 无效的数字格式模型
- reactjs - 为什么 TS 在我的情况下会出现以下错误:“数字”类型的参数不可分配给“从不”类型的参数?
- c# - 当用户解锁 Windows 时,应用程序需要在 Windows 7 中执行一些任务