blob: 03ce33300eba8316f849e0d9e9cee0c4d5088c88 [file] [log] [blame]
Yury Selivanov02a0a192017-12-14 09:42:21 -05001__all__ = 'run',
2
3from . import coroutines
4from . import events
Yury Selivanova4afcdf2018-01-21 14:56:59 -05005from . import tasks
Yury Selivanov02a0a192017-12-14 09:42:21 -05006
7
8def run(main, *, debug=False):
Kyle Stanleye4070132019-09-30 20:12:21 -04009 """Execute the coroutine and return the result.
Yury Selivanov02a0a192017-12-14 09:42:21 -050010
11 This function runs the passed coroutine, taking care of
12 managing the asyncio event loop and finalizing asynchronous
13 generators.
14
15 This function cannot be called when another asyncio event loop is
16 running in the same thread.
17
18 If debug is True, the event loop will be run in debug mode.
19
20 This function always creates a new event loop and closes it at the end.
21 It should be used as a main entry point for asyncio programs, and should
22 ideally only be called once.
23
24 Example:
25
26 async def main():
27 await asyncio.sleep(1)
28 print('hello')
29
30 asyncio.run(main())
31 """
32 if events._get_running_loop() is not None:
33 raise RuntimeError(
34 "asyncio.run() cannot be called from a running event loop")
35
36 if not coroutines.iscoroutine(main):
37 raise ValueError("a coroutine was expected, got {!r}".format(main))
38
39 loop = events.new_event_loop()
40 try:
41 events.set_event_loop(loop)
42 loop.set_debug(debug)
43 return loop.run_until_complete(main)
44 finally:
45 try:
Yury Selivanova4afcdf2018-01-21 14:56:59 -050046 _cancel_all_tasks(loop)
Yury Selivanov02a0a192017-12-14 09:42:21 -050047 loop.run_until_complete(loop.shutdown_asyncgens())
Kyle Stanley9fdc64c2019-09-19 08:47:22 -040048 loop.run_until_complete(loop.shutdown_default_executor())
Yury Selivanov02a0a192017-12-14 09:42:21 -050049 finally:
50 events.set_event_loop(None)
51 loop.close()
Yury Selivanova4afcdf2018-01-21 14:56:59 -050052
53
54def _cancel_all_tasks(loop):
Yury Selivanov416c1eb2018-05-28 17:54:02 -040055 to_cancel = tasks.all_tasks(loop)
Yury Selivanova4afcdf2018-01-21 14:56:59 -050056 if not to_cancel:
57 return
58
59 for task in to_cancel:
60 task.cancel()
61
62 loop.run_until_complete(
63 tasks.gather(*to_cancel, loop=loop, return_exceptions=True))
64
65 for task in to_cancel:
66 if task.cancelled():
67 continue
68 if task.exception() is not None:
69 loop.call_exception_handler({
70 'message': 'unhandled exception during asyncio.run() shutdown',
71 'exception': task.exception(),
72 'task': task,
73 })