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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 付出过就不要后悔,爱情里没有绝对地对与错
- 下一篇: html爱情表白神器,回忆纪念册(附源码