繁体   English   中英

如何在python中终止gech()?

[英]How to abort gech () in python?

我有3个活动线程。 其中之一激活另一个线程,并使用getch()检测ESC键(如果按下该键则关闭程序)。

当其他两个线程完成其操作(不按ESC)时,它们成功关闭,但是第一个线程仍在等待按下ESC。 因此该程序仍在运行。

class tracking():
def __init__(self):    
    self.tecla = '\x1b' #ESC
    self.case = None

def pressed(self, case):
    self.case = getch()

def inicio(self): #The Thread in question calls this function
    Thread(target=self.pressed(self.case)).start()      
    while True:
        if self.case is not None:
            if self.case == self.tecla:
                sys.exit()
            else:
                self.case = None
                self.pressed(self.case)

这是因为getch()是同步的。 有几种选择:

  • 您可以select等待I / O操作(包括键盘),请参见此处: https : //docs.python.org/2/library/select.html

  • 您可以使用一个库,该库允许您检测按键,然后循环并等待直到得到按键。 如果您使用诸如pygame之类的方法,可能会很麻烦。

  • 您可以使用thread.interrupt_main自己破坏线程,请参见此处: https ://docs.python.org/2/library/thread.html#thread.interrupt_main

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM