Hen*_*son 12 python concurrency multithreading python-2.x
它似乎
import Queue
Queue.Queue().get(timeout=10)
Run Code Online (Sandbox Code Playgroud)
是键盘可中断(ctrl-c)而
import Queue
Queue.Queue().get()
Run Code Online (Sandbox Code Playgroud)
不是.我总是可以创建一个循环;
import Queue
q = Queue()
while True:
try:
q.get(timeout=1000)
except Queue.Empty:
pass
Run Code Online (Sandbox Code Playgroud)
但这似乎是一件奇怪的事情.
那么,是否有一种方法可以无限期地等待但是键盘可以中断Queue.get()?
Queue对象具有此行为,因为它们使用Condition对象形成threading模块.所以你的解决方案真的是唯一的出路.
但是,如果您真的想要一个Queue执行此操作的方法,则可以对该Queue类进行monkeypatch .例如:
def interruptable_get(self):
while True:
try:
return self.get(timeout=1000)
except Queue.Empty:
pass
Queue.interruptable_get = interruptable_get
Run Code Online (Sandbox Code Playgroud)
这会让你说
q.interruptable_get()
Run Code Online (Sandbox Code Playgroud)
代替
interruptable_get(q)
Run Code Online (Sandbox Code Playgroud)
虽然在这种情况下,Python社区通常不鼓励monkeypatching,因为常规函数似乎同样好.