0

我试图从键盘捕获一组单词并对每个单词运行一个对应的命令。

每个线程寻找一个不同的词。出于某种原因,虽然两个线程都在运行,但只捕获了一个单词。

import pythoncom, pyHook, os, threading

KEYUP_EVENT_NAME = 'key up'

class keyboard_hooker(object):
    """
    handles keyboard events and executes coresponding command.
    """"
    def __init__(self, target, command):
        self.target = target
        self.command = command
        self.index = 0

    def _target_function(self):
        """
        the target function to execute when key sequence was pressed.
        """
        os.system(self.command)
        return

    def _thread_opener(self):
        """
        opens a thread to run the target function.
        """
        new_thread = threading.Thread(target=self._target_function,args=())
        new_thread.start()
        return

    def _keyboard(self, event):
        """
        handles the keyboard event and searches for a specific word typed.
        """
        print self.target      
        if event.MessageName == KEYUP_EVENT_NAME:
            return True

        if self.index == len(self.target) - 1:
            self._thread_opener()
            self.index = 0
            return True

        if chr(event.Ascii) == self.target[self.index]:
            self.index += 1
            return True

        self.index = 0
        return True

    def hook_keyboard(self):
        """
        hooks the keyboard presses.
        blocking.
        """
        hm = pyHook.HookManager()
        hm.KeyAll = self._keyboard
        hm.HookKeyboard()
        pythoncom.PumpMessages()

这是主文件:

import shortcuts, threading, time

TARGETS = {'clcl': 'calc', 'fff': '"c:\Program Files\Google\Chrome\Application\chrome.exe" facebook.com'}


def keyboardHooker(key_word, target_command):
    """
    initiats a new keyboard hooker instance.
    """
    hooker = shortcuts.keyboard_hooker(key_word, target_command)
    hooker.hook_keyboard()


def main():
    for command in TARGETS:
        new_thread = threading.Thread(target=keyboardHooker,args=(command, TARGETS[command]))
        new_thread.start()
        print "this is the active count {}".format(threading.active_count())


if __name__ == '__main__':
    main()
4

0 回答 0