美文网首页
解决This event loop is already run

解决This event loop is already run

作者: 盗花 | 来源:发表于2020-04-04 20:40 被阅读0次

有一段协程代码如下,在PyCharm中能够正确运行,在jupyter notebook中确报错RuntimeError: This event loop is already running

import asyncio
import requests

async def request():
    url = 'https://www.baidu.com'
    status = requests.get(url)
    return status
    
def callback(task):
    print('Status:', task.result())
 
coroutine = request()
task = asyncio.ensure_future(coroutine)
print('Task:', task)

loop = asyncio.get_event_loop()
loop.run_until_complete(task)
print('Task:', task)
print('Task Result:', task.result())

解决办法是封装event loop,参考https://pypi.org/project/nest-asyncio/
,具体如下:
1.pip3 install nest_asyncio
2.在协程代码开头,加上如下两行:

import nest_asyncio
nest_asyncio.apply()

相关文章

网友评论

      本文标题:解决This event loop is already run

      本文链接:https://www.haomeiwen.com/subject/qussphtx.html