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的详细用法 (转载)
Python控制键盘鼠标pynput的详细用法 更新时间:2019年01月28日 15:15:16 作者:botoo 这篇文章主要介绍了Python控制键盘鼠标pynput的详细用法,小编觉得挺不 ...
- python键盘上下左右控制_【322】python控制键盘鼠标:pynput
Python控制键盘鼠标:pynput 地址:pynput - PyPI 这个库让你可以控制和监控输入设备. 对于每一种输入设备,它包含一个子包来控制和监控该种输入设备: pynput.mouse:包 ...
- python记录鼠标键盘操作自动执行重复工作
系列文章目录 文章目录 系列文章目录 前言 github项目原地址 一.执行方法 二.python录制 1.Frame1.py 2.KeymouseGo.py 三.说明书 KeymouseGo v2. ...
- 使用 Python 实现鼠标键盘自动化
使用 Python 实现鼠标键盘自动化 本文演示了如何使用 Python 的 pyautogui 模块实现鼠标的自动移动以及键盘的自行输入. 该模块不是 Python 自带的, 因此执行以下命令进行安 ...
- python热键+鼠标键盘控制
python热键+鼠标键盘控制 应用:ctrl+home自动输入文本:home停止 代码:hotkey 应用:ctrl+home自动输入文本:home停止 代码:hotkey #!/usr/bin/e ...
- [转载] 使用 Python 实现鼠标键盘自动化
参考链接: 使用Python进行鼠标和键盘自动化 使用 Python 实现鼠标键盘自动化 本文演示了如何使用 Python 的 pyautogui 模块实现鼠标的自动移动以及键盘的自行输入. 该模块不 ...
- python 操作鼠标和键盘
python 操作鼠标和键盘 1.PyMouse 模块 2.PyAutoGUI 模块 1.PyMouse 模块 安装pymouse需要安装一些其他的包,否则运行时候会报错! 需要安装PyHook和Py ...
- (程序员必备技能)基于Python的鼠标与键盘控制实战扩展与源码
(程序员必备技能)基于Python的鼠标与键盘控制实战与源码 文章目录 (程序员必备技能)基于Python的鼠标与键盘控制实战与源码 一.序言 二.配置环境 1.下载pyautogui包 三.鼠标控制 ...
- Python控制鼠标和键盘-PyAutoGUI
PyAutoGUI是用Python写的一个模块,使用它可以控制鼠标和键盘. 利用它可以实现自动化任务,再也不用担心有重复枯燥的任务了. pyautogui模块的功能: 移动鼠标.点击左右键和滚轮 发送 ...
最新文章
- 发布AI操作系统、应用市场,开源机器学习数据库和AI操作系统内核,第四范式这波操作有点秀!
- runtime 分类结构体_水性木器涂料的5大分类+4大配方事项
- HW2017笔试编程题
- PHP回调函数的几种用法
- python 从url中提取域名和path
- LeetCode Reverse Linked List II
- Word2vec基础之霍夫曼树
- 成都Uber优步司机奖励政策(4月24日)
- ORACLE10g R2及PATH官方下载地址
- 如何用shell脚本读取配置文件
- Bailian2973 Skew数【进制】
- 程序员应该具备的12种能力
- ireport 生成一维码 和 二维码 小记
- 进销存系统测试实战-功能测试
- css设置动画匀速运动,CSS3 transition动画
- 小程序之100推荐:901~1000
- android 玻璃背景,Android 弹窗毛玻璃背景实践
- 博尔顿大学介绍让学生们在9月重返校园的创新措施
- Scaling SPADE to “Big Provenance”(论文阅读)
- python 聚类 客户细分_Python中用K-均值聚类来探索顾客细分
热门文章
- 2020年开启我的新人生:反思与展望
- 战地4不显示服务器,战地4设置服务器
- 【博物纳新】Isaura—光环特效开源库评测
- 开工大吉 | 兔年启新程,万事尽可期
- 英文长句单词字典排序
- linux桌面环境哪个好,你应该选择哪一个Linux桌面环境?
- 有关zeal离线包的下载
- Wallys// DR9074EDR9074-6E(PN02.7)DR9074-5G(PN02.1)QCN90X4 WIFI5G WIFI6E
- libjingle源码分析之三:P2P传输
- GIS坐标系转换(EPSG:4326与EPSG:3857相互转换)