2012-09-12 70 views
7

我想製作一個python腳本,可以在後臺運行,但在mouseevent或keyevent發生時打印文本。是否有任何庫/內置功能來實現這一點?或者我可以調用任何系統命令來獲取此信息?作爲根是沒有問題的。我怎樣才能捕捉mouseevents和keyevents在Linux上使用python背景

+0

如此 - 就像一個鍵盤記錄? –

+0

是的。 ...字符限制... – jett

+0

您必須從'/ dev/input'中的設備讀取輸入事件。 –

回答

11

我想,你可能會使用Python綁定evdev: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 
2

看看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()