在Linux上的python中侦听全局键组合

时间:2014-03-13 01:29:06

标签: python linux keyboard-shortcuts hotkeys

我刚刚写了一个小程序,每隔几分钟从flickr下载一个新壁纸。

现在我想添加“喜欢”壁纸的功能,所以它会比非喜欢或不喜欢的壁纸更频繁地出现。

我想为此功能指定全局键盘快捷键。

例如:如果按ctrl + 7,它将在Python中执行某种“喜欢”的功能。

是否有任何库(在JavaScript中,例如,我可以使用shortcut("ctrl-b", someFunction);定义快捷方式的库)

否则,我该怎么做呢?我见过this similar SO question,但它已经过时了。

3 个答案:

答案 0 :(得分:6)

我不知道任何旨在扩展的库。然而,正如你的链接所说,pykeylogger的后端提供了一个如何做到的例子,但它似乎有点过于复杂,你需要。

pykeylogger使用python-xlib模块捕获X显示上的按键。有人已经在pastebin上创建了一个更轻松的例子。以下是按原样复制的来源。

from Xlib.display import Display
from Xlib import X
from Xlib.ext import record
from Xlib.protocol import rq

disp = None

def handler(reply):
    """ This function is called when a xlib event is fired """
    data = reply.data
    while len(data):
        event, data = rq.EventField(None).parse_binary_value(data, disp.display, None, None)

        # KEYCODE IS FOUND USERING event.detail
        print event.detail

        if event.type == X.KeyPress:
            # BUTTON PRESSED
            print "pressed"
        elif event.type == X.KeyRelease:
            # BUTTON RELEASED
            print "released"

# get current display
disp = Display()
root = disp.screen().root

# Monitor keypress and button press
ctx = disp.record_create_context(
            0,
            [record.AllClients],
            [{
                    'core_requests': (0, 0),
                    'core_replies': (0, 0),
                    'ext_requests': (0, 0, 0, 0),
                    'ext_replies': (0, 0, 0, 0),
                    'delivered_events': (0, 0),
                    'device_events': (X.KeyReleaseMask, X.ButtonReleaseMask),
                    'errors': (0, 0),
                    'client_started': False,
                    'client_died': False,
            }])
disp.record_enable_context(ctx, handler)
disp.record_free_context(ctx)

while 1:
    # Infinite wait, doesn't do anything as no events are grabbed
    event = root.display.next_event()

您必须扩展处理程序以满足您的需要,而不是仅仅打印到屏幕,然后将其转换为单独的线程。

(痛苦)替代方案是直接听键盘,而不依赖于外部库或X会话。在linux中,所有内容都是一个文件,您可以在后台将keyboard input will be in /dev/input作为文件读取,例如open('/dev/input/even2', 'rb')。这不建议,因为它需要升级权限,找出哪个设备是键盘,然后创建自己的键映射。只是想让你知道必要时有什么可能。

编辑:还找到Global keybinding on X using Python gtk3,它似乎有更多示例优点。

答案 1 :(得分:4)

对于那些想要查看我最终使用的代码的人,我提出了一点要点right here.

每台计算机的密钥代码可能略有不同。此外,我迅速编写的keylistener类不受各种可能发生的问题的保护。再说一遍,它对我来说效果很好。

答案 2 :(得分:1)

这是一个更清洁的版本,它也解码和打印键名,而不仅仅是数字:

#!/usr/bin/env python2

# Captures all keyboard and mouse events, including modifiers
# Adapted from http://stackoverflow.com/questions/22367358/
# Requires python-xlib

from Xlib.display import Display
from Xlib import X, XK
from Xlib.ext import record
from Xlib.protocol import rq


class Listener:
  def __init__(self):
    self.disp = None
    self.keys_down = set()

  def keycode_to_key(self, keycode, state):
    i = 0
    if state & X.ShiftMask:
      i += 1
    if state & X.Mod1Mask:
      i += 2
    return self.disp.keycode_to_keysym(keycode, i)

  def key_to_string(self, key):
    keys = []
    for name in dir(XK):
      if name.startswith("XK_") and getattr(XK, name) == key:
        keys.append(name.lstrip("XK_").replace("_L", "").replace("_R", ""))
    if keys:
      return " or ".join(keys)
    return "[%d]" % key

  def keycode_to_string(self, keycode, state):
    return self.key_to_string(self.keycode_to_key(keycode, state))

  def mouse_to_string(self, code):
    if code == X.Button1:
      return "Button1"
    elif code == X.Button2:
      return "Button2"
    elif code == X.Button3:
      return "Button3"
    elif code == X.Button4:
      return "Button4"
    elif code == X.Button5:
      return "Button5"
    else:
      return "{%d}" % code

  def down(self, key):
    self.keys_down.add(key)
    self.print_keys()

  def up(self, key):
    if key in self.keys_down:
      self.keys_down.remove(key)
      self.print_keys()

  def print_keys(self):
    keys = list(self.keys_down)
    print "Currently pressed:", ", ".join(keys)

  def event_handler(self, reply):
    data = reply.data
    while data:
      event, data = rq.EventField(None).parse_binary_value(data, self.disp.display, None, None)
      if event.type == X.KeyPress:
        self.down(self.keycode_to_string(event.detail, event.state))
      elif event.type == X.KeyRelease:
        self.up(self.keycode_to_string(event.detail, event.state))
      elif event.type == X.ButtonPress:
        self.down(self.mouse_to_string(event.detail))
      elif event.type == X.ButtonRelease:
        self.up(self.mouse_to_string(event.detail))

  def run(self):
    self.disp = Display()
    XK.load_keysym_group('xf86')
    root = self.disp.screen().root
    ctx = self.disp.record_create_context(0,
                                          [record.AllClients],
                                          [{
                                            'core_requests': (0, 0),
                                            'core_replies': (0, 0),
                                            'ext_requests': (0, 0, 0, 0),
                                            'ext_replies': (0, 0, 0, 0),
                                            'delivered_events': (0, 0),
                                            'device_events': (X.KeyReleaseMask, X.ButtonReleaseMask),
                                            'errors': (0, 0),
                                            'client_started': False,
                                            'client_died': False,
                                          }])
    self.disp.record_enable_context(ctx, lambda reply: self.event_handler(reply))
    self.disp.record_free_context(ctx)
    while True:
      event = root.display.next_event()


if __name__ == "__main__":
  Listener().run()

输出如下:

Currently pressed: Alt
Currently pressed:
Currently pressed: Alt
Currently pressed: Alt, Tab
Currently pressed: Alt
Currently pressed: Alt, Tab
Currently pressed: Alt
Currently pressed: Alt, Tab
Currently pressed: Alt
Currently pressed: Alt, Tab
Currently pressed: Alt
Currently pressed: Alt, Tab
Currently pressed: Alt
Currently pressed:
Currently pressed: Control
Currently pressed: Control, a
Currently pressed: Control
Currently pressed: Control, Shift
Currently pressed: Control, Shift, A
Currently pressed: Control, Shift