Python 3.x 如何同时收听D总线事件和IPC通道?
我有以下简化的代码。它侦听D总线,并在创建新作业时执行某些操作。为此,我需要启动GLib.MainLoop().run(),正如我发现的多个示例所示 在执行此操作时,我希望程序能够持续监听IPC总线,并在收到消息时执行某些操作。但显然,这不起作用,因为我的程序卡在了GLib.MainLoop().run() 如何实现让我同时听D总线和IPC的功能Python 3.x 如何同时收听D总线事件和IPC通道?,python-3.x,python-3.4,glib,dbus,systemd,Python 3.x,Python 3.4,Glib,Dbus,Systemd,我有以下简化的代码。它侦听D总线,并在创建新作业时执行某些操作。为此,我需要启动GLib.MainLoop().run(),正如我发现的多个示例所示 在执行此操作时,我希望程序能够持续监听IPC总线,并在收到消息时执行某些操作。但显然,这不起作用,因为我的程序卡在了GLib.MainLoop().run() 如何实现让我同时听D总线和IPC的功能 #!/usr/bin/env python3.4 import asgi_ipc as asgi from gi.repository import
#!/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