如果用户按下ctrl+shift+c,我试图停止代码的运行。我使用下面的代码。不幸的是,sys.exit()只停止了"wait_for_ctrl_shift_c“函数,而没有停止"main_func”函数。我应该用什么来阻止它们呢?谢谢。
def wait_for_ctrl_shift_c():
print ('wait_for_ctrl_shift_c is working')
keyboard.wait('ctrl+shift+c')
print('wait_for_ctrl_shift_c was pressed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
sys.exit()
def main_func():
a=0
while True:
print ('Working2 ',a)
a=a+1
sleep(1)
if __name__ == '__main__':
Thread(target = wait_for_ctrl_shift_c).start()
Thread(target = main_func).start()
发布于 2019-12-27 04:05:12
有多种方法可以做到这一点。首先,你有3个线程,一个是主线程,另一个是你创建的2个(无限循环和键盘)。
您可以注册信号并处理它,也可以调用interrupt_main来中断主线程(而不是while循环线程)。中断将转到主异常处理程序。另外,我没有使用True,而是更改了第二个线程,使其具有一个属性来检查是否应该为干净的退出而运行。
import os
import threading
import time
import sys
import _thread
def wait_for_ctrl_shift_c():
print ('wait_for_ctrl_shift_c is working')
keyboard.wait('ctrl+shift+c')
print ('exiting thread')
_thread.interrupt_main()
sys.exit()
def main_func():
a=0
t = threading.currentThread()
while getattr(t, "run", True):
print ('Working2 ',a)
a=a+1
time.sleep(1)
print ('exiting main_func')
if __name__ == '__main__':
try:
t1 = threading.Thread(target = wait_for_ctrl_shift_c)
t2 = threading.Thread(target = main_func)
t1.start()
t2.start()
t1.join()
t2.join()
except:
print ('main exiting')
t2.run = False
sys.exit()
发布于 2019-12-26 23:16:41
在另一个窗口中打开shell,输入ps
列出正在运行的进程,然后杀死Python one (如果3145
是它的PID
,则通过kill 3145
)停止这两个进程。这样,我们就可以杀死运行这些线程的进程。
https://stackoverflow.com/questions/59490088
复制相似问题