python-3.x - 如何同时监听D-Bus事件和IPC channel ?

标签 python-3.x python-3.4 glib dbus systemd

我有以下简单的代码。它监听 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

关于python-3.x - 如何同时监听D-Bus事件和IPC channel ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40708043/

相关文章:

Python - Gspread请求错误401

pygame - Colliderect() 意外触发

c - 为什么当元素大小大于实际值大小时会出现 `g_array_append_val` 段错误?

c++ - 使用 valgrind 调查 Glib 内存泄漏

python - PyQt5 QGraphicsView透明背景

python - pyinstaller 无法使用 tkinter

python - 在 PyCharm 中为特定文件设置不同的解释器

Django 教程第 2 部分模板——未反射(reflect) base_site.html 更改

python - 如何安装Python 3.4及以上版本的日历模块?

C++ Gtk 线程。我做对了吗?