Python 我需要停止多线程代码的运行

Python 我需要停止多线程代码的运行,python,Python,如果用户按下ctrl+shift+c,我试图阻止代码运行。我使用下面的代码。不幸的是,sys.exit()只停止“wait\u for\u ctrl\u shift\u c”函数,而不停止“main\u func”。我应该用什么来阻止他们? 谢谢 在另一个窗口中打开shell,键入ps列出正在运行的进程,并杀死Python进程(通过kill 3145,如果3145是它的PID),停止它们。通过这种方式,我们可以终止运行这些线程的进程。有多种方法。首先,您有3个线程,一个主线程和另外2个(无限循环

如果用户按下ctrl+shift+c,我试图阻止代码运行。我使用下面的代码。不幸的是,sys.exit()只停止“wait\u for\u ctrl\u shift\u c”函数,而不停止“main\u func”。我应该用什么来阻止他们? 谢谢


在另一个窗口中打开shell,键入
ps
列出正在运行的进程,并杀死Python进程(通过
kill 3145
,如果
3145
是它的
PID
),停止它们。通过这种方式,我们可以终止运行这些线程的进程。

有多种方法。首先,您有3个线程,一个主线程和另外2个(无限循环和键盘线程)

您可以注册信号并对其进行处理,也可以调用interrupt_main来中断主线程(而不是while循环线程)。中断将转到主异常处理程序。另外,我将第二个线程改为具有一个属性,以检查它是否应该为clean exit运行,而不是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()

你能把同样的条件也添加到你的主功能中吗?我不能添加键盘。请等待('ctrl+shift+c')添加到我的主功能中,因为如果我不按“ctrl+shift+c”,它就不能继续了。这就是为什么它被称为WAIT。在这种情况下,让每个函数监视
SIGINT
信号。它可以在标准库的
signal
包中找到。我杀死了名为“pythonw.exe”的进程。有四个。我杀了所有人。我在Spyder工作。斯派德也坠毁了。所以你的解决方案肯定有效,但我更希望Spyder保持开放。在psutil.process\u iter()中为proc定义close\u python():PROCNAME=“pythonw.exe”:#print(proc.name())如果proc.name()=PROCNAME:print('python was closed')proc.kill()还检查信号处理,这是处理这些场景的更好方法。
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()