python如何在不中断while循环的情况下引发Exception



假设我有一些事件侦听器,它假设一直运行,并且有一些exceptions,我想将它们传递给函数调用方,类似于

import asyncio
_ = 0
async def listener(loop):
while True:
await asyncio.sleep(0.5)
if _ != 0:
raise ValueError('the _ is not 0 anymore!')
print('okay')
async def executor(loop):
while True:
x = await loop.run_in_executor(None, input, 'execute: ')
global _
_ = x
async def main(loop):
asyncio.ensure_future(listener(loop), loop=loop)
await executor(loop)

loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))

如果您要更改值,侦听器事件循环将停止,但我不希望它为break,我希望它为raise,这样您就可以捕获它,并且loop将继续运行

我不想让它坏掉,我想让它引发错误,这样你就可以抓住它,循环继续

如果您想引发错误但继续,那么侦听器不应该直接raise。相反,它应该使用Future对象向感兴趣的各方发出异常信号。main()应该在一个循环中等待广播的未来,而不是等待执行器:

import asyncio
_ = 0
broadcast = None
async def listener():
while True:
await asyncio.sleep(0.5)
if _ != 0:
broadcast.set_exception(ValueError('the _ is not 0 anymore!'))
else:
print('okay')
async def executor():
loop = asyncio.get_event_loop()
while True:
x = int(await loop.run_in_executor(None, input, 'execute: '))
global _
_ = x
async def main():
global broadcast
loop = asyncio.get_event_loop()
loop.create_task(listener())
loop.create_task(executor())
while True:
broadcast = loop.create_future()
try:
await broadcast
except ValueError as e:
print('got error', e)
asyncio.get_event_loop().run_until_complete(main())

相关内容

最新更新