【发布时间】:2021-10-06 09:36:03
【问题描述】:
我正在使用 python 3.8.7 中的 asyncio 和 asyncua 库,我想使用 asyncio.Queue 将数据从 async 函数传递到主线程。
但是,我遇到的问题是我的队列在第一个await 之后没有收到任何消息。
这是我的例子:
import threading
import time
import asyncio
from asyncua import Client
import aiohttp
async def main(queue1):
queue1.put_nowait("main")
client = Client(url='opc.tcp://localhost:4840/freeopcua/server/')
#client = aiohttp.ClientSession()
async with client:
await queue1.put("in_async")
queue1.put_nowait("in_async_2")
queue1.put_nowait("after await")
def wrapper(queue1: asyncio.Queue):
queue1.put_nowait("wrapper")
asyncio.run(main(queue1))
if __name__ == '__main__':
queue1 = asyncio.Queue()
t = threading.Thread(target=wrapper, args=(queue1,))
t.start()
time.sleep(1)
noEx = True
while noEx:
try:
x = queue1.get_nowait()
print(x)
except asyncio.QueueEmpty:
noEx = False
我明白了:
wrapper
main
如果我使用其他异步库(示例中为 aiohttp),那么一切都会按预期工作:
wrapper
main
in_async
in_async_2
after await
我已经验证 minimal asyncua server 在 opc.tcp://localhost:4840/freeopcua/server/ 服务器工作 - 我可以使用此示例中的代码获取数据,但队列似乎不起作用。我有什么遗漏吗?
【问题讨论】:
标签: python python-3.x asynchronous async-await python-asyncio