import queue
qq = queue.Queue()
qq.put('hi')
class MyApp():
def __init__(self, q):
self._queue = q
def _process_item(self, item):
print(f'Processing this item: {item}')
def get_item(self):
try:
item = self._queue.get_nowait()
self._process_item(item)
except queue.Empty:
pass
async def listen_for_orders(self):
'''
Asynchronously check the orders queue for new incoming orders
'''
while True:
self.get_item()
await asyncio.sleep(0)
a = MyApp(qq)
loop = asyncio.get_event_loop()
loop.run_until_complete(a.listen_for_orders())
使用Python 3.6。
我正在尝试编写一个事件处理程序,它可以不断地监听queue
中的消息,并处理这些消息(在本例中打印)。但它必须是异步的 - 我需要能够在终端(IPython)中运行它,并手动向queue
发送内容(至少最初是为了测试)。
以下代码无法正常工作- 它会一直阻塞。
我该如何让它永久运行,但在每次while
循环迭代后返回控制权?
谢谢。
附注:
为了使事件循环与IPython(版本7.2)配合使用,我正在使用此代码来自于ib_insync
库, 在上面的实际问题中,我正在使用这个库。
while True
是不好的。相反,当您向队列中添加内容(使用方法)时,应调用另一个方法从队列中取出元素,执行其操作,并在最后再次检查队列以获取更多元素。如果没有任何元素,则终止。对于此类任务,使用线程也更容易。 - RnDloop.run_until_complete()
会阻塞,但你的方法似乎是同步的。除了在顶部放置消息之外,我没有看到消息被放入队列的地方。你提到手动输入消息...这是什么意思? - Nikolas Stevenson-Molnar