python pynput鼠标键盘监控(详细)第2部键盘监控tcy

Posted Jason_WangYing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python pynput鼠标键盘监控(详细)第2部键盘监控tcy相关的知识,希望对你有一定的参考价值。


1.类键盘监听实现
 
"""1.作者:tcy 写于上海叶榭。2018/8/30
   2.用途:实时监听键盘,可用来启停程序,键盘中断。
           如输入stop停止事件,输入start开始运行。
   3.平台:window7 python3.7 PyCharm模拟。
   4.技术说明:用程序和类分别包装。建议用类
               监听部分有暂停键盘监听,恢复监听,销毁监听;
               暂停后可以恢复,但销毁后不能再恢复"""
 
from pynput import keyboard
from collections import deque
import threading,time
 
#处理字符串类
class KeyboardStr():
    '''1.接收键盘监听取得的字符串,处理带有shift切换的键,如输入!,大写字符;
       2.要取得可打印的字符串,默认数量最多10个,用t.a.get_print_chars获取;
       3.t.a.get_print_chars获取最多100个任意字符和非打印字符(以代码命名)'''
 
    def __init__(self):
        # super(KeyboardStr, self).__init__()
        # 获取字符串变量
        self.shift_press_flag=False
        self.get_print_chars = deque()  # 获取键盘字符串以回车结束
        self.get_all_chars = deque()    # 获取键盘所有字符串,含非打印字符以回车结束
        self.__get_print_chars = deque()
        self.__get_all_chars = deque()
 
        self.__shift_up_chars = {
            '0': ')', '1': '!', '2': '@', '3': '#', '4': '$', '5': '%', '6': '^', '7': '&',
            '8': '*', '9': '(', '10': '_', '11': '+', '12': '~', '13': '{', '14': '}',
            '15': ':', '16': '"', '17': '|', '18': '<', '19': '>', '20': '?'}
        self.__shift_down_key_chars = {
            "0": "0", "1": "1", "2": "2", "3": "3", "4": "4", "5": "5", "6": "6", "7": "7",
            "8": "8", "9": "9", "10": "-", "11": "=", "12": "`", "13": "[", "14": "]",
            "15": ";", "16": "'", "17": "'\\'", "18": ",", "19": ".", "20": "/"}
 
    # 处理键盘上下键 大小写问题
    def __get_combination_key_char(self,key_char:str):
        new_char=''
        is_up_down_key_char = key_char in self.__shift_down_key_chars.values()
        if key_char.__len__()==1:
            if key_char.isalpha() and self.shift_press_flag:
                new_char=key_char.upper()
            elif is_up_down_key_char and self.shift_press_flag:
                index_name = [k for k, v in self.__shift_down_key_chars.items() if v == key_char]
                new_char=self.__shift_up_chars[index_name[0]]
            else:
                new_char=key_char
            return  new_char
        else:
            return None
 
    '''获取回车确认前10个可打印键盘字符;回车后显示;'''
 
    def GetPrintChars(self, key_char:str,GetstrNumber=10):
        if  key_char.__len__()==1:
            new_char = self.__get_combination_key_char(key_char)
            self.__get_print_chars.append(new_char)
 
            while self.__get_print_chars.__len__() > GetstrNumber:
                self.__get_print_chars.popleft()
 
        if key_char=='Key.enter':
            self.get_print_chars = self.__get_print_chars.copy()
            self.__get_print_chars.clear()
            print('GetPrintCharStr===>%s\\n' % self.get_print_chars)
 
    '''获取回车确认前100个所有字符,含非打印字符'''
 
    def GetAllChars(self, key_char, GetstrNumber=100):
        self.__get_all_chars.append(key_char)
        while self.__get_all_chars.__len__() > GetstrNumber:
            self.__get_all_chars.popleft()
        if key_char == 'Key.enter':
            self.get_all_chars = self.__get_all_chars.copy()
            self.__get_all_chars.clear()
            print('GetAllCharStr===>%s\\n' % self.get_all_chars)
#********************************************************************************
class KeyboardClass(threading.Thread,KeyboardStr):
    '''1.用途:实时监听键盘事件,能暂停,恢复,销毁。
       2.测试:测试部分有2个,一个测试键盘监听,一个测试字符串处理。'''
    def __init__(self):
        super(KeyboardClass, self).__init__()
        KeyboardStr.__init__(self)
 
        #键盘监听变量
        self.run_flag = True
        self.pause_flag = True
        self.listener = keyboard.Listener()
 
        self.a=KeyboardStr()
 
    def __GetOneChar(self, key):
        return key.char if isinstance(key, keyboard.KeyCode) else str(key)
    
    def on_press(self,key):
        key_char = self.__GetOneChar(key)
        try:
            if key_char=='Key.shift':
                self.a.shift_press_flag=True
                # print('alphanumeric key {0} pressed'.format(key_char))
        except AttributeError:
            key_char=None
            print('special key {0} pressed'.format(key_char))
        finally:
            print('Alphanumeric key = 【{0}】 pressed...'.format(key_char))
 
 
    def on_release(self,key):
        key_char = self.__GetOneChar(key)
        if key_char == 'Key.shift':
            self.a.shift_press_flag = False
 
        self.a.GetPrintChars(key_char)
        self.a.GetAllChars(key_char)
        # print('{0} released'.format(key))
        if not self.run_flag:#key == keyboard.Key.esc:
            return False# Stop listener
 
    def keyboard_pause(self):
        self.listener.stop()
        self.pause_flag=False
 
    def keyboard_resume(self):
        self.pause_flag=True
 
    def keyboard_destroy(self):
        self.pause_flag=True
        self.run_flag=False
        self.listener.stop()
 
    def run(self):
        while self.run_flag:
            with keyboard.Listener(on_press=self.on_press,
                                    on_release=self.on_release) as self.listener:
                if self.pause_flag:
                    self.listener.join()
 
#键盘字符处理测试程序
def test_str():
    t=KeyboardClass()
    t.start()
 
    print('1.start run...................................')
    while 1:
        print('2.可打印字符串===》',t.a.get_print_chars)
        print('3.所有字符串===》',t.a.get_all_chars)
        time.sleep(2)
 
#键盘监听测试程序
def test_keyboard_listen():
    t = KeyboardClass()
    t.start()
 
    print('1.1.start run...................................',time.ctime())
    time.sleep(5)
    print('1.2.start run stop..............................', time.ctime())
 
    print('2.1.start pause..................................', time.ctime())
    t.keyboard_pause()
    time.sleep(5)
    print('2.2.end pause.....................................%s\\n'% (time.ctime()))
    print('3.1.keyboard listener resume......................%s\\n'% (time.ctime()))
    t.keyboard_resume()
    time.sleep(5)
    print('3.2.stop resume.stoping.............................%s\\n'% (time.ctime()))
    print('4.1.start destroy...................................%s\\n'% (time.ctime()))
    t.keyboard_destroy()
    time.sleep(1)
    print('4.2.end destroy......................................%s\\n'%( time.ctime()))
    time.sleep(1)
    print('5.all program end.exit....')
 
# test_str()
test_keyboard_listen()
#-------------------------------------------------------------------------------------------------------
#第一步分测试显示如下:随机显示内容,视你的按下什么键
# 1.start run...................................
# 2.可打印字符串===》 deque([])
# 3.所有字符串===》 deque([])
'''没有按键盘字符'''
# Alphanumeric key = 【a】 pressed...
# Alphanumeric key = 【s】 pressed...
# Alphanumeric key = 【Key.shift】 pressed...
# as2.可打印字符串===》 deque([])
# 3.所有字符串===》 deque([])
'''按下回车后显示结果'''
# Alphanumeric key = 【Key.enter】 pressed...
# GetPrintCharStr===>deque(['a', 's'])
# GetAllCharStr===>deque(['a', 's', 'Key.shift', 'Key.enter'])
# dAlphanumeric key = 【d】 pressed...
# 2.可打印字符串===》 deque(['a', 's'])
# 3.所有字符串===》 deque(['a', 's', 'Key.shift', 'Key.enter'])
# Alphanumeric key = 【Key.enter】 pressed...
#
# GetPrintCharStr===>deque(['d'])
#
# GetAllCharStr===>deque(['d', 'Key.enter'])
#
# 2.可打印字符串===》 deque(['d'])
# 3.所有字符串===》 deque(['d', 'Key.enter'])
# Alphanumeric key = 【Key.shift】 pressed...
# Alphanumeric key = 【1】 pressed...
# Alphanumeric key = 【2】 pressed...
# Alphanumeric key = 【3】 pressed...
# 2.可打印字符串===》 deque(['d'])
# 3.所有字符串===》 deque(['d', 'Key.enter'])
# $Alphanumeric key = 【4】 pressed...
# Alphanumeric key = 【5】 pressed...
# %
# Alphanumeric key = 【Key.enter】 pressed...
# GetPrintCharStr===>deque(['!', '@', '#', '$', '%'])
#
# GetAllCharStr===>deque(['1', '2', '3', '4', '5', 'Key.shift', 'Key.enter'])
 
# GetAllCharStr===>deque(['h', 'h', 'h', 'Key.space', 'Key.shift', 'Key.shift_r', 'Key.delete', 'Key.end', 'Key.page_down', 'Key.insert', 'Key.home', 'Key.page_up', 'Key.down', 'Key.right', 'Key.up', 'Key.left', 'Key.down', '2', '0', 'Key.enter'])
#
# 2.可打印字符串===》 deque(['h', 'h', 'h', '2', '0'])
# 3.所有字符串===》 deque(['h', 'h', 'h', 'Key.space', 'Key.shift', 'Key.shift_r', 'Key.delete', 'Key.end', 'Key.page_down', 'Key.insert', 'Key.home', 'Key.page_up', 'Key.down', 'Key.right', 'Key.up', 'Key.left', 'Key.down', '2', '0', 'Key.enter'])
#************************************************************************************************
#第二部分监听测试结果:
# C:\\python37\\python.exe C:/Users/Administrator/.PyCharmCE2018.2/config/scratches/tmp.py
# 1.1.start run................................... Thu Aug 30 00:45:29 2018
# dAlphanumeric key = 【d】 pressed...
#  Alphanumeric key = 【Key.space】 pressed...
# fAlphanumeric key = 【f】 pressed...
#
# Alphanumeric key = 【Key.enter】 pressed...
# GetPrintCharStr===>deque(['d', 'f'])
#
# GetAllCharStr===>deque(['d', 'Key.space', 'f', 'Key.enter'])
#
# dAlphanumeric key = 【d】 pressed...
# gAlphanumeric key = 【g】 pressed...
# 1.2.start run stop.............................. Thu Aug 30 00:45:34 2018
# 2.1.start pause.................................. Thu Aug 30 00:45:34 2018
#
# fffffff2.2.end pause.....................................Thu Aug 30 00:45:39 2018
#
# 3.1.keyboard listener resume......................Thu Aug 30 00:45:39 2018
#
# Alphanumeric key = 【s】 pressed...
# sfAlphanumeric key = 【f】 pressed...
# Alphanumeric key = 【Key.enter】 pressed...
# GetPrintCharStr===>deque(['d', 'g', 's', 'f'])
#
# GetAllCharStr===>deque(['d', 'g', 's', 'f', 'Key.enter'])
#
# Alphanumeric key = 【Key.space】 pressed...
# Alphanumeric key = 【f】 pressed...
# Alphanumeric key = 【Key.enter】 pressed...
# GetPrintCharStr===>deque(['f'])
#
# GetAllCharStr===>deque(['Key.space', 'f', 'Key.enter'])
#
# 3.2.stop resume.stoping.............................Thu Aug 30 00:45:44 2018
#
# 4.1.start destroy...................................Thu Aug 30 00:45:44 2018
#
# 4.2.end destroy......................................Thu Aug 30 00:45:45 2018

# 5.all program end.exit....
#
# Process finished with exit code 0
 

-------------------------------------------------------------------------------------------------------------------

2.函数监听
from pynput import keyboard
import threading,time
listener=keyboard.Listener()
 
run_flag=True
pause_flag=True
def on_press(key):
    key_char = key.char if isinstance(key, keyboard.KeyCode) else str(key)
    try:
        print('alphanumeric key {0} pressed'.format(
            key_char))
    except AttributeError:
        print('special key {0} pressed'.format(
            key))
 
def on_release(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 keyboard_pause(listen=listener):
    global pause_flag
    listen.stop()
    pause_flag=False
def keyboard_resume(listen=listener):
    global pause_flag
    pause_flag=True
    # listen.run()
def keyboard_stop(listen=listener):
    global run_flag,pause_flag
    pause_flag=True
    run_flag=False
def run():
    global listener,run_flag,pause_flag
    while run_flag:
        with keyboard.Listener(
                on_press=on_press,
                on_release=on_release) as listener:
            if pause_flag:
                listener.join()
    #     print('end22222222222222222222')
 
t = threading.Thread(target=run)
t.start()
 
 
print('1.start run.....---------------------11--------------------')
time.sleep(5)
print('1.end run.....---------------------12--------------------')
print('2.start pause.....-------------------21--------------------')
keyboard_pause(listen=listener)
time.sleep(5)
print('2.end pause.....-------------------22--------------------')
print('3.start run.....---------------------31-------------------')
keyboard_resume()
time.sleep(5)
print('3.end run.....---------------------32-------------------')
print('4.start stop.....----------------------41-----------------------------')
keyboard_stop()
time.sleep(1)
print('4.end stop.....----------------------------42---------------------------')
time.sleep(1)
print('5.all end.....----------------------------5---------------------------')
 
# C:\\python37\\python.exe C:/Users/Administrator/.PyCharmCE2018.2/config/scratches/keboardok1.py
# 1.start run.....---------------------11--------------------
 
# falphanumeric key f pressed
#  alphanumeric key Key.space pressed
# falphanumeric key f pressed
# 1.end run.....---------------------12--------------------
# 2.start pause.....-------------------21--------------------
# hhddddgghhjhjj2.end pause.....-------------------22--------------------
# 3.start run.....---------------------31-------------------
# talphanumeric key t pressed
# talphanumeric key t pressed
# talphanumeric key t pressed
#  alphanumeric key Key.space pressed
# alphanumeric key f pressed
# ffalphanumeric key f pressed
# 3.end run.....---------------------32-------------------
# 4.start stop.....----------------------41-----------------------------
#  alphanumeric key Key.space pressed
# f4.end stop.....----------------------------42---------------------------
# ff5.all end.....----------------------------5---------------------------

# Process finished with exit code 0
————————————————
版权声明:本文为CSDN博主「tcy23456」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/tcy23456/article/details/82322851

以上是关于python pynput鼠标键盘监控(详细)第2部键盘监控tcy的主要内容,如果未能解决你的问题,请参考以下文章

python使用笔记:pynput库控制键盘鼠标

做了个python3 pynput 监控鼠标键盘操作并回放的模块

如何通过pynput与日志记录实现键盘鼠标的监听行为?

Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘

你的聊天记录是怎么被公司监控的?

使用 pynput 键盘检测小键盘键