问题描述
似乎
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 usingCondition
objects form thethreading
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 theQueue
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中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!