Python監(jiān)控鍵盤按什么鍵的方法-創(chuàng)新互聯(lián)

創(chuàng)新互聯(lián)www.cdcxhl.cn八線動(dòng)態(tài)BGP香港云服務(wù)器提供商,新人活動(dòng)買多久送多久,劃算不套路!

廣靈網(wǎng)站建設(shè)公司成都創(chuàng)新互聯(lián)公司,廣靈網(wǎng)站設(shè)計(jì)制作,有大型網(wǎng)站制作公司豐富經(jīng)驗(yàn)。已為廣靈上千家提供企業(yè)網(wǎng)站建設(shè)服務(wù)。企業(yè)網(wǎng)站搭建\外貿(mào)網(wǎng)站制作要多少錢,請(qǐng)找那個(gè)售后服務(wù)好的廣靈做網(wǎng)站的公司定做!

這篇文章將為大家詳細(xì)講解有關(guān)Python監(jiān)控鍵盤按什么鍵的方法,小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。

Python如何監(jiān)控鍵盤按了什么鍵

1、安裝pynput

pip install pynput # conda or py3

2、程序功能介紹

這個(gè)程序是為了實(shí)現(xiàn)監(jiān)聽(tīng)鍵盤操作,記錄鍵盤輸入的值,獲取

1 擊鍵行為特征:

第一個(gè)鍵釋放到第二個(gè)鍵按下的時(shí)間

第一個(gè)鍵按下到第二個(gè)鍵釋放的時(shí)間

按下一個(gè)鍵盤到釋放的時(shí)間

2 停頓特征:

停頓是兩次敲擊鍵盤是時(shí)間差超過(guò)規(guī)定的停頓閾限,根據(jù)已有的研究,這里將停頓閾限定為 2s。本文提取停頓次數(shù)、最長(zhǎng)停頓、停頓位置等特征。

示例代碼:

# -*- coding: utf-8 -*-ahello world
import sys, os
from pynput.keyboard import Controller, Key, Listener
from pynput import keyboard
import time
# from tkinter import *

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'}
#比較按鍵生成的兩個(gè)txt文件,這里主要是為了實(shí)現(xiàn)當(dāng)退格鍵按下后,
#對(duì)比退格前后文本的差異,這里可以自己延伸
def com_str(path, file1, file2):
    path2 = os.path.join(path, file1)
    path3 = os.path.join(path, file2)
    with open(path2, 'r', encoding='utf-8') as f:
        file1 = f.readlines()
    content1 = [str.strip().split() for str in file1]
    with open(path3, 'r', encoding='utf-8') as f:
        file2 = f.readlines()
    content2 = [str.strip().split() for str in file2]
    #print("content1:", content1)
    #print("content2:", content2)
    str1 = []
    str2 = []
    for sub_list in content1:
        str1.extend(sub_list)
    for sub_list in content2:
        str2.extend(sub_list)
   # print("the str1:", str1, "the length:", len(str1))
    #print("the str2:", str2, "the length:", len(str2))
    origanl_len = len(str1)
    print("extend", origanl_len)
    if len(str1) > len(str2):
        str2.extend([' '] * (len(str1) - len(str2)))
    elif len(str1) < len(str2):
        str1.extend([' '] * (len(str2) - len(str1)))
    index = 0
    indexs = []
    count = 0
    for i, j in zip(str1, str2):
        if i != j:
            indexs.append(index)
            count += 1
            if index < origanl_len - 1:
                print("the before...")
            else:
                print("the after...")
        index += 1
    if count == 1:
        print("single...")
    elif count>1:
        print("the sentence...")
#得到鍵入的值
def get_key_name(key):
    if isinstance(key, keyboard.KeyCode):
        with open(r'C:\Users\admin\Desktop\key_record.txt','a',encoding='utf-8') as f:
            f.write(key.char)
        with open(r'C:\Users\admin\Desktop\key_record1.txt','a',encoding='utf-8') as f:
            f.write(key.char)
        return key.char
    else:
        if str(key) in ['Key.enter','Key.space','Key.tab']:
            with open(r'C:\Users\admin\Desktop\key_record.txt', 'a',encoding='utf-8') as f:
                f.write(keyBoard_dict[str(key)])
            with open(r'C:\Users\admin\Desktop\key_record1.txt', 'a',encoding='utf-8') as f:
                f.write(keyBoard_dict[str(key)])
        if str(key) in ['Key.backspace']:
            com_str(r'C:\Users\admin\Desktop','key_record.txt','key_record1.txt')
        return str(key)
# 監(jiān)聽(tīng)按壓
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)
            #停頓次數(shù)
            dict['interval_times'] += 1
            #最長(zhǎng)停頓
            dict['max_interval'] = time_interval if time_interval > dict['max_interval'] else dict['max_interval']
    index += 1

    print("正在按壓:", get_key_name(key))

# 監(jiān)聽(tīng)釋放
def on_release(key):
    global start,fun_start, time_interval, index,count,count_dict
    count+=1
    if count==2:
        #第一個(gè)鍵按下到第二個(gè)鍵釋放的時(shí)間
        count_dict['first_p_to_second_r']=time.time()-count_dict['first_time']
        count=0
    #按下一個(gè)鍵盤到釋放的時(shí)間
    print("the interval between first press and release:",
          time.time() - start-time_interval)
    start = time.time()
    index = 1
    print("已經(jīng)釋放:", get_key_name(key))
    if key == Key.esc:
        # 停止監(jiān)聽(tīng)
        return False

# 開(kāi)始監(jiān)聽(tīng)
def start_listen():
    with Listener(on_press=on_press, on_release=on_release) as listener:
        listener.join()

if __name__ == '__main__':
    # 開(kāi)始監(jiān)聽(tīng),按esc退出監(jiān)聽(tīng)
    start_listen()
    print(dict)

關(guān)于Python監(jiān)控鍵盤按什么鍵的方法就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

當(dāng)前文章:Python監(jiān)控鍵盤按什么鍵的方法-創(chuàng)新互聯(lián)
當(dāng)前鏈接:http://muchs.cn/article28/dsehcp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)建站搜索引擎優(yōu)化、Google、定制網(wǎng)站、網(wǎng)站制作、網(wǎng)站維護(hù)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司