ensure_future
- erstellt Task
und kehrt sofort zurück. Sie sollten erstellt Aufgabe erwarten es Ergebnis zu erhalten (einschließlich Fall, wenn es Ausnahme auslöst):
import asyncio
async def test():
await asyncio.sleep(0)
raise ValueError('123')
async def main():
try:
task = asyncio.ensure_future(test()) # Task aren't finished here yet
await task # Here we await for task finished and here exception would be raised
except ValueError as e:
print(repr(e))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Ausgang:
ValueError('123',)
Falls planen Sie nicht Aufgabe sofort zu erwarten, nachdem Sie es erstellt , können Sie es erwarten später (zu wissen, wie es fertig ist):
async def main():
task = asyncio.ensure_future(test())
await asyncio.sleep(1)
# At this moment task finished with exception,
# but we didn't retrieved it's exception.
# We can do it just awaiting task:
try:
await task
except ValueError as e:
print(repr(e))
Ausgang ist gleich:
ValueError('123',)
Vielen Dank. Weißt du auch, wie man Ausnahmen mit 'call_soon_threadsafe()' abfängt? –
@MarcoSulla Entschuldigung, ich weiß es nicht. Eine Möglichkeit, die ich sehe, ist die Verwendung von Wrapper, um die Ausnahme im Callback zu behandeln: http://pastebin.com/rNyTWMBk, aber ich weiß nicht, ob es so üblich ist. –