Asynchronous Python 3.6+中的异步POST;在while循环中
场景如下。 我正在使用OpenCV从本地网络摄像头捕获帧。 我想用以下逻辑在while循环中发布每一帧:Asynchronous Python 3.6+中的异步POST;在while循环中,asynchronous,python-asyncio,aiohttp,Asynchronous,Python Asyncio,Aiohttp,场景如下。 我正在使用OpenCV从本地网络摄像头捕获帧。 我想用以下逻辑在while循环中发布每一帧: url = "http://www.to.service" while True: cap = cv2.VideoCapture(0) try: _, frame = cap.read() frame_data = do_something(frame) async_post(url, frame_data) except Keyb
url = "http://www.to.service"
while True:
cap = cv2.VideoCapture(0)
try:
_, frame = cap.read()
frame_data = do_something(frame)
async_post(url, frame_data)
except KeyboardInterrupt:
break
我用asyncio
和aiohttp
尝试了以下内容,但没有成功
async def post_data(session, url, data):
async with session.post(url) as response:
return await response.text()
async def main():
async with aiohttp.ClientSession() as session:
cap = cv2.VideoCapture(0)
while True:
try:
_, frame = cap.read()
frame_data = do_something(frame) # get a dict
await post_data(session, url, frame_data) # post the dict
except KeyboardInterrupt:
break
cap.release()
cv2.destroyAllWindows()
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
据我所知,本文给出的逻辑可能不适合异步请求,因为原则上我无法填写要收集的任务列表。
我希望这足够清楚。如果不是,请提前道歉。
非常感谢您的帮助。
干杯你能详细说明没有成功意味着什么吗?你有例外吗?如果是,请张贴回溯。否则,请告诉我们程序是如何失败的。不会产生错误。post只是同步执行。请注意,您有一个
wait
,它告诉asyncio等待它完成。如果要在后台继续发布,则应使用asyncio.create_task(POST_data(…)
。您可能还需要将,frame=cap.read()
更改为,frame=wait循环。在执行器(None,cap.read)
中运行事件循环,同时等待下一个映像。