从线程消耗的鼠标忽略KeyboardInterrupt

时间:2017-06-26 19:53:26

标签: python multithreading python-2.7 rabbitmq pika

我正在尝试使用来自github的pika 0.10.0运行以下测试:

import logging
import sys
import pika
import threading

logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
URL = 'amqp://guest:guest@127.0.0.1:5672/%2F?socket_timeout=0.25'


class BaseConsumer(threading.Thread):

    def run(self):
        self._connection = None
        self._channel = None
        self.connect()
        self.open_channel()
        self.consume()

    def connect(self):
        parameters = pika.URLParameters(URL)
        self._connection = pika.BlockingConnection(parameters)

    def open_channel(self):
        self._channel = self._connection.channel()
        self._channel.exchange_declare(exchange='exc1', exchange_type='topic', passive=False,
                                       durable=False, auto_delete=False, internal=False, arguments=None)
        self._channel.queue_declare(queue='test', passive=False, durable=False,
                                    exclusive=False, auto_delete=False, arguments=None)
        self._channel.queue_bind(
            'test', 'exc1', routing_key='rk', arguments=None)

    def consume(self):
        self._channel.basic_consume(self.on_message, 'test')
        try:
            self._channel.start_consuming()
        except KeyboardInterrupt:
            logging.info("Stop consuming now!")
            self._channel.stop_consuming()
        self._connection.close()

    def on_message(self, channel, method_frame, header_frame, body):
        print method_frame.delivery_tag
        print body
        channel.basic_ack(delivery_tag=method_frame.delivery_tag)

c1 = BaseConsumer()
c1.setDaemon(False)
c1.start()

脚本正在连接到我的MQ,并且显然能够使用来自MQ的消息。问题是我无法阻止线程。在我的键盘上按CTRL-C只会导致" ^ C"在不中断消耗的情况下出现在控制台中。

问题是,当它在线程内运行时,如何让鼠兔停止消耗?我想请注意,我遵循在消费者线程中创建连接的准则。

如果在使用c1.start()启动线程之后,我还执行无限循环并从那里记录一些内容然后按下CTRL-C将结束while循环,但是消费者线程仍将忽略任何其他CTRL-C。 / p>

附带问题:是否有可能停止在线程内部使用某些外部信号,如线程。条件或什么?我不知道如何干扰start_consuming。

1 个答案:

答案 0 :(得分:0)

  

问题:...然后按CTRL-C将结束while循环

def stop()添加BaseConsumer
抓住KeyboardInterrupt并致电stop()

try: 
    BaseConsumer.run() 
except KeyboardInterrupt: 
    BaseConsumer.stop()

阅读pika: asynchronous_consumer_example