Python Notes36:监听键鼠

Python Notes36:监听键鼠

安装库

pip install pynput

Demo

''' Description: henggao_note version: v1.0.0 Date: 2022-07-03 21:24:39 LastEditors: henggao LastEditTime: 2022-07-03 22:17:31 ''' import os import time from pynput import keyboard savefilepath = r'D:\桌面\key_record.txt' press_time =0 release_time =0 def on_press(key): global press_time press_time = time.time() try: print('alphanumeric key {0} pressed'.format( key.char)) except AttributeError: print('special key {0} pressed'.format( key)) def on_release(key): global release_time release_time = time.time() print('{0} released'.format( key)) print(release_time-press_time) if key == keyboard.Key.esc: # Stop listener return False with open(savefilepath,"a") as f: f.write('{0}'.format( key)) f.write(str("%.2f" % (release_time-press_time))) f.write("\n") # 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 = keyboard.Listener( on_press=on_press, on_release=on_release) listener.start()

Demo2

''' Description: henggao_note version: v1.0.0 Date: 2022-07-03 21:54:05 LastEditors: henggao LastEditTime: 2022-07-04 09:16:53 ''' from pynput.keyboard import Key, Listener import time start=time.time() end=time.time() fun_start=0 time_interval=0 index=0 dict={'interval_times':0,'max_interval':0.,'interval_location':[]} count=0 count_dict={'first_time':0.,'first_p_to_second_r':0.} keyBoard_dict={'Key.enter':'\n', 'Key.space':' ', "Key.tab":'\t'} savefilepath = r'D:\桌面\key_record.txt' # 监听按压 def on_press(key): global fun_start,time_interval,index,dict,count,count_dict fun_start = time.time() if count == 0: count_dict['first_time'] = fun_start if index == 0 or index == 1: time_interval = fun_start - start if index == 1 and time_interval > 2.: #停顿位置 dict["interval_location"].append(key) #停顿次数 dict['interval_times'] += 1 #最长停顿 dict['max_interval'] = time_interval if time_interval > dict['max_interval'] else dict['max_interval'] index += 1 # print("正在按压:", get_key_name(key)) # 监听释放 def on_release(key): global start,fun_start, time_interval, index,count,count_dict count+=1 if count==2: #第一个键按下到第二个键释放的时间 count_dict['first_p_to_second_r']=time.time()-count_dict['first_time'] count=0 #按下一个键盘到释放的时间 print("the interval between first press and release:", time.time() - start-time_interval) with open(savefilepath,"a") as f: f.write('{0}'.format( key)) f.write(str("%.2f" % (time.time() - start-time_interval))) f.write("\n") start = time.time() index = 1 # print("已经释放:", get_key_name(key)) if key == Key.esc: # 停止监听 return False # 开始监听 def start_listen(): with Listener(on_press=on_press, on_release=on_release) as listener: listener.join() if __name__ == '__main__': # 开始监听,按esc退出监听 start_listen() print(dict)