\d dZdZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddlm Z ddl m Z ddl mZddl mZdd l mZdd l mZdd lmZejdjZd-d Zd-d ZdZGddejZeZ ddlZejxZZn #e$rYnwxYwddddZejj Z ejj!Z!ejj"Z"de"ddZ#dZ$dZ%dZ&dZ'dddZ(ej)dZ*d-dZ+dddZ,dddZ-ej)d Z.ee._Gd!d"ej/Z0d#d$d%Z1d&Z2d'Z3e j4Z5iZ6d(Z7d)Z8d*Z9d+Z:e7Z;e:Z dd,lm7Z7m:Z:m8Z8m9Z9m5Z5m6Z6e7Z?e:Z@e8ZAe9ZBdS#e$rYdSwxYw).z0Support 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_coroutinecT|tj}tj|S)z!Return a currently executed task.)rget_running_loop_current_tasksgetloops ..\python\lib\asyncio\tasks.pyrr#s& |&((  d # ##ctjd} tt}n#t$r|dz }|dkrYnwxYw3fd|DS)z'Return a set of all tasks for the loop.NrTrichh|].}tj|u|,|/S)r _get_loopdone).0tr#s r$ zall_tasks..=sE > > >! ##t++AFFHH+ +++r%)rrlist _all_tasks RuntimeError)r#itaskss` r$rr*s |&(( A $$E      FADyyy  > > > >u > > >>s0A A c|B |j}||dS#t$r tjdtdYdSwxYwdS)Nz~Task.set_name() was added in Python 3.8, the method support will be mandatory for third-party task implementations since 3.13. stacklevel)set_nameAttributeErrorwarningswarnDeprecationWarning)tasknamer7s r$_set_task_namer>As  }H HTNNNNN  8 8 8 M9)Q 8 8 8 8 8 8 8 8s&AAceZdZdZdZddddfd ZfdZeeZ dZ dZ d Z d Z d Zd Zdd dZddddZddZdZdZdfd ZdZxZS)rz A coroutine wrapped in a Future.TN)r#r=contextct||jr|jd=tj|sd|_t d||dt|_nt||_d|_ d|_ d|_ ||_ |tj|_n||_|j|j|jt)|dS)Nr"Fza coroutine was expected, got zTask-rr@)super__init___source_tracebackr iscoroutine_log_destroy_pending TypeError_task_name_counter_namestr_num_cancels_requested _must_cancel _fut_waiter_coro contextvars copy_context_context_loop call_soon _Task__stepr)selfcoror#r=r@ __class__s r$rEz Task.__init__`s d###  ! +&r*%d++ G).D %ETEEFF F <7!3!5!577DJJTDJ&'#! ?'466DMM#DM T[$-@@@tr%c|jtjkr7|jr0|dd}|jr |j|d<|j|tdS)Nz%Task was destroyed but it is pending!)r<messagesource_traceback) _stater_PENDINGrHrFrTcall_exception_handlerrD__del__)rWr@rYs r$r`z Task.__del__{sy ;'* * *t/H *BG% E.2.D*+ J - -g 6 6 6 r%c*tj|SN)r _task_reprrWs r$__repr__z Task.__repr__s$T***r%c|jSrb)rPrds r$get_coroz Task.get_coro zr%c|jSrb)rKrds r$get_namez Task.get_namerhr%c.t||_dSrb)rLrK)rWvalues r$r7z Task.set_namesZZ r%c td)Nz*Task does not support set_result operationr0)rWresults r$ set_resultzTask.set_resultsGHHHr%c td)Nz-Task does not support set_exception operationrn)rW exceptions r$ set_exceptionzTask.set_exceptionsJKKKr%)limitc,tj||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. )r_task_get_stack)rWrts r$ get_stackzTask.get_stacks*)$666r%)rtfilec.tj|||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. )r_task_print_stack)rWrtrxs r$ print_stackzTask.print_stacks+D%>>>r%cd|_|rdS|xjdz c_|j|j|rdSd|_||_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). This also increases the task's count of cancellation requests. FrNmsgT)_log_tracebackr*rMrOcancelrN_cancel_message)rWr~s r$rz Task.cancelsx,$ 99;; 5 ##q(##   '&&3&// t "tr%c|jS)zReturn the count of the task's cancellation requests. This count is incremented when .cancel() is called and may be decremented using .uncancel(). rMrds r$ cancellingzTask.cancellings **r%cF|jdkr|xjdzc_|jS)zDecrement the task's count of cancellation requests. This should be called by the party that called `cancel()` on the task beforehand. Returns the remaining number of cancellation requests. rrrrds r$uncancelz Task.uncancels/  & * *  ' '1 , ' '**r%c|rtjd|d||jr5t |tjs|}d|_|j}d|_t|j | || d}n| |}t|dd}|8tj||j ur?t!d|d|d}|j |j||jn|r||ur;t!d |}|j |j||jnnd|_||j|j||_|jr'|j|j rd|_nt!d |d |}|j |j||jn|(|j |j|jnt3j|r>t!d |d |}|j |j||jnUt!d|}|j |j||jn#t6$rf}|jr/d|_t9|j n&t9|jYd}~nd}~wtj$r1}||_t9Yd}~nqd}~wt@tBf$r'}t9"|d}~wtF$r+}t9"|Yd}~nd}~wwxYwtI|j |d}dS#tI|j |d}wxYw)Nz_step(): already done: z, F_asyncio_future_blockingzTask z got Future z attached to a different looprCzTask cannot await on itself: r}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*rInvalidStateErrorrN isinstanceCancelledError_make_cancelled_errorrPrOrrTsendthrowgetattrrr)r0rUrVrSradd_done_callback _Task__wakeuprrinspect isgenerator StopIterationrDrprl_cancelled_excKeyboardInterrupt SystemExitrs BaseExceptionr)rWexcrXroblockingnew_excrYs r$__stepz Task.__steps 99;; =.;$;;C;;== =   &c:#<== 30022 %D zDJ%%%H {4C$v'A4HHH#$V,,DJ>>*CCC!CCCDDGJ(( Wdm)EEEEE~~".DDDD#F#F ,, K$--IIII;@700 M4=1BBB+1(,:#/66(,(< 7 > >:49 1*<#'<<17<<==GJ(( Wdm)EEEE $$T[$-$HHHH$V,, A&B)-BB7=BBCC $$K$-%AAAA''Hf'H'HII $$K$-%AAAA{ . . .  .$)!4#78888""39---(   "%D  GGNN        !:.    GG ! !# & & &  ' ' ' GG ! !# & & & & & & & & 'd  D ) ) )DDD  D ) ) )DKKKKsb-K=HO3 O AL+&O3+O='M)$O3)O="N O,!O O3OO33P c ||n,#t$r}||Yd}~nd}~wwxYwd}dSrb)rorVr)rWfuturers r$__wakeupz Task.__wakeupQsr  MMOOO KKMMMM    KK         s+ AAArb)__name__ __module__ __qualname____doc__rHrEr` classmethodr__class_getitem__rergrjr7rprsrwr{rrrrVr __classcell__rYs@r$rrNs+* %)d6     $ L11+++   IIILLL"&77777.$(d ? ? ? ? ?((((T+++ + + +UUUUUUnr%r)r=r@ctj}|||}n|||}t|||S)z]Schedule the execution of a coroutine object in a spawn task. Return a Task object. NrC)rrrr>)rXr=r@r#r<s r$rrnsY  " $ $D%%g664 Kr%)timeout return_whencKtj|stj|r$t dt |j|std|tttfvrtd|t|}td|Drt dtj}t||||d{VS)a}Wait for the Futures or Tasks 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 zSet of Tasks/Futures is empty.zInvalid return_when value: c3>K|]}tj|VdSrb)rrG)r+fs r$ zwait..s- 1 1: !! $ $ 1 1 1 1 1 1r%z6Passing coroutines is forbidden, use tasks explicitly.N)risfuturerrGrItyper ValueErrorrrrsetanyrr_wait)fsrrr#s r$rrs Nz5b99NLb9JLLMMM ;9:::?O]KKKD{DDEEE RB 1 1b 1 1 111RPQQQ  " $ $Dr7K66 6 6 6 6 6 66r%c\|s|ddSdSrb)r*rp)waiterargss r$_release_waiterrs6 ;;== $  r%cKtj}||d{VS|dkrt||}|r|St ||d{V |S#t j$r}t j|d}~wwxYw| }| |t|}tj t|}t||}|| |d{Vn~#t j$rl|r*|cY|S||t ||d{VwxYw|r(||S||t ||d{V ||S#t j$r}t j|d}~wwxYw#|wxYw)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*ro_cancel_and_waitrr TimeoutError create_future call_laterr functoolspartialrrremove_done_callback)futrr#rrtimeout_handlecbs r$rrs  " $ $Dyyyyyy!||Cd+++ 88:: ::<< s.......... 5::<< ( 5 5 5)++ 4 5   ! !F__WovFFN  ?F 3 3B $ ' ' 'C"  LLLLLLLL(   xxzz zz||##2 /((,,,'s6666666666  88:: 9::<<   $ $R ( ( (#3T222 2 2 2 2 2 2 2 9zz|| , 9 9 9 -//S8 9 sf7B B3B..B3(D10I+17F,(I+>.F,,*I++,I+II(I##I((I++Jc K|s Jd| d |||t  t| fd}|D]}|| d{V  |D]}||n5#  |D]}||wxYwtt}}|D]A}|r| |,| |B||fS)zVInternal helper for wait(). The fs argument must be a collection of Futures. zSet of Futures is empty.Nc(dzdks>tks3tkri|sW|EsddSdSdSdSdS)Nrr)rr cancelledrrrr*rp)rcounterrrrs r$_on_completionz_wait.._on_completions1  qLL ? * * ? * *AKKMM *01 0I)%%''';;== (!!$''''' + * * *0I0I ( (r%) rrrlenrrrrr*add) rrrr#rrr*pendingrrrs ` @@@r$rrs ))))))    ! !FN/6JJ"ggG ( ( ( ( ( ( ( (,, N++++3  %  ! ! # # # 3 3A " "> 2 2 2 2 3  %  ! ! # # # 3 3A " "> 2 2 2 2 3EE355'D  6688  HHQKKKK KKNNNN =s 9B222C$c(K|}tjt|}|| ||d{V||dS#||wxYw)z.Gs& 9 9 9AM!$ ' ' ' 9 9 9r%NcD],}|d-dSrb)r put_nowaitclear)rrr*todos r$ _on_timeoutz!as_completed.._on_timeoutJsL " "A " "> 2 2 2 OOD ! ! ! ! r%csdS||sdSdSdSrb)removerr)rr*rrs r$rz$as_completed.._on_completionPsf  F A  $2  ! ! # # # # # $ $22r%cKd{V}| tj|Srb)r!rrro)rr*s r$ _wait_for_onez#as_completed.._wait_for_oneXsB((**       9) )xxzzr%)rrrrGrIrrqueuesrr_get_event_looprrrranger) rrrrrr_rr*r#rrs @@@@@r$r r .s$Sz5b99SQd2hh>OQQRRR 577D  ! # #D 9 9 9 9R 9 9 9DN $$$$$$$,, N++++ ?#+>> 3t99  moor%c#KdVdS)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$__sleep0rgs EEEEEr%c>K|dkrtd{V|Stj}|}||t j||} |d{V |S#|wxYw)z9Coroutine that completes after a given time (in seconds).rN)rrrrrr_set_result_unless_cancelledr)delayror#rhs r$r r ss zzjj  " $ $D    ! !F < ( (A||||||   s )BBr"c$t||S)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#s r$r r s .t 4 4 44r%ctj|r)|%|tj|urtd|Sd}t j|s5t j|rt|}d}ntd|tj d} | |S#t$r|s|wxYw)NzRThe future belongs to a different loop than the one specified as the loop argumentFTz:An asyncio.Future, a coroutine or an awaitable is requiredr5)rrr)rrrGr isawaitable_wrap_awaitablerIrrrr0close)rr#called_wrap_awaitables r$rrs''  G,=n,M,M M MEFF F!  !. 1 1+  ~ . . +,^<tj}| g S fd}i}gd dd}d |D]u}||vrRt ||}|t j|}||urd|_ dz |||<||n||} |vt| S)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. cdz r*|s|dSsl|r+|}|dS|}||dSkrg}D]x}|r#t j|jdn|j}n*|}||}| |yj r+|}|dS |dSdS)Nr) r*rrrrrsrrrroappendrrp) rrresultsresr nfinishednfutsouterrs r$_done_callbackzgather.._done_callbacksQ =EJJLL===??   F }} //11##C(((mmoo?'',,,F   G $ $==?? +%3!19+--CC--//C{!jjlls####& *//11##C(((((  )))));  r%rNr"Fr) rrrrprrr)rHrrr) rcoros_or_futuresr#r arg_to_futargrrrrrs ` @@@@r$r r sK< %''""$$  5*5*5*5*5*5*5*5*5*nJH EI D E j  4000C|(--#~~ ,1( QJE!JsO  ! !. 1 1 1 1S/C XD 1 1 1E Lr%ct|rStj}|fdfd}|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. cr*|s|dS|rdS|}||dS|dSrb)rrrrrsrpro)innerrrs r$_inner_done_callbackz$shield.._inner_done_callbackqs ??   ??$$ "!!! F ??   1 LLNNNNN//##C##C(((((  00000r%c^sdSdSrb)r*r)rr r s r$_outer_done_callbackz$shield.._outer_done_callbacks8zz|| =  & &'; < < < < < = =r%)rr*rr)rr)rr#r r r rs @@@r$r r IsB 3  E zz||  U # #D    E11111"====== 0111 0111 Lr%ctjstdtjfd}|S)zsSubmit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result. zA coroutine object is requiredc tjtdS#ttf$rt $r/}r|d}~wwxYw)Nr")r _chain_futurer rrrset_running_or_notify_cancelrs)rrXrr#s r$callbackz*run_coroutine_threadsafe..callbacks   !-4"@"@"@& I I I I I-.       2244 *$$S)))  s$)A3*A..A3)rrGrI concurrentrFuturecall_soon_threadsafe)rXr#rrs`` @r$rrs{  !$ ' ':8999   & & ( (F h''' Mr%c.tj|dS)z3Register a new task in asyncio as executed by loop.N)r/rr<s r$rrsN4r%crtj|}|td|d|d|t|<dS)NzCannot enter into task z while another task z is being executed.r r!r0r#r<rs r$rrsf!%d++LGTGG#/GGGHH HN4r%crtj|}||urtd|d|dt|=dS)Nz Leaving task z! does not match the current task .rrs r$rrsi!%d++L4A4AA/;AAABB Btr%c.tj|dS)zUnregister a task.N)r/discardrs r$rrstr%)rrrrr/r rb)Cr__all__concurrent.futuresrrQrr itertoolstypesr9weakrefrrrrrrrrcount__next__rJrrr> _PyFuturer_PyTask_asyncio_CTask ImportErrorrrrrrrrrrr coroutinerr r rrrrr r rWeakSetr/r rrrr_py_register_task_py_unregister_task_py_enter_task_py_leave_task_c_register_task_c_unregister_task _c_enter_task _c_leave_taskr(r%r$r4sy66  %%%%%% %Y_Q''0$$$$>>>>.   QQQQQ7 QQQh "OOO M!D66    D #D     $$4$4"0 # 77777@   D D D N)))X % % %"!%66666r   "+/55555,02...!.w~:16xxxxxv???D0W_        #&  6666666666666666 &)MMMM    DD s$BBBE88FF