【发布时间】:2021-05-05 20:55:28
【问题描述】:
我正在使用 asyncio 进行一些 TCP 通信。我有一个Receive() 函数,它在无限循环中执行read()。这使用asyncio.create_task(Receive()) 作为后台任务运行。
现在,如果连接被对等方关闭,则会引发我在Receive() 函数中捕获的异常(或可能是任何其他异常)。但是,我想重新引发该异常,以便外部代码可以决定要做什么(例如重新连接)。
由于在任务中引发了异常,我不知道如何检索它。
我试图创建一个例子来说明我的意思:
import asyncio
async def divide(x):
try:
return 1/x
except Exception as e:
print("Divide inner exception: ", e)
raise # Re-raise so main() can handle it
async def someFn():
asyncio.create_task(divide(0)) # Exception is never retrieved
# await divide(0) # This will raise two exceptions - the original in divide() and in main()
async def main():
try:
await someFn()
# Do other things while someFn() runs
except Exception as e:
print("main exception: ", e)
asyncio.run(main())
如何获取main()中的任务异常?
【问题讨论】:
标签: python python-asyncio