我正在使用 QThread
(pyside) 来处理 X11 上的全局热键。我有一些简单的 while 循环,看起来像:
while self.doRun:
event=root.display.next_event()
if event.type==X.KeyPress:
....
但 next_event()
以等待实际事件而闻名。那么如何在不等待另一次击键的情况下停止该循环呢?我正在考虑通过 Xlib 使用按键发送假事件,但我认为这不是正确的方法。此外 .terminate()
在该事件上不是一个选项......使用 pyside 它会使整个应用程序崩溃:
Fatal Python error: This thread state must be current when releasing
有什么想法吗?
最佳答案
这是一个迟到的答案,但我遇到了同样的问题,所以也许它对某人仍然有帮助。
基于documentation , 你可以使用 Python 的 select module接收超时事件。
使用 select 的解决方案基本上包括两个步骤:1) 处理所有未决事件,以及 2) 等待 select 调用,直到新的 I/O 事件到达。如果没有事件到达,该方法将在一定时间后超时。
这样的事件循环看起来像这样:
# Main loop, handling events
def loop(self):
self.loop_cond = True
timeout=5 # timeout in seconds
while self.loop_cond:
# handle all available events
i = self.d.pending_events()
while i > 0:
event = self.display.next_event()
self.handle_event(event)
i = i - 1
# Wait for display to send something, or a timeout of one second
readable, w, e = select.select([self.display], [], [], timeout)
# if no files are ready to be read, it's an timeout
if not readable:
self.handle_timeout()
我用 small example 创建了一个要点.
关于python - 如何破解 xlib 的 next_event()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27088697/