o ?Og~@sldZdZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddlm Z ddl m Z ddl mZddl mZdd l mZdd l mZdd lmZedjZdCd d ZdCddZddZGdddejZeZzddlZWn ey|YnwejZZddddZejj Z ejj!Z!ejj"Z"de"dddZ#ddZ$ddZ%ddZ&d d!Z'dd"d#d$Z(ej)d%d&Z*dCd'd(Z+dd)d*d+Z,dd)d,d-Z-ej)d.d/Z.ee._Gd0d1d1ej/Z0d2d3d4d5Z1d6d7Z2d8d9Z3e 4Z5iZ6d:d;Z7dd?Z9d@dAZ:e7Z;e:ZzddBlm7Z7m:Z:m8Z8m9Z9m5Z5m6Z6Wn ey+YdSwe7Z?e:Z@e8ZAe9ZBdS)Dz0Support 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) GenericAlias) base_tasks) coroutines)events) exceptions)futures) _is_coroutinecCs|durt}t|S)z!Return a currently executed task.N)rget_running_loop_current_tasksgetloopr"4/opt/alt/python310/lib64/python3.10/asyncio/tasks.pyr#s rcs^durtd} ztt}Wnty#|d7}|dkr!Ynwnq fdd|DS)z'Return a set of all tasks for the loop.NrTrics&h|]}t|ur|s|qSr")r _get_loopdone).0tr r"r# =szall_tasks..)rrlist _all_tasks RuntimeError)r!iZtasksr"r r#r*s   rcCs8|durz|j}Wn tyYdSw||dSdSN)set_nameAttributeError)tasknamer.r"r"r#_set_task_nameAs   r2cseZdZdZdZdddfdd ZfddZeeZ d d Z d d Z d dZ ddZ ddZddZddddZdddddZd!ddZd!fdd Zdd ZZS)"rz A coroutine wrapped in a Future.TN)r!r1cstj|d|jr|jd=t|sd|_td||dur)dt|_nt ||_d|_ d|_ ||_ t |_|jj|j|jdt|dS)Nr Fza 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!r1 __class__r"r#r7]s    z Task.__init__csF|jtjkr|jr|dd}|jr|j|d<|j|tdS)Nz%Task was destroyed but it is pending!)r0messageZsource_traceback) Z_staterZ_PENDINGr:r8rDZcall_exception_handlerr6__del__)rGr5rIr"r#rLts  z Task.__del__cCs t|Sr-)rZ_task_repr_inforGr"r"r# _repr_infos zTask._repr_infocC|jSr-)rArMr"r"r#get_coroz Task.get_corocCrOr-)r=rMr"r"r#get_namerQz Task.get_namecCst||_dSr-)r>r=)rGvaluer"r"r#r.sz Task.set_namecCtd)Nz*Task does not support set_result operationr+)rGresultr"r"r# set_resultzTask.set_resultcCrT)Nz-Task does not support set_exception operationrU)rG exceptionr"r"r# set_exceptionrXzTask.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)rGr[r"r"r# get_stacks zTask.get_stack)r[filecCst|||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)rGr[r]r"r"r# print_stacks zTask.print_stackcCs>d|_|r dS|jdur|jj|drdSd|_||_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%r@cancelr?_cancel_message)rGr`r"r"r#ras z Task.cancelc s|rtd|d||jrt|tjs|}d|_|j}d|_t |j |zz|dur8| d}n| |}Wnnt yg}z|jrUd|_tj|jdnt|jWYd}~n d}~wtjy}z||_tWYd}~nd}~wttfy}zt|d}~wty}z t|WYd}~nd}~wwt|dd}|dur't||j urtd|d|d}|j j|j||jd n|r||urtd |}|j j|j||jd nd|_|j |j!|jd ||_|jr|jj|jdrd|_ntd |d |}|j j|j||jd nj|dur7|j j|j|jd nt"#|rStd |d |}|j j|j||jd nutd|}|j j|j||jd Wt$|j |d}dSWt$|j |d}dSWt$|j |d}dSWt$|j |d}dSWt$|j |d}dSWt$|j |d}dSWt$|j |d}dSWt$|j |d}dSWt$|j |d}dSWt$|j |d}dSt$|j |d}w)Nz_step(): already done: z, Fr__asyncio_future_blockingzTask z got Future z attached to a different loopr4zTask 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%rZInvalidStateErrorr? isinstanceCancelledError_make_cancelled_errorrAr@rrDsendthrow StopIterationr6rarbrWrSZ_cancelled_excKeyboardInterrupt SystemExitrZ BaseExceptiongetattrrr$r+rErFrCrcadd_done_callback _Task__wakeupinspectZ isgeneratorr)rGexcrHrVZblockingnew_excrIr"r#Z__steps                 6 1  (  "   z Task.__stepc CsRz|Wnty }z||WYd}~d}dSd}~ww|d}dSr-)rVrlrF)rGfuturerqr"r"r#Z__wakeup.s   z Task.__wakeupr-)__name__ __module__ __qualname____doc__r:r7rL classmethodr__class_getitem__rNrPrRr.rWrZr\r^rarFro __classcell__r"r"rIr#rKs"    "Wr)r1cCs t}||}t|||S)z]Schedule the execution of a coroutine object in a spawn task. Return a Task object. )rrrr2)rHr1r!r0r"r"r#rKs  r)timeout return_whencst|s t|rtdt|j|std|tt t fvr)td|t t |}tdd|DrBtjdtddfd d |D}t|||Id HS) aWait for the Futures and coroutines given by fs to complete. The fs iterable 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. zexpect a list of futures, not z#Set of coroutines/Futures is empty.zInvalid return_when value: css|]}t|VqdSr-)rr9r&fr"r"r# xszwait..zThe explicit passing of coroutine objects to asyncio.wait() is deprecated since Python 3.8, and scheduled for removal in Python 3.11. stacklevelch|]}t|dqSr r r}r r"r#r(~zwait..N)risfuturerr9r;typert ValueErrorrrrrrsetanywarningswarnDeprecationWarning_wait)fsr{r|r"r r#r]srcGs|s |ddSdSr-)r%rW)waiterargsr"r"r#_release_waiterrc st}|dur|IdHS|dkrAt||d}|r |St||dIdHz|WStjy@}zt|d}~ww| }| |t |}t t |}t||d}||zfz|IdHWn&tjy|r||YW|S||t||dIdHw|r|W|S||t||dIdHz |WW|Stjy}zt|d}~ww|w)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. Nrr )rrr r%rV_cancel_and_waitrre TimeoutError create_future call_laterr functoolspartialrnraremove_done_callback)futr{r!rqrtimeout_handlecbr"r"r#rsX                  rc s|d|dur||tt|fdd}|D]}||q!zIdHWdur8|D]}||q:ndurK|D]}||qMwtt}}|D]}|rk| |q_| |q_||fS)zVInternal helper for wait(). The fs argument must be a collection of Futures. Ncsjd8dkstkstkr-|s/|dur1dur"s3ddSdSdSdSdS)Nrr)rr cancelledrYrar%rWr~Zcounterr|rrr"r#_on_completions z_wait.._on_completion) rrrlenrnrarrr%add)rr{r|r!rr~r%Zpendingr"rr#rs6      rc sP|}tt|}||z||IdHW||dS||w)z.Ncs*D] }|dqdSr-)r put_nowaitclearr)rr%todor"r# _on_timeout(s   z!as_completed.._on_timeoutcs<sdS||sdurdSdSdSr-)removerrar)r%rrr"r#r.s    z$as_completed.._on_completioncs&IdH}|durtj|Sr-)rrrrVr)r%r"r# _wait_for_one6s z#as_completed.._wait_for_one)rrrr9r;rrtZqueuesrr_get_event_looprrnrranger)rr{rrrr~_r")rr%r!rrr#r s$      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#__sleep0Es rcs\|dkr tIdH|St}|}||tj||}z |IdHW|S|w)z9Coroutine that completes after a given time (in seconds).rN)rrrrrrZ_set_result_unless_cancelledra)ZdelayrVr!rshr"r"r#r Qs  r r cCs t||dS)zmWrap a coroutine or an awaitable in a future. If the argument is a Future, it is returned directly. r )_ensure_future)coro_or_futurer!r"r"r#r bs r cCst|r|dur|t|urtd|Sd}t|s-t|r)t|}d}nt d|dur7t j dd}z| |WSt yK|sJ|w)NzRThe future belongs to a different loop than the one specified as the loop argumentFTz:An asyncio.Future, a coroutine or an awaitable is requiredr)rrr$rrr9rpZ isawaitable_wrap_awaitabler;rrrr+close)rr!Zcalled_wrap_awaitabler"r"r#rjs&      rccs|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#rsrcs*eZdZdZfddZdddZZS)_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. cstj|d||_d|_dS)Nr F)r6r7 _children_cancel_requested)rGchildrenr!rIr"r#r7s z_GatheringFuture.__init__NcCs:|rdSd}|jD] }|j|drd}q |rd|_|S)NFr_T)r%rrar)rGr`Zretchildr"r"r#ras  z_GatheringFuture.cancelr-)rtrurvrwr7rarzr"r"rIr#rs rF)return_exceptionscs|st}|gSfdd}i}gddd}d|D]3}||vrSt||d}|dur>t|}||urEd|_d7|||<||n||} |q)t |dS)aReturn 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.) If *return_exceptions* is False, cancelling gather() after it has been marked done won't cancel any submitted awaitables. For instance, gather can be marked done after propagating an exception to the caller, therefore, calling ``gather.cancel()`` after catching an exception (raised by one of the awaitables) from gather won't cancel any other awaitables. csd7dus r|s|dSs6|r'|}|dS|}|dur6|dSkryg}D]%}|rRt|jdurMdn|j}n |}|dur^|}| |q>j rr|}|dS |dSdS)Nr) r%rrYrfrZrrerbrVappendrrW)rrqZresultsresrZ nfinishedZnfutsouterrr"r#_done_callbacks>   zgather.._done_callbackrNr Fr) rrrrWrrr$r:rnrr)rZcoros_or_futuresr!rZ arg_to_futargrr"rr#r s4 7     r csXt|r St}|fddfdd}|S)aWait for a future, shielding it from cancellation. The statement task = asyncio.create_task(something()) res = await shield(task) 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: task = asyncio.create_task(something()) try: res = await shield(task) except CancelledError: res = None Save a reference to tasks passed to this function, to avoid a task disappearing mid-execution. The event loop only keeps weak references to tasks. A task that isn't referenced elsewhere may get garbage collected at any time, even before it's done. cs`r|s |dS|rdS|}|dur'|dS|dSr-)rrYrarZrWrV)innerrqrr"r#_inner_done_callbackOs z$shield.._inner_done_callbackcss dSdSr-)r%rr)rrr"r#_outer_done_callback`rz$shield.._outer_done_callback)rr%rr$rrn)rr!rr")rrrr#r 's!    r cs:ts tdtjfdd}|S)zsSubmit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result. zA coroutine object is requiredc sZz ttdWdSttfyty,}z r'|d}~ww)Nr )rZ _chain_futurer rkrjrlZset_running_or_notify_cancelrZ)rqrHrsr!r"r#callbackrs z*run_coroutine_threadsafe..callback)rr9r; concurrentrFutureZcall_soon_threadsafe)rHr!rr"rr#r is   r cCt|dS)z3Register a new task in asyncio as executed by loop.N)r*rr0r"r"r#rrcCs4t|}|durtd|d|d|t|<dS)NzCannot enter into task z while another task z is being executed.rrr+r!r0rr"r"r#rs   rcCs2t|}||urtd|d|dt|=dS)Nz Leaving task z! does not match the current task .rrr"r"r#rs   rcCr)zUnregister a task.N)r*discardrr"r"r#rrr)rrrrr*rr-)Crw__all__Zconcurrent.futuresrrBrrp itertoolstypesrweakrefrrrrrrrrcount__next__r<rrr2Z _PyFuturerZ_PyTaskZ_asyncio ImportErrorZ_CTaskrrrrrrrrrr coroutinerr r rrrrr r r ZWeakSetr*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            u    &G,9   {B$