Use dbus to just send a message in Python

Deadly 提交于 2019-12-03 17:11:24

Here is an example that uses interface method calls:

Server:

#!/usr/bin/python3

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

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()

Client:

#!/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()

Output:

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

Hope that helps.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!