Python 3中的KeyboardInterrupt多线程

3
我正在尝试使用以下代码使主线程等待其工作线程完成,但当我尝试使用Ctrl+C中断时,它不会停止。
import threading
import sys
exit = threading.Event()

#pass it to the threads

try:
    exit.wait()
    print('Goodbye')
    sys.exit()
except KeyboardInterrupt:
    print('Interrupted')
    sys.exit()

更新 没有任何输出。所有后台线程都是守护程序。


1
有格式错误。已修复。 - Colin Sergi
1
你在哪个平台上?在Linux或macOS上(除非你使用的是基本上已经损坏的3.0-3.1版本),我相信所有对线程对象的wait操作都应该可以被信号中断,并且一旦被中断,Python将立即将SIGINT处理为KeyboardInterrupt。但是在Windows上...我不确定它是如何工作的,但你可能需要更多的东西。 - abarnert
1
另外,我假设主线程仍然被 exit.wait() 阻塞着,还没有打印出 Goodbye,是这样吗?(如果不是,那么它已经离开了 try/except 块,所以显然 try 无法捕获异常。) - abarnert
1
守护线程还是普通线程?“中断”会打印吗? - Sraw
我正在使用Windows操作系统。主线程仍然被阻塞。所有我的后台线程目前都是守护进程。 - Colin Sergi
1个回答

1
import threading
import sys
import time
exit = threading.Event()

#pass it to the threads

try:
    print("hi")
    time.sleep(20)
    print('Goodbye')
    sys.exit()
except KeyboardInterrupt:
    print('Interrupted')
    sys.exit()

请尝试使用上述语句测试您的代码。我已经测试过了,对我来说运行得很好。
由于您在没有设置任何超时的情况下使用了exit.wait(),它将无限运行。因此,请将一些时间作为参数传入。 按照以下代码进行操作:
exit = threading.Event()

#pass it to the threads

try:
    print("hi")
    exit.wait(5)
    print('Goodbye')
    sys.exit()
except KeyboardInterrupt:
    print('Interrupted')
    sys.exit()

我正在尝试让主线程无限等待,除非被中断,最好不要只是运行一个检查标志的while循环。 - Colin Sergi
这是可能的吗? - Colin Sergi
1
如果使用循环,那是可以实现的。但是使用Wait()是不可能的。 - Nitikesh Pattanayak

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接