How to listen for D-Bus events and IPC channel at the same time?

I have the following simple code. He listens to the D-Bus and does something when a new task is created. To do this, I need to run GLib.MainLoop().run(), as it was presented by several examples that I found.

At the same time, I want the program to constantly listen on the IPC bus and do something when the message is received. But obviously this does not work since my program is stuck in GLib.MainLoop().run().

How to implement what allows me to listen to D-Bus and IPC at the same time?

#!/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")
+4
source share
1 answer

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
+2

Source: https://habr.com/ru/post/1661375/


All Articles