[英]python3.8 RuntimeError: no running event loop
我從作者 caleb hattingh 的書中獲取了以下代碼片段。 我嘗試運行代碼片段並遇到此錯誤。(練習)
我該如何解決這個問題?
import asyncio
async def f(delay):
await asyncio.sleep(1 / delay)
return delay
loop = asyncio.get_event_loop()
for i in range(10):
loop.create_task(f(i))
print(loop)
pending = asyncio.all_tasks()
group = asyncio.gather(*pending, return_exceptions=True)
results = loop.run_until_complete(group)
print(f'Results: {results}')
loop.close()
您必須將loop
作為參數傳遞給.all_tasks()
function:
pending = asyncio.all_tasks(loop)
Output:
<_UnixSelectorEventLoop running=False closed=False debug=False>
<_GatheringFuture pending>
Results: [8, 5, 2, 9, 6, 3, ZeroDivisionError('division by zero'), 7, 4, 1]
因此,要全面更正您的腳本:
import asyncio
async def f(delay):
if delay:
await asyncio.sleep(1 / delay)
return delay
loop = asyncio.get_event_loop()
for i in range(10):
loop.create_task(f(i))
print(loop)
pending = asyncio.all_tasks(loop)
group = asyncio.gather(*pending, return_exceptions=True)
results = loop.run_until_complete(group)
print(f'Results: {results}')
loop.close()
使用python3.7
及以后的版本可以省略事件循環和任務的顯式創建和管理。 asyncio
API 已經更改了幾次,您會找到涵蓋過時語法的教程。 以下實現對應於您的解決方案。
import asyncio
async def f(delay):
await asyncio.sleep(1 / delay)
return delay
async def main():
return await asyncio.gather(*[f(i) for i in range(10)], return_exceptions=True)
print(asyncio.run(main()))
Output
[ZeroDivisionError('division by zero'), 1, 2, 3, 4, 5, 6, 7, 8, 9]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.