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

时间:2018-11-23 18:56:38

标签: python-3.x asynchronous exception-handling python-asyncio

让我说我有一些事件监听器应该一直运行,并且有一些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继续前进

1 个答案:

答案 0 :(得分:0)

  

我不希望它中断,我希望它引发错误,这样您就可以抓住它并让循环继续下去

如果要引发错误但继续进行,则侦听器不应直接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())