B §@s@dZdZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddl m Z ddl mZdd l mZd>d d Zd?d d Zd@ddZGdddejZeZy ddlZWnek rYn XejZZddZejjZejjZejjZddedddZddZddddZddZ ddZ!ddd d!d"Z"ejd#d$Z#dAddd%d&Z$ddd'd(Z%ed)d*Z&Gd+d,d,ej'Z(dd-d.d/d0Z)ddd1d2Z*d3d4Z+e ,Z-iZ.d5d6Z/d7d8Z0d9d:Z1d;d<Z2e/Z3e2Z4e0Z5e1Z6y$dd=lm/Z/m2Z2m0Z0m1Z1m-Z-m.Z.Wnek r*YnXe/Z7e2Z8e0Z9e1Z:dS)Bz0Support 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)futures) coroutinecCs|dkrt}t|S)z!Return a currently executed task.N)rget_running_loop_current_tasksget)loopr2/opt/alt/python37/lib64/python3.7/asyncio/tasks.pyrsrcsbdkrtd}x:y tt}Wn&tk rH|d7}|dkrDYqXPqWfdd|DS)z'Return a set of all tasks for the loop.Nrrics&h|]}t|kr|s|qSr)r _get_loopdone).0t)rrr 5szall_tasks..)rrlist _all_tasks RuntimeError)ritasksr)rr r"s rcsbdkrtd}x:y tt}Wn&tk rH|d7}|dkrDYqXPqWfdd|DS)Nrricsh|]}t|kr|qSr)rr!)r#r$)rrr r%Nsz$_all_tasks_compat..)rget_event_loopr&r'r()rr)r*r)rr _all_tasks_compat9s r,cseZdZdZdZedddZed ddZddfd d Zfd d Z d dZ ddZ ddZ ddddZ dddddZddZd!fdd ZddZZS)"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. zETask.current_task() is deprecated, use asyncio.current_task() instead) stacklevelN)warningswarnPendingDeprecationWarningrr+r)clsrrrr rcs zTask.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. z?Task.all_tasks() is deprecated, use asyncio.all_tasks() insteadr-)r.)r/r0r1r,)r2rrrr rsszTask.all_tasks)rcsvtj|d|jr|jd=t|s:d|_td|d|_d|_||_ t |_ |j j|j|j dt|dS)N)rFza coroutine was expected, got )context)super__init___source_tracebackr iscoroutine_log_destroy_pending TypeError _must_cancel _fut_waiter_coro contextvarsZ copy_context_context_loop call_soon _Task__stepr)selfcoror) __class__rr r6s  z Task.__init__csF|jtjkr8|jr8|dd}|jr,|j|d<|j|tdS)Nz%Task was destroyed but it is pending!)taskmessageZsource_traceback) Z_staterZ_PENDINGr9r7r@Zcall_exception_handlerr5__del__)rCr4)rErr rHs  z Task.__del__cCs t|S)N)rZ_task_repr_info)rCrrr _repr_infoszTask._repr_infocCs tddS)Nz*Task does not support set_result operation)r()rCresultrrr set_resultszTask.set_resultcCs tddS)Nz-Task does not support set_exception operation)r()rC exceptionrrr 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)rCrNrrr get_stackszTask.get_stack)rNfilecCst|||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)rCrNrPrrr 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"r<cancelr;)rCrrr rRs  z Task.cancelc s|rtd|d||jr>t|tjs8t}d|_|j}d|_t|j |zhy"|dkrp| d}n | |}Wnt k r}z0|jrd|_t tnt |jWdd}~XYntjk rt Yntk r}zt |Wdd}~XYntk rN}zt |Wdd}~XYnpXt|dd}|dk rBt||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||dkrb|j j|j|jdn\t|rtd |d |}|j j|j||jdn$td |}|j j|j||jdWdt|j |d}XdS)Nz_step(): already done: z, F_asyncio_future_blockingzTask z got Future z attached to a different loop)r4zTask 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; isinstanceCancelledErrorr=r<rr@sendthrow StopIterationr5rMrKvaluerR Exception BaseExceptiongetattrr!r(rArBr?rSadd_done_callback _Task__wakeupinspectZ isgeneratorr)rCexcrDrJZblockingnew_exc)rErr Z__steps|             z Task.__stepc CsJy |Wn,tk r8}z||Wdd}~XYn X|d}dS)N)rJrZrB)rCfuturer`rrr Z__wakeup<s  z Task.__wakeup)N)N)N)__name__ __module__ __qualname____doc__r9 classmethodrrr6rHrIrKrMrOrQrRrBr^ __classcell__rr)rEr rQs      !TrcCst}||S)z]Schedule the execution of a coroutine object in a spawn task. Return a Task object. )rrr)rDrrrr rYsr)rtimeout return_whencst|st|r(tdt|j|s4td|tt t fkrPtd|dkr`t fddt |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. zexpect a list of futures, not z#Set of coroutines/Futures is empty.zInvalid return_when value: Ncsh|]}t|dqS))r)r )r#f)rrr r%szwait..)risfuturerr8r:typerc ValueErrorrrrrr+set_wait)fsrrirjr)rr risrcGs|s|ddS)N)r"rK)waiterargsrrr _release_waitersrt)rcs|dkrt}|dkr"|IdHS|dkrVt||d}|rF|S|t|}| |t |}t t |}t||d}| |zry|IdHWn*tjk r|||YnX|r|S||t||dIdHtWd|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. Nr)r)rr+r r"rJrRr TimeoutError create_future call_laterrt functoolspartialr]rUremove_done_callback_cancel_and_wait)futrirrrtimeout_handlecbrrr rs8         rc s|s td|d|dk r.||tt|fdd}x|D]}||qNWzIdHWddk rx|D]}||qWXtt}}x*|D]"}| r| |q| |qW||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 cancelledrLrRr"rK)rk)counterrjr}rrrr _on_completions z_wait.._on_completion) AssertionErrorrvrwrtlenr]rRrzror"add)rqrirjrrrkr"Zpendingr)rrjr}rrr rps*     rpc sF|}tt|}||z||IdHWd||XdS)z.r)Queue)rcs.x D]}|dqWdS)N)rz put_nowaitclear)rk)rr"todorr _on_timeouts  z!as_completed.._on_timeoutcs4sdS||s0dk r0dS)N)removerrR)rk)r"r}rrr r#s    z$as_completed.._on_completioncs$IdH}|dkrtj|S)N)rrrurJ)rk)r"rr _wait_for_one+sz#as_completed.._wait_for_one)rrlrr8r:rmrcrr+roZqueuesrr]rwranger)rqrrirrrrk_r)rr"rr}rr rs       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. Nrrrrr __sleep0:s rcs\|dkrtIdH|S|dkr(t}|}||tj||}z |IdHS|XdS)z9Coroutine that completes after a given time (in seconds).rN)rrr+rvrwrZ_set_result_unless_cancelledrR)ZdelayrJrrbhrrr r Fs  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. Nr3z$loop argument must agree with Future)rz:An asyncio.Future, a coroutine or an awaitable is required)rr8rr+rr7rrlr!rnr_Z isawaitabler _wrap_awaitabler:)Zcoro_or_futurerrFrrr r Xs    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 awaitablerrr rosrcs.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. N)rcstj|d||_d|_dS)N)rF)r5r6 _children_cancel_requested)rCchildrenr)rErr r6sz_GatheringFuture.__init__cCs:|r dSd}x|jD]}|rd}qW|r6d|_|S)NFT)r"rrRr)rCZretZchildrrr rRs z_GatheringFuture.cancel)rcrdrerfr6rRrhrr)rEr rysrF)rreturn_exceptionscs|s*|dkrt}|gSfdd}i}gddxn|D]f}||krt||d}|dkr~t|}||k rd|_d7|||<||n||} |qTWt |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.) Ncsd7r$|s |dSsd|rFt}|dS|}|dk rd|dSkrg}x@D]8}|rt}n|}|dkr|}||qvWjrȈtn  |dS)Nr) r"rrLrrUrMrJappendrrK)r|r`ZresultsZres)r nfinishednfutsouterrrr _done_callbacks4    zgather.._done_callbackr)rFr) rr+rvrKr rr!r9r]rr)rrZcoros_or_futuresrZ arg_to_futargr|r)rrrrrr r s2 1     r cs\t||drSt}|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 )rcs\r|s|dS|r.n*|}|dk rJ|n|dS)N)rrLrRrMrKrJ)innerr`)rrr _inner_done_callback#s  z$shield.._inner_done_callbackcssdS)N)r"rz)r)rrrr _outer_done_callback4sz$shield.._outer_done_callback)r r"rr!rvr])rrrr)rrrr r s     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 sTyttdWn6tk rN}zr<|Wdd}~XYnXdS)N)r)rZ _chain_futurer rZZset_running_or_notify_cancelrM)r`)rDrbrrr callbackFs  z*run_coroutine_threadsafe..callback)rr8r: concurrentrFutureZcall_soon_threadsafe)rDrrr)rDrbrr r =s    r cCst|dS)z3Register a new task in asyncio as executed by loop.N)r'r)rFrrr rZsrcCs4t|}|dk r(td|d|d|t|<dS)NzCannot enter into task z while another task z is being executed.)rrr()rrFrrrr r_s rcCs2t|}||k r(td|d|dt|=dS)Nz Leaving task z! does not match the current task .)rrr()rrFrrrr rgs rcCst|dS)zUnregister a task.N)r'discard)rFrrr rosr)rrrrr'r)N)N)N)N);rf__all__Zconcurrent.futuresrr>rxr_typesr/weakrefrrrrrrrr,Z _PyFuturerZ_PyTaskZ_asyncio ImportErrorZ_CTaskrrrrrrtrrpr{rrr 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_taskrrrr sx        }   9,7  m;$