本文介绍了使用dbus仅使用Python发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个Python程序。我只想从一个发送消息(一个长字符串)到另一个,并且我想使用dbus。
现在,有一种简单的方法吗?

I have 2 Python programs. I just want to send a message (a long string) from the one to the other, and I want use dbus.Now, is there an easy way to do this?

例如,如果消息很小,我已经部分解决了将消息放入其中的问题。路径。但是后来我不得不使用外部程序dbus-send:

For example, if the message is very small, I have partially solved the problem putting the message in the path. But then I had to use the external program dbus-send:

服务器(python):

Server (python):

import dbus,gtk
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
def msg_handler(*args,**keywords):
    try:
        msg=str(keywords['path'][8:])
        #...do smthg with msg
        print msg
    except:
        pass

bus.add_signal_receiver(handler_function=msg_handler, dbus_interface='my.app', path_keyword='path')
gtk.main()

客户(bash :():

Client (bash:( ):

dbus-send --session /my/app/this_is_the_message my.app.App

是否可以用Python编写客户端?还是有更好的方法来实现相同的结果?

Is there a way to write the client in Python? or also, is there a better way to achieve the same result?

推荐答案

以下是使用接口方法调用的示例:

Here is an example that uses interface method calls:

服务器:

#!/usr/bin/python3

#Python DBUS Test Server
#runs until the Quit() method is called via DBUS

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk
import dbus
import dbus.service
from dbus.mainloop.glib import DBusGMainLoop

class MyDBUSService(dbus.service.Object):
    def __init__(self):
        bus_name = dbus.service.BusName('org.my.test', bus=dbus.SessionBus())
        dbus.service.Object.__init__(self, bus_name, '/org/my/test')

    @dbus.service.method('org.my.test')
    def hello(self):
        """returns the string 'Hello, World!'"""
        return "Hello, World!"

    @dbus.service.method('org.my.test')
    def string_echo(self, s):
        """returns whatever is passed to it"""
        return s

    @dbus.service.method('org.my.test')
    def Quit(self):
        """removes this object from the DBUS connection and exits"""
        self.remove_from_connection()
        Gtk.main_quit()
        return

DBusGMainLoop(set_as_default=True)
myservice = MyDBUSService()
Gtk.main()

客户端:

#!/usr/bin/python3

#Python script to call the methods of the DBUS Test Server

import dbus

#get the session bus
bus = dbus.SessionBus()
#get the object
the_object = bus.get_object("org.my.test", "/org/my/test")
#get the interface
the_interface = dbus.Interface(the_object, "org.my.test")

#call the methods and print the results
reply = the_interface.hello()
print(reply)

reply = the_interface.string_echo("test 123")
print(reply)

the_interface.Quit()

输出:

$ ./dbus-test-server.py &
[1] 26241
$ ./dbus-server-tester.py 
Hello, World!
test 123

希望有帮助。

这篇关于使用dbus仅使用Python发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 12:35