python 控制和监控键盘输入 pynput模块

控制键盘输入

用 pynput.keyboard.Controller 来实现

from pynput.keyboard import Key, Controller

keyboard = Controller()

# 按下和释放空格键
keyboard.press(Key.space)
keyboard.release(Key.space)

# 键入小写字母“a”
keyboard.press('a')
keyboard.release('a')

# 键入两个大写字母,两种方式
keyboard.press('A')
keyboard.release('A')
with keyboard.pressed(Key.shift):
    keyboard.press('a')
    keyboard.release('a')

# 用快捷方法 type 键入“hello world”
keyboard.type('Hello World')

监听键盘输入

用 pynput.keyboard.Listener 来实现

from pynput import keyboard

# 按键按下事件
def on_press(key):
    try:
        print('alphanumeric key {0} pressed'.format(
            key.char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))

# 按键释放事件
def on_release(key):
    print('{0} released'.format(
        key))
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# 监听所有事件,直到释放
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

# 以非阻塞方式运行
listener = keyboard.Listener(
    on_press=on_press,
    on_release=on_release)
listener.start()

键盘监听器是threading.Thread,并且所有回调都将从线程中调用。
pynput.keyboard.Listener.stop从任何地方调用,引发StopException 或False从回调返回以停止线程
None:代表未知键
pynput.keyboard.Key: 特殊键
pynput.keyboard.KeyCode: 普通字母数字键
按键监听还可以用来监听热键:
用 pynput.keyboard.HotKey 来实现

from pynput import keyboard

def on_activate():
    print('Global hotkey activated!')

def for_canonical(f):
    return lambda k: f(l.canonical(k))

hotkey = keyboard.HotKey(
    keyboard.HotKey.parse('++h'),
    on_activate)
with keyboard.Listener(
        on_press=for_canonical(hotkey.press),
        on_release=for_canonical(hotkey.release)) as l:
    l.join()

这将创建一个热键,然后使用监听器线程更新其状态。一旦同时按下所有指定的键,on_activate将被调用

你可能感兴趣的:(python,python)