python-3.x – 如何同时收听D-Bus事件和IPC频道?

我有以下简单的代码.它会监听D-Bus并在创建新作业时执行某些操作.为了实现这一点,我需要启动GLib.MainLoop().run(),因为我发现了多个例子.

在这样做时,我希望程序能够持续监听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")

最佳答案 由于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
点赞