gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 03:26:59 28 4
gpt4 key购买 nike

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

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com