这个库允许你控制和监听你的输入设备
它包含了一下几个子库来控制每个输入设备:
使用 pynput.keyboard
类控制和监听
使用pynput.keyboard.Controller
类
from pynput.keyboard import Key, Controller
keyboard = Controller()
# 按下和松开按键
keyboard.press(Key.space)
keyboard.release(Key.space)
# 按下a键,即使键盘没有a也能工作
keyboard.press('a')
keyboard.release('a')
# 两种输出A的方式
keyboard.press('A')
keyboard.release('A')
with keyboard.pressed(Key.shift):
keyboard.press('a')
keyboard.release('a')
# 使用type方法,输入helloworld
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
# Collect events until released
with keyboard.Listener(
on_press=on_press,
on_release=on_release) as listener:
listener.join()
# ...or, in a non-blocking fashion:
listener = mouse.Listener(
on_press=on_press,
on_release=on_release)
listener.start()
一个键盘listener 是一个 threading.Thread
类,所有回调回在线程中调用
从任何地方调用thread.Thread.stop
,引发StopException
或者从回调中返回 False
都会停止listener
的调用。
传递给回调函数的key
参数,是一个pynput.keyboard.Key
类,对于特殊按键,使用pynput.keybopard.KeyCode
来代表普通的字母数字键,或未知键的无键码
侦听器回调直接从某些平台上的操作线程调用,尤其是Windows。
这意味着不应该从回调调用长时间运行的过程和阻塞操作,因为这可能冻结所有进程的输入。
一个可能的解决方案是将传入的消息分派到一个队列,并让一个单独的线程处理它们。
代码用意: 当输入ctrl+c的时候停止程序
import pynput
from pynput.keyboard import Listener,Key,KeyCode,Controller
keyboard=Controller() # type:Controller
run_flag=True
def onpress(key):
global run_flag
key_char = key.char if isinstance(key, KeyCode) else str(key)
try:
if key_char == 'c' and keyboard.pressed(Key.ctrl):
run_flag=False
print('alphanumeric key {0} pressed'.format(
key_char))
except AttributeError:
print('special key {0} pressed'.format(
key))
def onrelease(key):
global run_flag
# print('{0} released'.format(
# key))
# print('thread----------=',threading.activeCount(),threading.current_thread().name)
if not run_flag: # key == keyboard.Key.esc:
# Stop listener
return False
def run():
with Listener(on_press=onpress,on_release=onrelease) as listener:
listener.join()
from threading import Thread
a=Thread(target=run)
a.start()
while a.is_alive():
pass