2 回答

TA貢獻1820條經驗 獲得超10個贊
該asyncio.run()
文件說:
當另一個異步事件循環在同一線程中運行時,無法調用此函數。
在您的情況下,jupyter(IPython ≥ 7.0)已經在運行事件循環:
您現在可以在 IPython 終端和筆記本中的頂層使用 async/await,它應該——在大多數情況下——“正常工作”。將 IPython 更新到版本 7+,將 IPykernel 更新到版本 5+,然后您就可以參加比賽了。
因此,您無需自己啟動事件循環,而是可以await main(url)
直接調用,即使您的代碼位于任何異步函數之外。
Jupyter/IPython
async def main():
print(1)
await main()
蟒蛇 (≥ 3.7)
import asyncio
async def main():
print(1)
asyncio.run(main())
在您的代碼中,將給出:
url = ['url1', 'url2']
result = await main(url)
for text in result:
pass # text contains your html (text) response
警告
與 IPython 相比,Jupyter 使用循環的方式略有不同。

TA貢獻1826條經驗 獲得超6個贊
要添加 tocglacet的答案 - 如果想要檢測循環是否正在運行并自動調整(即main()在現有循環上運行,否則asyncio.run()),這里是一個可能有用的片段:
# async def main():
# ...
try:
loop = asyncio.get_running_loop()
except RuntimeError: # 'RuntimeError: There is no current event loop...'
loop = None
if loop and loop.is_running():
print('Async event loop already running. Adding coroutine to the event loop.')
tsk = loop.create_task(main())
# ^-- https://docs.python.org/3/library/asyncio-task.html#task-object
# Optionally, a callback function can be executed when the coroutine completes
tsk.add_done_callback(
lambda t: print(f'Task done with result={t.result()} << return val of main()'))
else:
print('Starting new event loop')
asyncio.run(main())
添加回答
舉報