Execute the coroutine and return the result. This function runs the passed coroutine, taking care of managing the asyncio event loop, finalizing asynchronous generators and closing the default executor. This function cannot be called when another asyncio event loop is running i
(main, *, debug=None, loop_factory=None)
| 167 | |
| 168 | |
| 169 | def run(main, *, debug=None, loop_factory=None): |
| 170 | """Execute the coroutine and return the result. |
| 171 | |
| 172 | This function runs the passed coroutine, taking care of |
| 173 | managing the asyncio event loop, finalizing asynchronous |
| 174 | generators and closing the default executor. |
| 175 | |
| 176 | This function cannot be called when another asyncio event loop is |
| 177 | running in the same thread. |
| 178 | |
| 179 | If debug is True, the event loop will be run in debug mode. |
| 180 | If loop_factory is passed, it is used for new event loop creation. |
| 181 | |
| 182 | This function always creates a new event loop and closes it at the end. |
| 183 | It should be used as a main entry point for asyncio programs, and should |
| 184 | ideally only be called once. |
| 185 | |
| 186 | The executor is given a timeout duration of 5 minutes to shutdown. |
| 187 | If the executor hasn't finished within that duration, a warning is |
| 188 | emitted and the executor is closed. |
| 189 | |
| 190 | Example: |
| 191 | |
| 192 | async def main(): |
| 193 | await asyncio.sleep(1) |
| 194 | print('hello') |
| 195 | |
| 196 | asyncio.run(main()) |
| 197 | """ |
| 198 | if events._get_running_loop() is not None: |
| 199 | # fail fast with short traceback |
| 200 | raise RuntimeError( |
| 201 | "asyncio.run() cannot be called from a running event loop") |
| 202 | |
| 203 | with Runner(debug=debug, loop_factory=loop_factory) as runner: |
| 204 | return runner.run(main) |
| 205 | |
| 206 | |
| 207 | def _cancel_all_tasks(loop): |