__all__ = 'run',from . import coroutinesfrom . import eventsfrom . import tasksdef run(main, *, debug=False):"""Run a coroutine.This function runs the passed coroutine, taking care ofmanaging the asyncio event loop and finalizing asynchronousgenerators.This function cannot be called when another asyncio event loop isrunning in the same thread.If debug is True, the event loop will be run in debug mode.This function always creates a new event loop and closes it at the end.It should be used as a main entry point for asyncio programs, and shouldideally only be called once.Example:async def main():await asyncio.sleep(1)print('hello')asyncio.run(main())"""if events._get_running_loop() is not None:raise RuntimeError("asyncio.run() cannot be called from a running event loop")if not coroutines.iscoroutine(main):raise ValueError("a coroutine was expected, got {!r}".format(main))loop = events.new_event_loop()try:events.set_event_loop(loop)loop.set_debug(debug)return loop.run_until_complete(main)finally:try:_cancel_all_tasks(loop)loop.run_until_complete(loop.shutdown_asyncgens())finally:events.set_event_loop(None)loop.close()def _cancel_all_tasks(loop):to_cancel = tasks.all_tasks(loop)if not to_cancel:returnfor task in to_cancel:task.cancel()loop.run_until_complete(tasks.gather(*to_cancel, loop=loop, return_exceptions=True))for task in to_cancel:if task.cancelled():continueif task.exception() is not None:loop.call_exception_handler({'message': 'unhandled exception during asyncio.run() shutdown','exception': task.exception(),'task': task,})
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。