【问题标题】:Use dbus to just send a message in Python使用 dbus 在 Python 中发送消息
【发布时间】:2014-04-18 20:42:14
【问题描述】:

我有 2 个 Python 程序。我只想从一个到另一个发送一条消息(一个长字符串),我想使用 dbus。 现在,有没有简单的方法可以做到这一点?

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

服务器(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:( ):

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

有没有办法用 Python 编写客户端?或者,有没有更好的方法来达到同样的效果?

【问题讨论】:

    标签: python dbus


    【解决方案1】:

    这里是一个使用接口方法调用的例子:

    服务器:

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

    希望对您有所帮助。

    【讨论】:

    • 我希望不要创建任何新的服务类...无论如何谢谢。
    猜你喜欢
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    • 2018-06-28
    • 2010-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-14
    相关资源
    最近更新 更多