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.
我正在尝试编写一个事件处理程序,以不断侦听队列中的消息并对其进行处理(在这种情况下,将它们打印出来).但是它必须是异步的-我需要能够在终端(IPython)中运行它,并将其手动输入到队列中(至少最初是为了进行测试).
此代码不起作用-它会永远阻止.
如何使此操作永久运行,但在while循环的每次迭代后返回控制权?
谢谢.
边注:
为了使事件循环与IPython(7.2版)一起使用,我使用了ib_insync库中的this代码,在上述示例中,我将该库用于现实世界中的问题.