python pynput監聽鍵盤

會飛的八戒發表於2019-01-25
 1 """小白隨筆,大佬勿噴"""
 2 #鍵盤輸入
 3 from pynput.keyboard import Key,Controller,Listener
 4 keyboard = Controller()
 5 keyboard.press("a") #按下a
 6 keyboard.release("a") #鬆開a
 7 keyboard.press("A") #按下A
 8 keyboard.release("A") #鬆開A
 9 with keyboard.pressed(Key.shift): #按下shift
10     keyboard.press("a") #shift + a
11 keyboard.type("Hello World") #輸出文字
12 
13 #--------------------------------------------------
14 
15 # 鍵盤監聽
16 from pynput.keyboard import Key,Listener
17 def on_press(key):
18     if key == Key.enter:
19         print(`you press Enter`)
20     else:
21         return False #按鍵不是enter,停止監視
22 def on_release(key):
23     if key == Key.enter:
24         print(`you release Enter`)
25 #監聽鍵盤按鍵
26 with Listener(on_press=on_press,on_release=on_release) as listener:
27     listener.join()
28 #停止監視
29 Listener.stop()

 

相關文章