相关疑难解决方法(0)

带线程的Python程序无法捕获CTRL + C.

我正在编写一个python脚本,需要运行一个侦听网络套接字的线程.

我使用以下代码使用Ctrl+ 杀死它时遇到了麻烦c:

#!/usr/bin/python

import signal, sys, threading

THREADS = []

def handler(signal, frame):
    global THREADS
    print "Ctrl-C.... Exiting"
    for t in THREADS:
        t.alive = False
    sys.exit(0)

class thread(threading.Thread):
    def __init__(self):
        self.alive = True
        threading.Thread.__init__(self)


    def run(self):
        while self.alive:
            # do something
            pass

def main():
    global THREADS
    t = thread()
    t.start()
    THREADS.append(t)

if __name__ == '__main__':
    signal.signal(signal.SIGINT, handler)
    main()
Run Code Online (Sandbox Code Playgroud)

欣赏有关如何捕获Ctrl+ c并终止脚本的任何建议.

python multithreading

9
推荐指数
2
解决办法
1万
查看次数

使用threading.Timer时,Ctrl-C不起作用

我正在Windows上编写一个多线程Python应用程序.

我曾经使用过终止应用程序ctrl-c,但是一旦我添加了threading.Timer实例ctrl-c停止工作(或者有时需要很长时间).

怎么会这样?
具有Timer线程和ctrl-c?之间的关系是什么?

更新:
我在Python的线程文档中发现了以下内容:

线程与中断奇怪地交互:KeyboardInterrupt异常将由任意线程接收.(当信号模块可用时,中断始终转到主线程.)

python multithreading timer

6
推荐指数
1
解决办法
3598
查看次数

标签 统计

multithreading ×2

python ×2

timer ×1