python异步处理失败_具有异步功能的Python事件处理程序(无阻塞...

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代码,在上述示例中,我将该库用于现实世界中的问题.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值