Python pynput监听键盘

#键盘输入
from pynput.keyboard import Key,Controller,Listener
keyboard = Controller()
keyboard.press("a") #按下a
keyboard.release("a") #松开a
keyboard.press("A") #按下A
keyboard.release("A") #松开A
with keyboard.pressed(Key.shift): #按下shift
    keyboard.press("a") #shift + a
keyboard.type("Hello World") #输出文字

#--------------------------------------------------

# 键盘监听
from pynput.keyboard import Key,Listener
def on_press(key):
    if key == Key.enter:
        print('you press Enter')
    else:
        return False #按键不是enter,停止监视
def on_release(key):
    if key == Key.enter:
        print('you release Enter')
#监听键盘按键
with Listener(on_press=on_press,on_release=on_release) as listener:
    listener.join()
#停止监视
Listener.stop()

 

posted @ 2019-01-25 20:42  Sun先生  Views(6682)  Comments(0Edit  收藏  举报