在 Python 中使用字符串参数进行 Linux Desktopbus 进程间通信

问题描述

我目前正在努力在 python 中调用带有字符串参数的 desktopbus 方法。我尝试使用 dbus-python 库(https://dbus.freedesktop.org/doc/dbus-python/ --> 我也对其他库开放)。我可以调用不使用任何参数或纯整数参数的方法,如下所示:

from gi.repository import GLib
import sys
import dbus
import dbus.service
import dbus.mainloop.glib
from threading import Thread


class DesktopBus:

   def __init__(self,ip,port):
       self.ip = ip
       self.port = port
       dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
       self.proxy = {}
       self.properties_manager = {}
       self.thread = None
       self.mainLoop = GLib.MainLoop()

   def call_method(self,str_interface_name,str_method_name,param_list):
       """
       in:
       str_interface_name: eg. "com.MyService"
       str_method_name: Method name as string.
       param_list as list: eg [] or [1,2,3]
       """
       params = ""
       for i in param_list:
           params += str(i) + ","
       return eval('self.properties_manager["' + str_interface_name + '"].' + str_method_name + '(' +
                   params + 'dbus_interface="' + str_interface_name + '")')

db = DesktopBus("192.168.0.2","50000")
db.openInterface("SomeService")
db.call_method("SomeService","function",[1,3])

代码适用于整数参数。但是,对于字符串,它会失败(例如 db.call_method("SomeService",["a","b"])。任何人都可以帮我 :)

解决方法

你没有显示完整的错误信息,所以我只能猜测。


我无法运行它,但对我来说问题是它会将 ["a","b"] 放在字符串中作为 (a,b,...) 并且 eval() 将处理 a,{{1} } 作为变量。

您可能必须将每个字符串都放在外部 b 中以将 ' ' 作为文本的一部分 - " "

['"a"','"b"']

db.callmethod("SomeService","function",['"a"','"b"'])

给出字符串:

param_list = ["a","b"]

params = ""
for i in param_list:
    params += str(i) + ","

print(params)

但是

a,

给出你需要的字符串:

param_list = ['"a"','"b"']

params = ""
for i in param_list:
    params += str(i) + ","

print(params)

但坦率地说,您可以尝试在没有 "a","b", 的情况下执行此操作,然后它就不需要额外的 eval(),因为它不会将其全部转换为字符串。

' '