关于run_until_complete与asyncio.wait如何工作问题
来源:13-2 事件循环-2

东泽XD
2020-11-09
问题围绕loop.run_until_complete(asyncio.wait(tasks))
asyncio.wait给出描述coroutines will be wrapped in tasks
并且return two sets of Future:(donge,pending)
重点是要达成all_complelted才能返回,可是run_until_complete需要他作为调用参数返回值
所以我现在完全无法理解run_until_complete的工作原理,能解答一下么
如果asyncio.wait()作为协程对象传递的话倒是能理解,但这样的话all_complelted就无法理解
简单点来说就是协程对象的返回条件是all_complelted让我很糊涂。
写回答
1回答
-
bobby
2020-11-10
def run_until_complete(self, future): """Run until the Future is done. If the argument is a coroutine, it is wrapped in a Task. WARNING: It would be disastrous to call run_until_complete() with the same coroutine twice -- it would wrap it in two different Tasks and that can't be good. Return the Future's result, or raise its exception. """ self._check_closed() new_task = not futures.isfuture(future) future = tasks.ensure_future(future, loop=self) if new_task: # An exception is raised if the future didn't complete, so there # is no need to log the "destroy pending task" message future._log_destroy_pending = False future.add_done_callback(_run_until_complete_cb) try: self.run_forever() except: if new_task and future.done() and not future.cancelled(): # The coroutine raised a BaseException. Consume the exception # to not log a warning, the caller doesn't have access to the # local task. future.exception() raise finally: future.remove_done_callback(_run_until_complete_cb) if not future.done(): raise RuntimeError('Event loop stopped before Future completed.') return future.result()
这里是源码, 你直接看源码会更清楚,
下面是wait的源码
async def wait(fs, *, loop=None, timeout=None, return_when=ALL_COMPLETED): """Wait for the Futures and coroutines given by fs to complete. The sequence futures must not be empty. Coroutines will be wrapped in Tasks. Returns two sets of Future: (done, pending). Usage: done, pending = await asyncio.wait(fs) Note: This does not raise TimeoutError! Futures that aren't done when the timeout occurs are returned in the second set. """ if futures.isfuture(fs) or coroutines.iscoroutine(fs): raise TypeError(f"expect a list of futures, not {type(fs).__name__}") if not fs: raise ValueError('Set of coroutines/Futures is empty.') if return_when not in (FIRST_COMPLETED, FIRST_EXCEPTION, ALL_COMPLETED): raise ValueError(f'Invalid return_when value: {return_when}') if loop is None: loop = events.get_event_loop() fs = {ensure_future(f, loop=loop) for f in set(fs)} return await _wait(fs, timeout, return_when, loop)
00
相似问题