我正在使用 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()
?
如何获取任务异常main()
?
您可以利用引发异常的任务这一事实完成,而不是让任务在后台运行,而是实际等待其完成。这要求创建任务的代码不保留返回的任务对象create_task()
并将其返回给调用者或将其存储到一组共享任务中。 (图书馆如trio https://github.com/python-trio/trio甚至不允许盲目地产生后台任务,而是要求每个任务都伴随着nursery https://trio.readthedocs.io/en/stable/reference-core.html#trio.Nursery定义谁处理其异常)。
例如:
async def someFn():
# set up a background task, but also return it to the caller
t = asyncio.create_task(divide(0))
return t
async def other_things():
await asyncio.sleep(1)
async def main():
try:
task = await someFn()
# await both the background task and other things, immediately
# propagating an exception in either
await asyncio.gather(task, other_things())
except Exception as e:
print("main exception: ", e)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)