0

Im trying to capture a set of words from the keyboard and run a coresponding command to each word.

Each thread looks for a different word. For some reason although both threads are running only one word is captured.

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()

this is the main file:

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()
  • My guess is that `pyhook` expects only 1 thread to connect, and you're messing it up with multiple threads. Why do you have multiple threads anyway? – Brian Malehorn Jan 22 '16 at 23:02
  • It's easier to look for a single different word in each thread then multiple words in a single thread. – jackLantern Jan 23 '16 at 08:42
  • Clearly it's not that easy, since you're running into this bug. Could you try to do it all in one thread? My guess is your problem will disappear when you go to 1 thread. – Brian Malehorn Jan 25 '16 at 19:14

0 Answers0