a Z^@srdZdZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl m Z ddl mZddl mZdd l mZdd l mZedjZdBd d ZdCd dZdDddZddZGdddejZeZz ddlZWneyYn 0ejZZddddZejj Z ejj!Z!ejj"Z"dde"dddZ#ddZ$ddddZ%d d!Z&d"d#Z'ddd$d%d&Z(ej)d'd(Z*dEddd)d*Z+ddd+d,Z,ej)d-d.Z-ee-_Gd/d0d0ej.Z/dd1d2d3d4Z0ddd5d6Z1d7d8Z2e 3Z4iZ5d9d:Z6d;d<Z7d=d>Z8d?d@Z9e6Z:e9Z;e7Ze9Z?e7Z@e8ZAdS)Fz0Support for tasks, coroutines and the scheduler.)Task create_taskFIRST_COMPLETEDFIRST_EXCEPTION ALL_COMPLETEDwaitwait_for as_completedsleepgathershield ensure_futurerun_coroutine_threadsafe current_task all_tasks_register_task_unregister_task _enter_task _leave_taskN) base_tasks) coroutines)events) exceptions)futures) _is_coroutinecCs|durt}t|S)z!Return a currently executed task.N)rget_running_loop_current_tasksgetloopr!%/usr/lib64/python3.9/asyncio/tasks.pyr"srcs\durtd}z tt}WqJtyD|d7}|dkr@Yq0qJqfdd|DS)z'Return a set of all tasks for the loop.Nrrcs&h|]}t|ur|s|qSr!)r _get_loopdone.0trr!r" <szall_tasks..)rrlist _all_tasks RuntimeErrorr iZtasksr!rr"r)s  rcs\durtd}z tt}WqJtyD|d7}|dkr@Yq0qJqfdd|DS)Nrrr#csh|]}t|ur|qSr!)rr$r&rr!r"r)Uz$_all_tasks_compat..)rget_event_loopr*r+r,r-r!rr"_all_tasks_compat@s  r1cCs2|dur.z |j}Wnty$Yn 0||dSN)set_nameAttributeError)tasknamer3r!r!r"_set_task_nameXs   r7cseZdZdZdZed'ddZed(ddZdddfd d Zfd d Z d dZ ddZ ddZ ddZ ddZddZddZddddZddddd Zd)d!d"Zd*fd#d$ Zd%d&ZZS)+rz A coroutine wrapped in a Future.TNcCs(tjdtdd|dur t}t|S)zReturn the currently running task in an event loop or None. By default the current task for the current event loop is returned. None is returned when called not in the context of a Task. zVTask.current_task() is deprecated since Python 3.7, use asyncio.current_task() instead stacklevelN)warningswarnDeprecationWarningrr0rclsr r!r!r"rtszTask.current_taskcCstjdtddt|S)z|Return a set of all tasks for an event loop. By default all tasks for the current event loop are returned. zPTask.all_tasks() is deprecated since Python 3.7, use asyncio.all_tasks() insteadr8r9)r;r<r=r1r>r!r!r"rs zTask.all_tasks)r r6cstj|d|jr|jd=t|s:d|_td||durRdt|_n t ||_d|_ d|_ ||_ t |_|jj|j|jdt|dS)NrFza coroutine was expected, got zTask-context)super__init___source_tracebackr iscoroutine_log_destroy_pending TypeError_task_name_counter_namestr _must_cancel _fut_waiter_coro contextvarsZ copy_context_context_loop call_soon _Task__stepr)selfcoror r6 __class__r!r"rDs   z Task.__init__csF|jtjkr8|jr8|dd}|jr,|j|d<|j|tdS)Nz%Task was destroyed but it is pending!)r5messageZsource_traceback) _staterZ_PENDINGrGrErQZcall_exception_handlerrC__del__)rTrBrVr!r"rZs  z Task.__del__cCs|Sr2r!)r?typer!r!r"__class_getitem__szTask.__class_getitem__cCs t|Sr2)rZ_task_repr_inforTr!r!r" _repr_infoszTask._repr_infocCs|jSr2)rNr]r!r!r"get_corosz Task.get_corocCs|jSr2)rJr]r!r!r"get_namesz Task.get_namecCst||_dSr2)rKrJ)rTvaluer!r!r"r3sz Task.set_namecCs tddS)Nz*Task does not support set_result operationr,)rTresultr!r!r" set_resultszTask.set_resultcCs tddS)Nz-Task does not support set_exception operationrb)rT exceptionr!r!r" set_exceptionszTask.set_exception)limitcCs t||S)aReturn the list of stack frames for this task's coroutine. If the coroutine is not done, this returns the stack where it is suspended. If the coroutine has completed successfully or was cancelled, this returns an empty list. If the coroutine was terminated by an exception, this returns the list of traceback frames. The frames are always ordered from oldest to newest. The optional limit gives the maximum number of frames to return; by default all available frames are returned. Its meaning differs depending on whether a stack or a traceback is returned: the newest frames of a stack are returned, but the oldest frames of a traceback are returned. (This matches the behavior of the traceback module.) For reasons beyond our control, only one stack frame is returned for a suspended coroutine. )rZ_task_get_stack)rTrgr!r!r" get_stackszTask.get_stack)rgfilecCst|||S)anPrint the stack or traceback for this task's coroutine. This produces output similar to that of the traceback module, for the frames retrieved by get_stack(). The limit argument is passed to get_stack(). The file argument is an I/O stream to which the output is written; by default output is written to sys.stderr. )rZ_task_print_stack)rTrgrir!r!r" print_stacks zTask.print_stackcCs>d|_|rdS|jdur.|jj|dr.dSd|_||_dS)aRequest that this task cancel itself. This arranges for a CancelledError to be thrown into the wrapped coroutine on the next cycle through the event loop. The coroutine then has a chance to clean up or even deny the request using try/except/finally. Unlike Future.cancel, this does not guarantee that the task will be cancelled: the exception might be caught and acted upon, delaying cancellation of the task or preventing cancellation completely. The task may also return a value or raise a different exception. Immediately after this method is called, Task.cancelled() will not return True (unless the task was already cancelled). A task will be marked as cancelled when the wrapped coroutine terminates with a CancelledError exception (even if cancel() was not called). FNmsgT)Z_log_tracebackr%rMcancelrL_cancel_message)rTrlr!r!r"rms z Task.cancelc s|rtd|d||jr>t|tjs8|}d|_|j}d|_t |j |zz"|durp| d}n | |}Wnt y}z:|jrd|_tj|jdnt|jWYd}~n d}~0tjy}z||_tWYd}~nd}~0ttfy>}zt|WYd}~nd}~0typ}zt|WYd}~n~d}~00t|dd}|durjt||j urtd|d|d}|j j|j||jd n|r>||urtd |}|j j|j||jd n>d|_|j |j!|jd ||_|jrh|jj|jdrhd|_n*td |d |}|j j|j||jd n||dur|j j|j|jd n\t"#|rtd |d |}|j j|j||jd n$td|}|j j|j||jd Wt$|j |d}nt$|j |d}0dS)Nz_step(): already done: z, Frk_asyncio_future_blockingzTask z got Future z attached to a different looprAzTask cannot await on itself: z-yield was used instead of yield from in task z with z;yield was used instead of yield from for generator in task zTask got bad yield: )%r%rInvalidStateErrorrL isinstanceCancelledError_make_cancelled_errorrNrMrrQsendthrow StopIterationrCrmrnrdraZ_cancelled_excKeyboardInterrupt SystemExitrf BaseExceptiongetattrrr$r,rRrSrProadd_done_callback _Task__wakeupinspectZ isgeneratorr)rTexcrUrcblockingnew_excrVr!r"Z__step s   $  $            z Task.__stepc CsLz |Wn.ty:}z||WYd}~nd}~00|d}dSr2)rcryrS)rTfuturer~r!r!r"Z__wakeupbs   z Task.__wakeup)N)N)N)N)__name__ __module__ __qualname____doc__rG classmethodrrrDrZr\r^r_r`r3rdrfrhrjrmrSr| __classcell__r!r!rVr"rbs(     "Wr)r6cCs t}||}t|||S)z]Schedule the execution of a coroutine object in a spawn task. Return a Task object. )rrrr7)rUr6r r5r!r!r"rs  r)r timeout return_whencst|st|r(tdt|j|s4td|tt t fvrPtd|durbt nt jdtddtdd t|Drt jd tddfd d t|D}t|||IdHS) aWait 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. expect a list of futures, not z#Set of coroutines/Futures is empty.zInvalid return_when value: N[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.r8r9css|]}t|VqdSr2)rrFr'fr!r!r" r/zwait..zThe explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11.csh|]}t|dqSrr rrr!r"r)r/zwait..)risfuturerrFrHr[r ValueErrorrrrrrr;r<r=anyset_wait)fsr rrr!rr"rs" rcGs|s|ddSr2)r%rd)waiterargsr!r!r"_release_waitersrrc sr|durt}ntjdtdd|dur4|IdHS|dkrht||d}|rX|S|t | }| |t |}tt |}t||d}||zz|IdHWn(t jy|||Yn0|r|W|S||t||dIdHz |Wn2t jyN}zt |WYd}~nd}~00t W|n |0dS)aWait for the single Future or coroutine to complete, with timeout. Coroutine will be wrapped in Task. Returns result of the Future or coroutine. When a timeout occurs, it cancels the task and raises TimeoutError. To avoid the task cancellation, wrap it in shield(). If the wait is cancelled, the task is also cancelled. This function is a coroutine. Nrr8r9rr)rrr;r<r=r r%rcrmr TimeoutError create_future call_laterr functoolspartialr{rrremove_done_callback_cancel_and_wait)futrr rtimeout_handlecbr~r!r!r"rsJ            rc s|s Jd|d|dur.||tt|fdd}|D]}||qLz2IdHWdurz|D]}||q~n&dur|D]}||q0tt}}|D]"}|r| |q| |q||fS)zVInternal helper for wait(). The fs argument must be a collection of Futures. zSet of Futures is empty.NcsZd8dks4tks4tkrV|sV|durVdurDsVddS)Nrr)rr cancelledrermr%rdrZcounterrrrr!r"_on_completions z_wait.._on_completion) rrrlenr{rmrrr%add)rrrr rrr%pendingr!rr"rs2      rc sP|}tt|}||z ||IdHW||n ||0dS)z.cs*D]}|dqdSr2)r put_nowaitclearr)rr%todor!r" _on_timeoutbs  z!as_completed.._on_timeoutcs4sdS||s0dur0dSr2)removerrmr)r%rrr!r"rhs    z$as_completed.._on_completioncs$IdH}|durtj|Sr2)rrrrcr)r%r!r" _wait_for_onepsz#as_completed.._wait_for_one)rrrrFrHr[rqueuesrrr0r;r<r=rr{rranger)rr rrrrr_r!)rr%r rrr"rAs(       rccs dVdS)zSkip one event loop run cycle. This is a private helper for 'asyncio.sleep()', used when the 'delay' is set to 0. It uses a bare 'yield' expression (which Task.__step knows how to handle) instead of creating a Future object. Nr!r!r!r!r"__sleep0s rcsx|dkrtIdH|S|dur*t}ntjdtdd|}||tj ||}z|IdHW| S| 0dS)z9Coroutine that completes after a given time (in seconds).rNrr8r9) rrrr;r<r=rrrZ_set_result_unless_cancelledrm)delayrcr rhr!r!r"r s$   r cCst|r6|durt}||}|jr2|jd=|St|rb|dur^|t|ur^t d|St |r|t t ||dStddS)zmWrap a coroutine or an awaitable in a future. If the argument is a Future, it is returned directly. Nr@zRThe future belongs to a different loop than the one specified as the loop argumentrz:An asyncio.Future, a coroutine or an awaitable is required)rrFrr0rrErrr$rr}Z isawaitabler _wrap_awaitablerH)Zcoro_or_futurer r5r!r!r"r s    r ccs|EdHS)zHelper for asyncio.ensure_future(). Wraps awaitable (an object with __await__) into a coroutine that will later be wrapped in a Task by ensure_future(). N) __await__)Z awaitabler!r!r"rsrcs0eZdZdZddfdd ZdddZZS) _GatheringFuturezHelper for gather(). This overrides cancel() to cancel all the children and act more like Task.cancel(), which doesn't immediately mark itself as cancelled. Nrcstj|d||_d|_dS)NrF)rCrD _children_cancel_requested)rTchildrenr rVr!r"rDsz_GatheringFuture.__init__cCs:|r dSd}|jD]}|j|drd}q|r6d|_|S)NFrkT)r%rrmr)rTrlretchildr!r!r"rms  z_GatheringFuture.cancel)N)rrrrrDrmrr!r!rVr"rsrF)r return_exceptionscs|s<|durt}ntjdtdd|gSfdd}i}gdd|D]f}||vrt||d}|durt |}||urd |_ d 7|||<| |n||} |qdt |dS) a0Return a future aggregating results from the given coroutines/futures. Coroutines will be wrapped in a future and scheduled in the event loop. They will not necessarily be scheduled in the same order as passed in. All futures must share the same event loop. If all the tasks are done successfully, the returned future's result is the list of results (in the order of the original sequence, not necessarily the order of results arrival). If *return_exceptions* is True, exceptions in the tasks are treated the same as successful results, and gathered in the result list; otherwise, the first raised exception will be immediately propagated to the returned future. Cancellation: if the outer Future is cancelled, all children (that have not completed yet) are also cancelled. If any child is cancelled, this is treated as if it raised CancelledError -- the outer Future is *not* cancelled in this case. (This is to prevent the cancellation of one child to cause other children to be cancelled.) Nrr8r9csd7r$|s |dSsd|rF|}|dS|}|durd|dSkrg}D]J}|rt|jdurdn|j}n|}|dur|}| |qtj r|}|n  |dS)Nr) r%rrersrfrrrrnrcappendrrd)rr~resultsresrZ nfinishedZnfutsouterrr!r"_done_callbacks<    zgather.._done_callbackrrFr)rr0r;r<r=rrdr rr$rGr{rr)r rZcoros_or_futuresrZ arg_to_futargrr!rr"r s8  7     r cst|durtjdtddt||dr0St}|fddfdd }|S) a.Wait for a future, shielding it from cancellation. The statement res = await shield(something()) is exactly equivalent to the statement res = await something() *except* that if the coroutine containing it is cancelled, the task running in something() is not cancelled. From the POV of something(), the cancellation did not happen. But its caller is still cancelled, so the yield-from expression still raises CancelledError. Note: If something() is cancelled by other means this will still cancel shield(). If you want to completely ignore cancellation (not recommended) you can combine shield() with a try/except clause, as follows: try: res = await shield(something()) except CancelledError: res = None Nrr8r9rcs\r|s|dS|r.n*|}|durJ|n|dSr2)rrermrfrdrc)innerr~rr!r"_inner_done_callback~s  z$shield.._inner_done_callbackcssdSr2)r%rr)rrr!r"_outer_done_callbacksz$shield.._outer_done_callback) r;r<r=r r%rr$rr{)rr rr!)rrrr"r Ys     r cs:tstdtjfdd}|S)zsSubmit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result. zA coroutine object is requiredc slzttdWnNttfy0Yn8tyf}z rP|WYd}~n d}~00dS)Nr)rZ _chain_futurer rxrwryset_running_or_notify_cancelrf)r~rUrr r!r"callbacks z*run_coroutine_threadsafe..callback)rrFrH concurrentrFutureZcall_soon_threadsafe)rUr rr!rr"r s    r cCst|dS)z3Register a new task in asyncio as executed by loop.N)r+rr5r!r!r"rsrcCs4t|}|dur(td|d|d|t|<dS)NzCannot enter into task z while another task z is being executed.rrr,r r5rr!r!r"rs  rcCs2t|}||ur(td|d|dt|=dS)Nz Leaving task z! does not match the current task .rrr!r!r"rs  rcCst|dS)zUnregister a task.N)r+discardrr!r!r"rsr)rrrrr+r)N)N)N)N)Br__all__concurrent.futuresrrOrr} itertoolstypesr;weakrefrrrrrrrcount__next__rIrrr1r7Z _PyFuturerZ_PyTaskZ_asyncio ImportErrorZ_CTaskrrrrrrrrrr coroutinerr r rrrr r r WeakSetr+rrrrrZ_py_register_taskZ_py_unregister_taskZ_py_enter_taskZ_py_leave_taskZ_c_register_taskZ_c_unregister_taskZ _c_enter_taskZ _c_leave_taskr!r!r!r"s                )E,>  w?$