请问用Task封装两个coroutine的代码在python最新版应该怎么做?
Topic source做出来了,自问自答下吧
import threading
import asyncio
async def hello():
print('Hello world! (%s)' % threading.current_thread())
await asyncio.sleep(1)
print('Hello again! (%s)' % threading.current_thread())
loop = asyncio.new_event_loop()
a1 = loop.create_task(hello())
a2 = loop.create_task(hello())
tasks = [a1, a2]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
主要是用create_task将协程对象变为task,然后要用loop.create_task而不是asyncio.create_task;depreciation方面,currentThread换成了current_thread;get_event_loop换成了new_event_loop
- 1
juven永恒
我把它改成了这样,因为新版本已经用async,await 关键词代替@asyncio.coroutine,yield
但是这样做就会报错RuntimeWarning: coroutine 'hello' was never awaited,我搜索的原因是说python 3.11版本禁止将协程对象直接传递给 wait(),但这个应该怎么改呢?改了很多次都是报这个错