先上警告报错截图
这是我当时的代码
async def func1(x,y):
print(f'compute {x}+{y}...')
await asyncio.sleep(1)
return x+y
async def func2(x,y):
result = await func1(x,y)
print(f'{x}+{y}={result}')
if __name__ == '__main__':
loop = asyncio.get_event_loop() #1
loop.run_until_complete(func2(1,2))
loop.close()
根据提醒可以知道代码不报错在第11行,也就是我标记1的地方,接下来放上修改后的代码
async def func1(x,y):
print(f'compute {x}+{y}...')
await asyncio.sleep(1)
return x+y
async def func2(x,y):
result = await func1(x,y)
print(f'{x}+{y}={result}')
if __name__ == '__main__':
# loop = asyncio.get_event_loop()
loop = asyncio.new_event_loop() #1
asyncio.set_event_loop(loop) #2
loop.run_until_complete(func2(1,2))
loop.close()
解决这个警告很简单,将
loop = asyncio.get_event_loop()
更换成
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
然后报错就解决了
写在最后 :
“There is no current event loop” 是在 Python 3.7 版本中引入的写法。在此之前,使用 asyncio 库时,如果没有明确创建事件循环,会抛出 RuntimeError 异常。而在 Python 3.7 中,为了简化代码和提供更好的错误提示,引入了新的写法 “There is no current event loop”。这样,在没有明确创建事件循环的情况下,会直接抛出该异常。
所以3.7以上版本都会有这个警告提醒,但仍可以使用原写法。