Execute the coroutine and return the result. This function runs the passed coroutine, taking care of managing the asyncio event loop and finalizing asynchronous generators. This function cannot be called when another asyncio event loop is running in the same thread.
(main, *, debug=None)
| 158 | |
| 159 | |
| 160 | def run(main, *, debug=None): |
| 161 | """Execute the coroutine and return the result. |
| 162 | |
| 163 | This function runs the passed coroutine, taking care of |
| 164 | managing the asyncio event loop and finalizing asynchronous |
| 165 | generators. |
| 166 | |
| 167 | This function cannot be called when another asyncio event loop is |
| 168 | running in the same thread. |
| 169 | |
| 170 | If debug is True, the event loop will be run in debug mode. |
| 171 | |
| 172 | This function always creates a new event loop and closes it at the end. |
| 173 | It should be used as a main entry point for asyncio programs, and should |
| 174 | ideally only be called once. |
| 175 | |
| 176 | Example: |
| 177 | |
| 178 | async def main(): |
| 179 | await asyncio.sleep(1) |
| 180 | print('hello') |
| 181 | |
| 182 | asyncio.run(main()) |
| 183 | """ |
| 184 | if events._get_running_loop() is not None: |
| 185 | # fail fast with short traceback |
| 186 | raise RuntimeError( |
| 187 | "asyncio.run() cannot be called from a running event loop") |
| 188 | |
| 189 | with Runner(debug=debug) as runner: |
| 190 | return runner.run(main) |
| 191 | |
| 192 | |
| 193 | def _cancel_all_tasks(loop): |