gpt4 book ai didi

python - 如何从 Python 优雅地终止 GLib 主循环

转载 作者:太空宇宙 更新时间:2023-11-03 20:44:30 27 4
gpt4 key购买 nike

我编写了一个简单的 Python 脚本,用于根据某个 DBus 信号(即使 PulseAudio 接收器静音的守护进程)发送桌面通知。它有效,但用 Ctrl-C 终止脚本导致以下回溯:

Traceback (most recent call last):
File "./notify.py", line 32, in <module>
loop.run()
File "/usr/lib/python3.7/site-packages/gi/overrides/GLib.py", line 495, in run
super(MainLoop, self).run()
File "/usr/lib/python3.7/contextlib.py", line 119, in __exit__
next(self.gen)
File "/usr/lib/python3.7/site-packages/gi/_ossighelper.py", line 251, in register_sigint_fallback
signal.default_int_handler(signal.SIGINT, None)
KeyboardInterrupt

我尝试使用 atexit 注册清理功能调用GLib.MainLoop().quit() ,但这似乎不起作用。我知道我可以用 try: ... except: ... 捕获异常 block ,但是有更好的方法来处理这个问题吗?

脚本代码如下:

import atexit

import gi
gi.require_version('Notify', '0.7')
from gi.repository import Notify
from pydbus import SessionBus

def handle_muted(interface, changed_props, invalidated_props):
if changed_props["Muted"]:
n = Notify.Notification.new("muted")
n.set_urgency(Notify.Urgency(0))
n.show()

@atexit.register
def cleanup():
Notify.uninit()
props.onPropertiesChanged = None
loop.quit()

bus = SessionBus()
proxy = bus.get("org.mypadaemon")
props = proxy["org.freedesktop.DBus.Properties"]

if __name__ == '__main__':
from gi.repository import GLib

Notify.init("My PA Daemon")
props.onPropertiesChanged = handle_muted

loop = GLib.MainLoop()
loop.run()

最佳答案

定义自定义信号处理程序有效:

import signal

def sigint_handler(sig, frame):
if sig == signal.SIGINT:
loop.quit()
else:
raise ValueError("Undefined handler for '{}'".format(sig))

并在 if __name__ == '__main__' block 中:

signal.signal(signal.SIGINT, sigint_handler)

关于python - 如何从 Python 优雅地终止 GLib 主循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56684286/

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