2014-03-13 78 views
3

我有2個Python程序。我只想發送一條消息(一個長字符串)從一個到另一個,我想使用dbus。 現在,有沒有簡單的方法來做到這一點?使用dbus在Python中發送消息

例如,如果消息非常小,我已部分解決了將消息放入路徑中的問題。但後來我不得不使用外部程序DBUS-發送:

服務器(蟒蛇):

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嗎?還是有更好的方法來實現相同的結果?

回答

6

以下是一個使用接口方法調用的示例:

服務器:

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

客戶:

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

希望有所幫助。

+1

我希望不要創建任何新的服務類...無論如何謝謝。 – user1922691