Python Forum
Python - Keyboard module - Threading problem
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python - Keyboard module - Threading problem
#1
Hi everyone,
I am working on an app and trying to create a corrector and I am using keyboard module for the correction.
I have created two classes, one keyboard monitor, which reads pressed events and displays them to screen, and one which suppresses them.
What I want to achieve is while the app corrects user input, every text that is typed by the user is suppressed and saved in a variable, for later use.
I am struggling on the synchronization of all this.

import keyboard
import threading
import time

lock_for_listening_to_keyboard = threading.Lock()
global running_suppressed_monitor 
running_suppressed_monitor = False

#########################################################
def delete_and_write(times_to_delete, word_to_write):
    global running_suppress_monitor
    print("---Deleting & Rewrite Started---")
    time.sleep(2)
    running_suppressed_monitor = False
    print("---Deleting & Rewrite Ended---")
    # for i in range(times_to_delete+1):
    #     keyboard.press_and_release('backspace')

    # for i,char in enumerate(word_to_write):
    #     keyboard.write(char.upper())

    # keyboard.write(' ')   


def write_the_suppressed_string(string):
    keyboard.write(string)
#########################################################

class keyboard_monitor(threading.Thread):
    def __init__(self,thread_name, threadID, word_typed,  keyboard_suppress, counter_for_key_pressed):
        threading.Thread.__init__(self)
        self.name = thread_name
        self.threaID = threadID
        self.fstring = word_typed
        self.counter_for_key_presses = counter_for_key_pressed
        self.suppressed = keyboard_suppress
        self.temp = ""

    def stop(self):
        self._is_running = False

    def run(self):

        if (self.suppressed is False):

            while(True):

                event = keyboard.read_event(suppress = self.suppressed)

                if (event.event_type == keyboard.KEY_DOWN):

                    if (event.name == "space"):

                        suppressed_monitor = keyboard_monitor("suppressed_monitor", 2, self.fstring, True, self.counter_for_key_presses)
                        suppressed_monitor.start()
                        suppressed_monitor.join()

                        print("RETURNED TO MAIN MONITOR")
                        self.counter_for_key_presses = 0
                        self.fstring = ""
                    elif (event.name in "abcdefghijklmnopqrstuvwxyz"):
                        self.fstring = ''.join([self.fstring, event.name])
                        self.counter_for_key_presses += 1

        elif (self.suppressed is True):

            self.temp = self.fstring
            self.fstring = ""
            thread_delete_and_rewrite = threading.Thread(
                target = delete_and_write, args=(self.counter_for_key_presses, self.temp))
            thread_delete_and_rewrite.start()

            running_suppressed_monitor = True
            # while(thread_delete_and_rewrite.is_alive()):
            while(running_suppressed_monitor):

                event = keyboard.read_event(suppress=self.suppressed)

                if (event.event_type == keyboard.KEY_DOWN):
                    print("KEYS PRESSED WHILE SUPPRESSED = {}".format(event.name))
                    if (event.name == "space"):
                        self.temp = self.fstring
                        self.fstring = ""
                        thread_delete_and_rewrite = threading.Thread(
                                target = delete_and_write, args=(self.counter_for_key_presses, self.temp))
                        thread_delete_and_rewrite.start()
                        # thread_delete_and_rewrite.join()
                        self.counter_for_key_presses = 0
                        self.fstring = ""
                    elif (event.name in "abcdefghijklmnopqrstuvwxyz"):
                        self.fstring = ''.join([self.fstring, event.name])
                        self.counter_for_key_presses += 1
                    # NO thread_delete_and_rewrite.join()
                # NO thread_delete_and_rewrite.join()

                if (thread_delete_and_rewrite.is_alive() is False):
                    break


            thread_delete_and_rewrite.join()
            print("SELF.FSTRING = {}".format(self.fstring))

            print("BEFORE END OF SUPPRESSED MONITOR")

            if (self.fstring != ""):
                thread_write = threading.Thread(
                                target = write_the_suppressed_string, args=(self.fstring, ))
                thread_write.start()
                thread_write.join()
            print("SUPPRESSED ENDED")
            self._is_running = False


if __name__ == "__main__":
    kb_not_suppressed = keyboard_monitor("not_suppressed_monitor", 1, "", False, 0)
    kb_not_suppressed.start()
    kb_not_suppressed.join()
I have one little problem that when the second while loop ends it requires a key press to exit.
What have I missed here?
Thanks in advance.
Reply
#2
I am missing why you have two threads? Where is there any kind of parallelism in this task? What am I missing? The way I look at this problem is the correction code is a filter between keyboard input and what appears. I can see having this as a thread so you could do something else that is not keyboard related, but why would you want to separate the keyboard reader from the display update (thread-wise I mean)?
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  problem with memory_graph module akbarza 3 296 Mar-04-2024, 10:15 AM
Last Post: snippsat
  problem using coloeama module akbarza 3 513 Jan-08-2024, 07:31 AM
Last Post: akbarza
  problem in using subprocess module akbarza 5 944 Sep-24-2023, 02:02 PM
Last Post: snippsat
  problem in import module from other folder akbarza 5 1,259 Sep-01-2023, 07:48 AM
Last Post: Gribouillis
  problem in using pyqrcode module to create QRcode akbarza 9 1,791 Aug-23-2023, 04:17 PM
Last Post: snippsat
  Problem with Pyinstaller. No module named '_tkinter' tonynapoli2309 0 932 May-15-2023, 02:38 PM
Last Post: tonynapoli2309
  Concurrent futures threading running at same speed as non-threading billykid999 13 1,716 May-03-2023, 08:22 AM
Last Post: billykid999
  Problem with module time and leap seconds Pedroski55 3 1,189 Oct-07-2022, 11:27 PM
Last Post: Pedroski55
  Tutorials on sockets, threading and multi-threading? muzikman 2 2,076 Oct-01-2021, 08:32 PM
Last Post: muzikman
  Can I open\use threading in Python? korenron 2 1,762 Jun-30-2021, 10:42 AM
Last Post: korenron

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020