最新公告
  • 欢迎您光临起源地模板网,本站秉承服务宗旨 履行“站长”责任,销售只是起点 服务永无止境!立即加入钻石VIP
  • Python如何监控键盘按了什么键

    正文概述    2020-04-24   318

    Python如何监控键盘按了什么键

    Python如何监控键盘按了什么键

    1、安装pynput

    pip install pynput # conda or py3

    2、程序功能介绍

    这个程序是为了实现监听键盘操作,记录键盘输入的值,获取

    1 击键行为特征:

    第一个键释放到第二个键按下的时间

    第一个键按下到第二个键释放的时间

    按下一个键盘到释放的时间

    2 停顿特征:

    停顿是两次敲击键盘是时间差超过规定的停顿阈限,根据已有的研究,这里将停顿阈限定为 2s。本文提取停顿次数、最长停顿、停顿位置等特征。

    示例代码:

    # -*- 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'}
    #比较按键生成的两个txt文件,这里主要是为了实现当退格键按下后,
    #对比退格前后文本的差异,这里可以自己延伸
    def com_str(path, file1, file2):
        path1 = os.path.join(path, file1)
        path2 = os.path.join(path, file2)
        with open(path1, 'r', encoding='utf-8') as f:
            file1 = f.readlines()
        content1 = [str.strip().split() for str in file1]
        with open(path2, '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)
    # 监听按压
    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)
        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)

    更多技术请关注Python视频教程。


    起源地下载网 » Python如何监控键盘按了什么键

    常见问题FAQ

    免费下载或者VIP会员专享资源能否直接商用?
    本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。更多说明请参考 VIP介绍。
    提示下载完但解压或打开不了?
    最常见的情况是下载不完整: 可对比下载完压缩包的与网盘上的容量,若小于网盘提示的容量则是这个原因。这是浏览器下载的bug,建议用百度网盘软件或迅雷下载。若排除这种情况,可在对应资源底部留言,或 联络我们.。
    找不到素材资源介绍文章里的示例图片?
    对于PPT,KEY,Mockups,APP,网页模版等类型的素材,文章内用于介绍的图片通常并不包含在对应可供下载素材包内。这些相关商业图片需另外购买,且本站不负责(也没有办法)找到出处。 同样地一些字体文件也是这种情况,但部分素材会在素材包内有一份字体下载链接清单。
    模板不会安装或需要功能定制以及二次开发?
    请QQ联系我们

    发表评论

    还没有评论,快来抢沙发吧!

    如需帝国cms功能定制以及二次开发请联系我们

    联系作者

    请选择支付方式

    ×
    迅虎支付宝
    迅虎微信
    支付宝当面付
    余额支付
    ×
    微信扫码支付 0 元