如何对Ctrl + C键事件进行多线程python程序响应?
编辑:代码是这样的:
import threading
current = 0
class MyThread(threading.Thread):
def __init__(self, total):
threading.Thread.__init__(self)
self.total = total
def stop(self):
self._Thread__stop()
def run(self):
global current
while current<self.total:
lock = threading.Lock()
lock.acquire()
current+=1
lock.release()
print current
if __name__=='__main__':
threads = []
thread_count = 10
total = 10000
for i in range(0, thread_count):
t = MyThread(total)
t.setDaemon(True)
threads.append(t)
for i in range(0, thread_count):
threads[i].start()
Run Code Online (Sandbox Code Playgroud)
我试图在所有线程上删除join()但它仍然无效.是因为每个线程的run()过程中的锁段?
编辑:上面的代码应该可以工作但是当当前变量在5,000-6,000范围内并且通过如下错误时它总是被中断
Exception in thread Thread-4 (most likely raised during interpreter shutdown):
Traceback (most recent call …Run Code Online (Sandbox Code Playgroud) 我正在制作一个简单的多线程端口扫描器.它扫描主机上的所有端口并返回打开的端口.麻烦在于中断扫描.扫描完成需要花费大量时间,有时我希望在扫描过程中用Cc杀死程序.麻烦的是扫描不会停止.主线程被锁定在queue.join()上,并且忘记了KeyboardInterrupt,直到处理了队列中的所有数据,因此解除了主线程并正常退出程序.我的所有线程都被守护进来,所以当主线程死掉时,他们应该和他一起死掉.
我尝试使用信号库,没有成功.覆盖threading.Thread类和正常终止的添加方法不起作用...主线程在执行queue.join()时不会收到KeyboardInterrupt
import threading, sys, Queue, socket
queue = Queue.Queue()
def scan(host):
while True:
port = queue.get()
if port > 999 and port % 1000 == 0:
print port
try:
#sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#sock.settimeout(2) #you need timeout or else it will try to connect forever!
#sock.connect((host, port))
#----OR----
sock = socket.create_connection((host, port), timeout = 2)
sock.send('aaa')
data = sock.recv(100)
print "Port {} open, message: {}".format(port, data)
sock.shutdown()
sock.close()
queue.task_done()
except:
queue.task_done()
def main(host):
#populate queue
for i in range(1, …Run Code Online (Sandbox Code Playgroud) 我正在编写一个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并终止脚本的任何建议.