2016-11-20 26 views
4

我有以下简单的代码。它听取D-Bus并在创建新工作时做一些事情。为了实现这个目标,我需要启动GLib.MainLoop().run(),因为我发现了多个示例。如何同时收听D-Bus事件和IPC频道?

虽然这样做,我希望程序不断收听IPC总线,并在收到消息时执行某些操作。但显然这是行不通的,因为我的程序卡在GLib.MainLoop().run()

如何实现让我在同一时间收听D-Bus和IPC的东西?

#!/usr/bin/env python3.4 
import asgi_ipc as asgi 
from gi.repository import GLib 
from pydbus import SystemBus 
from systemd.daemon import notify as sd_notify 

def main(): 
    bus = SystemBus() 
    systemd = bus.get(".systemd1") 
    systemd.onJobNew = do_something_with_job() 

    channel_layer = asgi.IPCChannelLayer(prefix="endercp") 

    # Notify systemd this unit is ready 
    sd_notify("READY=1") 

    GLib.MainLoop().run() 

    while True: 
     message = channel_layer.receive(["endercp"]) 
     if message is not (None, None): 
      do_something_with_message(message) 


if __name__ == "__main__": 
    # Notify systemd this unit is starting 
    sd_notify("STARTING=1") 

    main() 

    # Notify systemd this unit is stopping 
    sd_notify("STOPPING=1") 

回答

2

由于IPCChannelLayer.receive()不会阻塞,因此您可以在空闲回调中运行它。试试这个:

callback_id = GLib.idle_add(GLib.PRIORITY_DEFAULT_IDLE, poll_channel, data=channel_layer) 
GLib.MainLoop().run() 
GLib.idle_remove_by_data(channel_layer) 

# ... 

def poll_channel(channel_layer): 
    message = channel_layer.receive(["endercp"]) 
    if message is not (None, None): 
     do_something_with_message(message) 
    return GLib.SOURCE_CONTINUE