python pynput监听键盘

import subprocess
from configparser import ConfigParser, NoOptionError, NoSectionError
from datetime import datetime
from os import getcwd, path, mkdir

from pynput.keyboard import Listener

config_path = path.join(getcwd(), 'config')
config_file = path.join(config_path, 'config.ini')
readme_file = 'readme.txt'


def warp_before_exec(func):
    def inner(*args, **kwargs):
        print('----========############################========----')
        print(f'\n{datetime.now().strftime("%Y-%m-%d %H:%M:%S")} 正在执行 \n')
        result = func(*args, **kwargs)
        print(f'\n{datetime.now().strftime("%Y-%m-%d %H:%M:%S")} 执行完毕 \n')
        return result
    return inner


class KeyboardListener:
    """通过读取键盘上的按键去匹配配置文件中的快捷键,从而执行快捷键下的指令
    """
    def __init__(self):
        self.key_list = []
        self.hotkey = []
        self._parser_config()


    def _parser_config(self):
        # 读取配置文件
        conf = ConfigParser()
        conf.read(config_file, encoding='utf-8')
        try:
            self.exec_path = conf.get('listener', 'exec_path')
        except NoSectionError:
            print('配置文件不存在,正在创建...')
            conf.add_section('listener')
            conf.set('listener', 'exec_path', 'C:\\python')
            conf.set('listener', 'alt_q', '& notepad.exe')
            conf.set('listener', 'alt_w', 'test.py')
            if not path.exists(config_path):
                mkdir(config_path)
            with open(config_file, 'w', encoding='utf-8') as f:
                conf.write(f)
                print('创建完成.')
        finally:
            print('准备就绪.')


    @staticmethod
    def _get_commend(hotkey):
        # 读取配置文件获取操作指令
        conf = ConfigParser()
        conf.read(config_file, encoding='utf-8')
        return conf.get('listener', hotkey)


    def _release_all(self, key):
        # 释放所有被按下的按键,防止按键粘黏
        self.on_release(key)


    def _process_hotkey(self, key) -> str:
        # 加工
        self.key_list.append(str(key).replace("'", "").replace("Key.", "").replace("_r", "").replace("_l", ""))
        keys = list(set(self.key_list))
        list_default_keys = ['ctrl', 'shift', 'alt']
        for i in list_default_keys:
            for j in keys:
                if i == j:
                    self.hotkey.append(j)
                    keys.remove(j)
        try:
            self.hotkey.append(keys[0])
        except IndexError:
            None
        hotkey = '_'.join(self.hotkey)

        return hotkey


    @warp_before_exec
    def exec_hotkey(self, cmd, key):
        """执行快捷指令
        :param cmd: 命令,字符型
        :param key: 按键
        """
        commend = cmd.split(' ', 1)
        if commend[0] == '&':
            subprocess.Popen(commend[1], shell=True, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
        else:
            subprocess.call(path.join(self.exec_path, cmd), shell=True)

        self._release_all(key)


    def on_press(self, key):
        # 加工输入的快捷键,使其成为可以识别的字符串
        hotkey = self._process_hotkey(key)

        # 预设快捷键
        if hotkey == 'alt_h':
            with open(readme_file, 'r', encoding='utf-8') as f:
                for line in f.readlines():
                    print(line, end='')
        elif hotkey == 'shift_alt_r':
            print('重新加载配置文件...')
            self._parser_config()
            print('加载完成.')
        elif hotkey == 'alt_z':
            print('退出.')
            exit()

        if len(self.hotkey) > 1:
            try:
                cmd = self._get_commend(hotkey)
                self.exec_hotkey(cmd, key)
            except NoOptionError:
                print('No hotkey founded, please try another.')

        self.hotkey = []


    def on_release(self, key):
        self.key_list = []


    def listen(self):  # 键盘监听函数
        with Listener(on_press=self.on_press, on_release=self.on_release) as listener:
            listener.join()


if __name__ == "__main__":
    listener = KeyboardListener()
    listener.listen()

你可能感兴趣的:(python,开发语言,windows)