本文介绍了键盘可中断的阻塞队列在Python中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎

  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)
(Queue.Empty除外):
pass

但这看起来很奇怪。



所以,有一种方法可以无限期地等待,键盘中断Queue.get()?

解决方案

队列行为,因为它们使用条件锁定线程模块。所以你的解决方案是唯一的方法。



但是,如果你真的想要一个 Queue 这个,你可以修改 Queue 类。例如:

  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)

虽然在这种情况下,Python社区通常不建议使用monkeypatching,因为常规功能似乎也一样好。


It seems

import Queue

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

is keyboard interruptible (ctrl-c) whereas

import Queue

Queue.Queue().get()

is not. I could always create a loop;

import Queue
q = Queue()

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

but this seems like a strange thing to do.

So, is there a way of getting an indefinitely waiting but keyboard interruptible Queue.get()?

解决方案

Queue objects have this behavior because they lock using Condition objects form the threading module. So your solution is really the only way to go.

However, if you really want a Queue method that does this, you can monkeypatch the Queue class. For example:

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

This would let you say

q.interruptable_get()

instead of

interruptable_get(q)

although monkeypatching is generally discouraged by the Python community in cases such as these, since a regular function seems just as good.

这篇关于键盘可中断的阻塞队列在Python中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 06:56