在python中暂停线程
如果按下某个键,我想暂停并继续线程。 我试过:如果按q键,它将删除(改为0)时间。睡眠(99999),但它不起作用。有人能帮我吗在python中暂停线程,python,python-3.x,multithreading,keyboard,python-multithreading,Python,Python 3.x,Multithreading,Keyboard,Python Multithreading,如果按下某个键,我想暂停并继续线程。 我试过:如果按q键,它将删除(改为0)时间。睡眠(99999),但它不起作用。有人能帮我吗 import keyboard from threading import Thread from time import sleep Thread1 = True Thread2 = True class main(): def test1(): if keyboard.is_pressed("q"): #i
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()
您可以为此创建一个类
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()
当用户点击q
时,我们将调用stop()
函数
def test1():
if keyboard.is_pressed("q"):
Thread1.stop()
顺便说一句,您的
main()
是冗余的。你的意思是defmain():
?这回答了你的问题吗?非常好,谢谢