代码之家  ›  专栏  ›  技术社区  ›  Henrik Gustafsson

python中的键盘中断阻塞队列

  •  12
  • Henrik Gustafsson  · 技术社区  · 16 年前

    似乎

    import Queue
    
    Queue.Queue().get(timeout=10)
    

    键盘是否可中断(ctrl-c),而

    import Queue
    
    Queue.Queue().get()
    

    不是。我总是可以创建一个循环;

    import Queue
    q = Queue()
    
    while True:
        try:
            q.get(timeout=1000)
        except Queue.Empty:
            pass
    

    但这似乎是一件奇怪的事情。

    那么,有没有一种方法可以获得一个无限期等待但键盘可中断的队列.get()?

    2 回复  |  直到 9 年前
        1
  •  6
  •   Eli Courtwright    16 年前

    Queue 对象具有这种行为,因为它们使用 Condition 对象构成 threading 模块。所以你的解决方案真的是唯一的方法。

    但是,如果你真的想要 排队 方法,您可以使用monkeypatch 排队 班级。例如:

    def interruptable_get(self):
        while True:
            try:
                return self.get(timeout=1000)
            except Queue.Empty:
                pass
    Queue.interruptable_get = interruptable_get
    

    你可以这么说

    q.interruptable_get()
    

    而不是

    interruptable_get(q)
    

    尽管monkeypatching在类似的情况下通常不受Python社区的支持,因为常规函数似乎也很好。

        2
  •  4
  •   Anders Waldenborg    16 年前

    这可能根本不适用于您的用例。但我已经成功地在几个案例中使用了这个模式:(粗略的,可能是小车,但你明白了)。

    STOP = object()
    
    def consumer(q):
        while True:
            x = q.get()
            if x is STOP:
                return
            consume(x)
    
    def main()
        q = Queue()
        c=threading.Thread(target=consumer,args=[q])
    
        try:
            run_producer(q)
        except KeybordInterrupt:
            q.enqueue(STOP)
        c.join()