python keyboard方法_多线程中的Python KeyboardInterrupt

本文讨论了在Python多线程环境中,如何正确处理KeyboardInterrupt信号,以便在按下CTRL+C时终止所有线程。示例代码中包含了定时器线程和Web服务器线程,通过自定义的join函数和信号处理来实现中断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Can anyone please tell me why the KeyboardInterrupt is not working here? I need to end both of the threads by the press of CTRL+C. The two threads - Timer thread and Web server thread. Here is the code -

import threading

import thread

import time

import urllib2

import httplib

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler

from SocketServer import ThreadingMixIn

import Queue

import signal

import sys

q = Queue.Queue()

j = Queue.Queue()

h = "threading working!"

class SignalHandler:

stopper = None

def __init__(self,stopper):

self.stopper = stopper

def __call__(self, signum, frame):

self.stopper.set()

sys.exit(0)

#Timer Thread

class myThread(threading.Thread):

stopper = None

def __init__(self, **kwargs):

self.req = []

self.stopper = stopper

for k, v in kwargs.iteritems():

setattr(self, k, v)

threading.Thread.__init__(self)

def run(self):

while not self.stopper.is_set():

while self.go:

try:

while True:

r = q.get_nowait()

self.req.append(r)

except Queue.Empty, e:

pass

t = threading.Timer(1,self.hello, [h])

t.start()

time.sleep(1)

def hello(self, s):

print s

while self.req:

r = self.req.pop()

print "Client Request >>>>>>>", r

thread_id = str(threading.currentThread())

j.put(thread_id)

def stop(self):

print "Stopping thread.."

self.go = False

try:

while True:

q.get_nowait()

q.task_done()

except Queue.Empty, e:

pass

#Webserver thread

class Handler(BaseHTTPRequestHandler):

def do_HEAD(self):

self.send_response(200)

self.send_header("Content type", "text/html")

self.end_headers()

def do_GET(self):

self.do_HEAD()

req = (self.path, self.client_address, self.command,)

q.put(req)

self.wfile.write("Thread Info: ")

self.wfile.write(j.get())

return

class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):

"""Handle requests in a separate thread."""

#main

if __name__ == '__main__':

stopper = threading.Event()

handler = SignalHandler(stopper)

signal.signal(signal.SIGINT, handler)

server = ThreadedHTTPServer(('localhost', 8080), Handler)

try:

timer_thread = myThread(stopper,go=True)

timer_thread.start()

server_thread = threading.Thread(target=server.serve_forever)

server_thread.daemon = True

server_thread.start()

print 'Starting server, use to stop'

except KeyboardInterrupt, e:

print "Interrupted"

q.join()

j.join()

timer_thread.stop()

timer_thread.join()

解决方案

First, your instance myThread in created with error, must be stopper=stopper (keyword arg is expected). Second, code has error, main thread does not wait server thread but immediately go to join()s. So, except never happens - nothing will be printed. And main bug is in join(). Join in Python is not interruptable by signals. So, you must write own join function, which will call original join() with timeout (for example, 1 second) but in the infinitive loop. Better is to make join with little timeout and next - sleep() - sleep is interruptable. Both in the loop.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值