9

我想制作一个可以在后台运行但在鼠标事件或键事件发生时打印文本的 python 脚本。是否有任何库/内置功能来实现这一点?或者我可以调用任何系统命令来获取此信息?成为root没有问题。

4

2 回答 2

13

我猜,你可能会为 evdev 使用 python 绑定:http ://packages.python.org/evdev/index.html 。在教程中,他们给出了一个键盘示例,但鼠标事件应该类似:

>>> from evdev import InputDevice, categorize, ecodes
>>> from select import select
>>> dev = InputDevice('/dev/input/event1')

>>> print(dev)
device /dev/input/event1, name "Dell Dell USB Keyboard", phys "usb-0000:00:12.1-2/input0"

>>> while True:
...    r,w,x = select([dev], [], [])
...    for event in dev.read():
...        if event.type == ecodes.EV_KEY:
...            print(categorize(event))
... # hitting a and holding space
key event at 1337016188.396030, 30 (KEY_A), down
key event at 1337016188.492033, 30 (KEY_A), up
key event at 1337016189.772129, 57 (KEY_SPACE), down
key event at 1337016190.275396, 57 (KEY_SPACE), hold
key event at 1337016190.284160, 57 (KEY_SPACE), up
于 2012-09-12T11:28:38.190 回答
4

看看pynput,例如:

from pynput.keyboard import Key, Listener
#defining function to print when key is pressed
def on_press(key):
  print('{0} pressed'.format(
    key))
#defining function to print when key is released
def on_release(key):
  print('{0} release'.format(
    key))
  if key == Key.esc:
    # Stop listener
    return False

# Collect events until released
with Listener(
    on_press=on_press,
    on_release=on_release) as listener:
    listener.join()
于 2016-09-12T16:33:17.383 回答