U if@svdZdZddlZddlZddlZddlZddlZddlZddl Z ddl Z ddl m Z ddl m Z ddl mZddl mZdd l mZdd l mZedjZdBd d ZdCd dZdDddZddZGdddejZeZz ddlZWnek rYn XejZZddddZejj 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|dkrt}t|S)z!Return a currently executed task.N)rget_running_loop_current_tasksgetloopr!2/opt/alt/python38/lib64/python3.8/asyncio/tasks.pyr"srcs^dkrtd}z tt}WqLtk rF|d7}|dkrBYqXqLqfdd|DS)z'Return a set of all tasks for the loop.Nrrcs&h|]}t|kr|s|qSr!)r _get_loopdone.0trr!r" <szall_tasks..)rrlist _all_tasks RuntimeErrorr iZtasksr!rr"r)s rcs^dkrtd}z tt}WqLtk rF|d7}|dkrBYqXqLqfdd|DS)Nrrr#csh|]}t|kr|qSr!)rr$r&rr!r"r)Usz$_all_tasks_compat..)rget_event_loopr*r+r,r-r!rr"_all_tasks_compat@s r0cCs4|dk r0z |j}Wntk r&Yn X||dSN)set_nameAttributeError)tasknamer2r!r!r"_set_task_nameXs  r6cseZdZdZdZed%ddZed&ddZdddfd d Zfd d Z d dZ ddZ ddZ ddZ ddZddZddddZdddddZdd Zd'fd!d" Zd#d$ZZS)(rz A coroutine wrapped in a Future.TNcCs(tjdtdd|dkr 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)warningswarnDeprecationWarningrr/rclsr 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() insteadr7r8)r:r;r<r0r=r!r!r"rs zTask.all_tasks)r r5cstj|d|jr|jd=t|s:d|_td||dkrRdt|_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 r5 __class__r!r"rCs   z Task.__init__csF|jtjkr8|jr8|dd}|jr,|j|d<|j|tdS)Nz%Task was destroyed but it is pending!)r4messageZsource_traceback) Z_staterZ_PENDINGrFrDrPZcall_exception_handlerrB__del__)rSrArUr!r"rXs  z Task.__del__cCs t|Sr1)rZ_task_repr_inforSr!r!r" _repr_infoszTask._repr_infocCs|jSr1)rMrYr!r!r"get_corosz Task.get_corocCs|jSr1)rIrYr!r!r"get_namesz Task.get_namecCst||_dSr1)rJrI)rSvaluer!r!r"r2sz Task.set_namecCs tddS)Nz*Task does not support set_result operationr,)rSresultr!r!r" set_resultszTask.set_resultcCs tddS)Nz-Task does not support set_exception operationr^)rS 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)rSrcr!r!r" get_stackszTask.get_stack)rcfilecCst|||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)rSrcrer!r!r" print_stacks zTask.print_stackcCs4d|_|rdS|jdk r*|jr*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). FNT)Z_log_tracebackr%rLcancelrKrYr!r!r"rgs  z Task.cancelc s|rtd|d||jr>t|tjs8t}d|_|j}d|_t|j |zfz"|dkrp| d}n | |}Wnt k r}z*|jrd|_tnt|jW5d}~XYntjk rtYnttfk r}zt|W5d}~XYntk rL}zt|W5d}~XYnpXt|dd}|dk r@t||j k rtd|d|d}|j j|j||jdn|r||krtd |}|j j|j||jdn8d|_|j|j|jd||_|jr>|jr>d|_n*td |d |}|j j|j||jdn||dkr`|j j|j|jdn\t !|rtd |d |}|j j|j||jdn$td |}|j j|j||jdW5t |j |d}XdS)Nz_step(): already done: z, F_asyncio_future_blockingzTask z got Future z attached to a different loopr@zTask 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%rZInvalidStateErrorrK isinstanceCancelledErrorrMrLrrPrsendthrow StopIterationrBrgr`r]KeyboardInterrupt SystemExitrb BaseExceptiongetattrrr$r,rQrRrOrhadd_done_callback _Task__wakeupinspectZ isgenerator)rSexcrTr_Zblockingnew_excrUr!r"Z__steps               z Task.__stepc CsJz |Wn,tk r8}z||W5d}~XYn X|d}dSr1)r_rprR)rSfuturerur!r!r"Z__wakeup[s  z Task.__wakeup)N)N)N)__name__ __module__ __qualname____doc__rF classmethodrrrCrXrZr[r\r2r`rbrdrfrgrRrs __classcell__r!r!rUr"rbs&     !Tr)r5cCs t}||}t|||S)z]Schedule the execution of a coroutine object in a spawn task. Return a Task object. )rrrr6)rTr5r r4r!r!r"rxs  r)r timeout return_whencst|st|r(tdt|j|s4td|tt t fkrPtd|dkrbt nt jdtddfdd t|D}t|||IdHS) 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: N[The loop argument is deprecated since Python 3.8, and scheduled for removal in Python 3.10.r7r8csh|]}t|dqSrr r'frr!r"r)szwait..)risfuturerrErGtyperx ValueErrorrrrrrr:r;r<set_wait)fsr r~rr!rr"rs rcGs|s|ddSr1)r%r`)waiterargsr!r!r"_release_waitersrrc s|dkrt}ntjdtdd|dkr4|IdHS|dkrt||d}|rX|St||dIdHz |Wn.t j k r}zt |W5d}~XYn Xt | }| |t|}tt|}t||d}||zz|IdHWnPt j k rF|r$|YWdS||t||dIdHYnX|r^|W*S||t||dIdHt W5|XdS)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. Nrr7r8rr)rrr:r;r<r r%r__cancel_and_waitrrj TimeoutError create_future call_laterr functoolspartialrrrgremove_done_callback)futr~r rurtimeout_handlecbr!r!r"rsL              rc s|s td|d|dk r.||tt|fdd}|D]}||qLzIdHW5dk r||D]}||qXtt}}|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|dk rVdk rDsVddS)Nrr)rr cancelledrargr%r`rZcounterrrrr!r"_on_completions z_wait.._on_completion) AssertionErrorrrrlenrrrgrrr%add)rr~rr rrr%Zpendingr!rr"rs*     rc sF|}tt|}||z||IdHW5||XdS)z.cs*D]}|dqdSr1)r put_nowaitclearr)rr%todor!r" _on_timeoutXs  z!as_completed.._on_timeoutcs4sdS||s0dk r0dSr1)removerrgr)r%rrr!r"r^s    z$as_completed.._on_completioncs$IdH}|dkrtj|Sr1)rrrr_r)r%r!r" _wait_for_onefsz#as_completed.._wait_for_one)rrrrErGrrxZqueuesrrr/r:r;r<rrrrranger)rr r~rrrr_r!)rr%r rrr"r7s*       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"__sleep0us rcsr|dkrtIdH|S|dkr*t}ntjdtdd|}||tj ||}z|IdHWS| XdS)z9Coroutine that completes after a given time (in seconds).rNrr7r8) rrrr:r;r<rrrZ_set_result_unless_cancelledrg)Zdelayr_r rwhr!r!r"r s$  r cCst|r6|dkrt}||}|jr2|jd=|St|rb|dk r^|t|k r^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)rrErr/rrDrrr$rrtZ isawaitabler _wrap_awaitablerG)Zcoro_or_futurer r4r!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"rsrcs.eZdZdZddfdd ZddZZS)_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)rBrC _children_cancel_requested)rSchildrenr rUr!r"rCsz_GatheringFuture.__init__cCs6|r dSd}|jD]}|rd}q|r2d|_|S)NFT)r%rrgr)rSZretZchildr!r!r"rgs z_GatheringFuture.cancel)rxryrzr{rCrgr}r!r!rUr"rsrF)r return_exceptionscs|s<|dkrt}ntjdtdd|gSfdd}i}gdd|D]f}||krt||d}|dkrt |}||k rd |_ d 7|||<| |n||} |qdt |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. Nrr7r8csd7r$|s |dSsd|rFt}|dS|}|dk rd|dSkrg}D]8}|rt}n|}|dkr|}||qtjrĈtn  |dS)Nr) r%rrarrjrbr_appendrr`)rruZresultsresrZ nfinishedZnfutsouterrr!r"_done_callbacks4    zgather.._done_callbackrrFr)rr/r:r;r<rr`r rr$rFrrrr)r rZcoros_or_futuresrZ arg_to_futargrr!rr"r s:  1     r cst|dk rtjdtddt||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 Nrr7r8rcs\r|s|dS|r.n*|}|dk rJ|n|dSr1)rrargrbr`r_)innerrurr!r"_inner_done_callbackus  z$shield.._inner_done_callbackcssdSr1)r%rr)rrr!r"_outer_done_callbacksz$shield.._outer_done_callback) r:r;r<r r%rr$rrr)rr rr!)rrrr"r Ps     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 slzttdWnNttfk r2Yn6tk rf}zrT|W5d}~XYnXdS)Nr)rZ _chain_futurer rornrpZset_running_or_notify_cancelrb)rurTrwr r!r"callbacks z*run_coroutine_threadsafe..callback)rrErG concurrentrFutureZcall_soon_threadsafe)rTr rr!rr"r s    r cCst|dS)z3Register a new task in asyncio as executed by loop.N)r+rr4r!r!r"rsrcCs4t|}|dk r(td|d|d|t|<dS)NzCannot enter into task z while another task z is being executed.rrr,r r4rr!r!r"rs rcCs2t|}||k r(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__Zconcurrent.futuresrrNrrt itertoolstypesr:weakrefrrrrrrcount__next__rHrrr0r6Z _PyFuturerZ_PyTaskZ_asyncio ImportErrorZ_CTaskrrrrrrrrrr coroutinerr r rrrr 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                #H,>  x?$