簡體   English   中英

如何從 Python 向 dBus 發送無符號值

[英]How to send unsigned values to dBus from Python

我正在嘗試使用 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 sender=:1.172 -> destination=org.kde.Solid.PowerManagement.PolicyAgent serial=5 path=/org/kde/Solid/PowerManagement/PolicyAgent; interface=org.kde.Solid.PowerManagement.PolicyAgent; member=AddInhibition int32 1字符串“這個”字符串“失敗”

回復

錯誤時間=1549706946.073536 sender=:1.29 -> destination=:1.172 error_name=org.freedesktop.DBus.Error.UnknownMethod reply_serial=5 字符串“在接口'org.kde.Solid.PowerManagement'atPolicyA中沒有這樣的方法'AddInhibition'對象路徑'/org/kde/Solid/PowerManagement/PolicyAgent'(簽名'iss')”

使用 QDBusViewer 應用程序時 dbus-monitor 的輸出

稱呼

方法調用時間=1549723045.320128 sender=:1.82 -> destination=org.kde.Solid.PowerManagement.PolicyAgent serial=177 path=/org/kde/Solid/PowerManagement/PolicyAgent; interface=org.kde.Solid.PowerManagement.PolicyAgent; member=AddInhibition uint32 1字符串“這個”字符串“作品”

回復

方法返回時間=1549723045.320888 sender=:1.29 -> destination=:1.82 serial=1370 reply_serial=177 uint32 30

由於 Python 不是強類型,我如何指定參數必須輸入為無符號整數?

您可以使用DBusArgument類通過指定參數的QMetaType來執行此操作。

例如,假設您想使用org.freedesktop.DBusRequestName方法(請參閱規范)。 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()方法和只使用構造函數)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM