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

python how to raise Exception without breaking a while loop

假设我有一些事件侦听器假设一直 运行 并且有一些 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 继续前进

I dont want it to break I want it to raise the error so you will be able to catch it and the loop to keep going

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