runners.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. __all__ = 'run',
  2. from . import coroutines
  3. from . import events
  4. from . import tasks
  5. def run(main, *, debug=None):
  6. """Execute the coroutine and return the result.
  7. This function runs the passed coroutine, taking care of
  8. managing the asyncio event loop and finalizing asynchronous
  9. generators.
  10. This function cannot be called when another asyncio event loop is
  11. running in the same thread.
  12. If debug is True, the event loop will be run in debug mode.
  13. This function always creates a new event loop and closes it at the end.
  14. It should be used as a main entry point for asyncio programs, and should
  15. ideally only be called once.
  16. Example:
  17. async def main():
  18. await asyncio.sleep(1)
  19. print('hello')
  20. asyncio.run(main())
  21. """
  22. if events._get_running_loop() is not None:
  23. raise RuntimeError(
  24. "asyncio.run() cannot be called from a running event loop")
  25. if not coroutines.iscoroutine(main):
  26. raise ValueError("a coroutine was expected, got {!r}".format(main))
  27. loop = events.new_event_loop()
  28. try:
  29. events.set_event_loop(loop)
  30. if debug is not None:
  31. loop.set_debug(debug)
  32. return loop.run_until_complete(main)
  33. finally:
  34. try:
  35. _cancel_all_tasks(loop)
  36. loop.run_until_complete(loop.shutdown_asyncgens())
  37. loop.run_until_complete(loop.shutdown_default_executor())
  38. finally:
  39. events.set_event_loop(None)
  40. loop.close()
  41. def _cancel_all_tasks(loop):
  42. to_cancel = tasks.all_tasks(loop)
  43. if not to_cancel:
  44. return
  45. for task in to_cancel:
  46. task.cancel()
  47. loop.run_until_complete(
  48. tasks._gather(*to_cancel, loop=loop, return_exceptions=True))
  49. for task in to_cancel:
  50. if task.cancelled():
  51. continue
  52. if task.exception() is not None:
  53. loop.call_exception_handler({
  54. 'message': 'unhandled exception during asyncio.run() shutdown',
  55. 'exception': task.exception(),
  56. 'task': task,
  57. })