-1

I want to pause and continue threads if a certain key is pressed. I tried: if q is pressed it will remove(change to 0) the "time.sleep(99999)" but it didnt work can anyone help me?

import keyboard
from threading import Thread
from time import sleep

Thread1 = True
Thread2 = True

class main():
    def test1():
        if keyboard.is_pressed("q"):      #if keyboard is pressed q it will reomve the sleep
            time = 0
        time = 99999

        while Thread1 == True:
            print("Thread1")
            sleep(time)
    def test2():
        while Thread2 == True:
            print("Thread2")
            sleep(1)
        
    Thread(target=test1).start()
    Thread(target=test2).start()
    
main()

Vuki
  • 21
  • 6
  • 1
    btw your `main()` is redundant. Did you mean `def main():`? – quamrana Feb 26 '21 at 17:26
  • Does this answer your question? [Pausing a thread using threading class](https://stackoverflow.com/questions/3262346/pausing-a-thread-using-threading-class) – quamrana Feb 26 '21 at 17:29

1 Answers1

0

You can create a class for this

class customThread(threading.Thread):
    def __init__(self, *args, **kwargs):
        super(customThread, self).__init__(*args, **kwargs)
        self.__stop_event = threading.Event()
        
    def stop(self):
        self.__stop_event.set()
    def stoppped(self):
        self.__stop_event.is_set()

And we will call the stop() function when user hits q.

def test1():
    if keyboard.is_pressed("q"):  
        Thread1.stop()  
Sekomer
  • 688
  • 1
  • 6
  • 24