有一段协程代码如下,在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()
网友评论