3 \a @sdZddddddddd d d d d g ZddlZddlZddlZddlZddlZddlm Z ddlm Z ddlm Z ddlm Z ddlm Z ddl mZGddde jZeZy ddlZWnek rYn XejZZej jZej jZej jZeddedddZddZeddddZeddZddd d!dZed/ddd"dZddd#d$Zeed <d e_ [ddd%d Z!ed&d'Z"Gd(d)d)e jZ#dd*d+d,d Z$ddd-d Z%d.d Z&dS)0z0Support for tasks, coroutines and the scheduler.TaskFIRST_COMPLETEDFIRST_EXCEPTION ALL_COMPLETEDwaitwait_for as_completedsleepasyncgathershield ensure_futurerun_coroutine_threadsafeN) base_tasks)compat) coroutines)events)futures) coroutinecseZdZdZejZiZdZe dddZ e dddZ ddfd d Z e jrXd d Zd dZddddZdddddZddZdfdd ZddZZS)rz A coroutine wrapped in a Future.TNcCs|dkrtj}|jj|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. N)rget_event_loop_current_tasksget)clsloopr/usr/lib64/python3.6/tasks.py current_task.szTask.current_taskcs$dkrtjfdd|jDS)z|Return a set of all tasks for an event loop. By default all tasks for the current event loop are returned. Ncsh|]}|jkr|qSr)_loop).0t)rrr Bsz!Task.all_tasks..)rr _all_tasks)rrr)rr all_tasks:szTask.all_tasks)rcsdtj|stt|tj|d|jr2|jd=||_d|_d|_ |j j |j |j jj|dS)N)rrF)r iscoroutineAssertionErrorreprsuper__init___source_traceback_coro _fut_waiter _must_cancelr call_soon_step __class__r"add)selfcoror)r0rrr)Dsz Task.__init__cCsH|jtjkr8|jr8|dd}|jr,|j|d<|jj|tjj|dS)Nz%Task was destroyed but it is pending!)taskmessageZsource_traceback) Z_staterZ_PENDING_log_destroy_pendingr*rZcall_exception_handlerFuture__del__)r2contextrrrr8Ss  z Task.__del__cCs tj|S)N)rZ_task_repr_info)r2rrr _repr_info^szTask._repr_info)limitcCs 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. )rZ_task_get_stack)r2r;rrr get_stackaszTask.get_stack)r;filecCstj|||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)r2r;r=rrr print_stackxs zTask.print_stackcCs4d|_|jrdS|jdk r*|jjr*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_tracebackdoner,cancelr-)r2rrrr@s  z Task.cancelcs|j stdj|||jr:t|tjs4tj}d|_|j}d|_||j j |j <zy"|dkrn|j d}n |j |}Wntk r}z.|jrd|_|jtjn |j|jWYdd}~Xntjk rtjYn~tk r}z|j|WYdd}~XnPtk rD}z|j|WYdd}~Xn Xt|dd}|dk r|j |j k r|j j|jtdj||n||r||kr|j j|jtdj|n2d|_|j|j||_|jr|jjrd|_n|j j|jtdj||n^|dkr |j j|jnDtj|rJ|j j|jtdj||n|j j|jtdj|Wd|j j j|j d}XdS) Nz!_step(): already done: {!r}, {!r}F_asyncio_future_blockingz6Task {!r} got Future {!r} attached to a different loopz!Task cannot await on itself: {!r}z;yield was used instead of yield from in task {!r} with {!r}zIyield was used instead of yield from for generator in task {!r} with {!r}zTask got bad yield: {!r}) r?r&formatr- isinstancerCancelledErrorr+r,r0rrsendthrow StopIteration set_exception set_resultvaluer(r@ Exception BaseExceptiongetattrr.r/ RuntimeErrorrAadd_done_callback_wakeupinspectZ isgeneratorpop)r2excr3resultZblocking)r0rrr/s            z Task._stepcCsJy |jWn,tk r8}z|j|WYdd}~Xn X|jd}dS)N)rTrKr/)r2futurerSrrrrPs  z Task._wakeup)N)N)N)__name__ __module__ __qualname____doc__weakrefWeakSetr"rr6 classmethodrr#r)rZPY34r8r:r<r>r@r/rP __classcell__rr)r0rrs"     !T)rtimeout return_whenc#stj|stj|r&tdt|j|s2td|tt t fkrNtdj |dkr^t j fddt|D}t|||EdHS)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 = yield from asyncio.wait(fs) Note: This does not raise TimeoutError! Futures that aren't done when the timeout occurs are returned in the second set. z expect a list of futures, not %sz#Set of coroutines/Futures is empty.zInvalid return_when value: {}Ncsh|]}t|dqS))r)r )rf)rrrr!7szwait..)risfuturerr% TypeErrortyperV ValueErrorrrrrBrrset_wait)fsrr^r_r)rrrscGs|js|jddS)N)r?rI)waiterargsrrr_release_waiter<srj)rccs|dkrtj}|dkr"|EdHS|j}|j|t|}tjt|}t||d}|j|zhy|EdHWn*t j k r|j ||j YnX|j r|jS|j ||j t jWd|j 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. N)r)rr create_future call_laterrj functoolspartialr rOrrDremove_done_callbackr@r?rT TimeoutError)futr^rrhtimeout_handlecbrrrrAs,       c #s|s td|jd|dk r.|j|tt|fdd}x|D]}|j|qNWzEdHWddk rjXtt}}x4|D],}|j||j r|j |q|j |qW||fS)zeInternal helper for wait() and wait_for(). The fs argument must be a collection of Futures. zSet of Futures is empty.Ncs\d8dks6tks6tkrX|j rX|jdk rXdk rFjjsXjddS)Nrr)rr cancelled exceptionr@r?rI)r`)counterr_rrrhrr_on_completion|s z_wait.._on_completion) r&rkrlrjlenrOr@reror?r1)rgr^r_rrwr`r?pendingr)rvr_rrrhrrfos(      rf)rr^c#stj|stj|r&tdt|jdk r2ntjfddt |Dddl m }|ddfdd }fd d t fd d }xD]}|j qWr|dk rʈj||xttD] }|VqWdS)amReturn an iterator whose values are coroutines. When waiting for the yielded coroutines you'll get the results (or exceptions!) of the original Futures (or coroutines), in the order in which and as soon as they complete. This differs from PEP 3148; the proper way to use this is: for f in as_completed(fs): result = yield from f # The 'yield from' may raise. # Use result. If a timeout is specified, the 'yield from' will raise TimeoutError when the timeout occurs before all Futures are done. Note: The futures 'f' are not necessarily members of fs. z expect a list of futures, not %sNcsh|]}t|dqS))r)r )rr`)rrrr!szas_completed..r)Queue)rcs.x D]}|jjdqWjdS)N)ro put_nowaitclear)r`)rwr?todorr _on_timeouts  z!as_completed.._on_timeoutcs6sdSj|j| r2dk r2jdS)N)remover{r@)r`)r?rrr}rrrws   z$as_completed.._on_completionc3s$jEdH}|dkrtj|jS)N)rrrprT)r`)r?rr _wait_for_onesz#as_completed.._wait_for_one)rrarr%rbrcrVrrreZqueuesrzrrOrlrangerx)rgrr^rzr~rr`_r)rwr?rrrr}rrs      c csX|dkrdV|S|dkr"tj}|j}|jj|tj||}z |EdHS|jXdS)z9Coroutine that completes after a given time (in seconds).rN)rrrkrrlrZ_set_result_unless_cancelledr@)ZdelayrTrrUhrrrrs cCstjdtddt||dS)zWrap a coroutine in a future. If the argument is a Future, it is returned directly. This function is deprecated in 3.5. Use asyncio.ensure_future() instead. z;asyncio.async() function is deprecated, use ensure_future()) stacklevel)r)warningswarnDeprecationWarningr )coro_or_futurerrrrasync_srcCstj|r(|dk r$||jk r$td|Stj|r^|dkrBtj}|j|}|j rZ|j d=|St j r~t j |r~tt||dStddS)zmWrap a coroutine or an awaitable in a future. If the argument is a Future, it is returned directly. Nz$loop argument must agree with Futurer)rz:An asyncio.Future, a coroutine or an awaitable is requiredr$)rrarrdrr%rrZ create_taskr*rZPY35rQZ isawaitabler _wrap_awaitablerb)rrr4rrrr s   ccs|jEdHS)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 awaitablerrrrsrcs.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)r(r) _children_cancel_requested)r2childrenr)r0rrr)$sz_GatheringFuture.__init__cCs:|jr dSd}x|jD]}|jrd}qW|r6d|_|S)NFT)r?rr@r)r2ZretZchildrrrr@)s z_GatheringFuture.cancel)rVrWrXrYr)r@r]rr)r0rrsrF)rreturn_exceptionscs|s*|dkrtj}|jjgSixjt|D]^}tj|sht||d}|dkr`|j}d|_ n&|}|dkr||j}n|j|k rt d||<q8Wfdd|D}t |t ||dddgfdd }x&t |D]\}}|jtj||qWS) a7Return a future aggregating results from the given coroutines or 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.) N)rFz)futures are tied to different event loopscsg|] }|qSrr)rarg) arg_to_futrr hszgather..rcsjr|js|jdS|jr@tj}slj|dSn,|jdk rf|j}slj|dSn|j}||<d7krjrjtjn j dS)Nr) r?rtrurrDrHZ _exceptionZ_resultrrI)irqres) nchildren nfinishedouterresultsrrr_done_callbackns*   zgather.._done_callback)rrrkrIrerrar rr6rdrxr enumeraterOrmrn)rrZcoros_or_futuresrrqrrrr)rrrrrrrr 8s8       cs@t||d}|jr|S|j}|jfdd}|j|S)a=Wait for a future, shielding it from cancellation. The statement res = yield from shield(something()) is exactly equivalent to the statement res = yield from 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 = yield from shield(something()) except CancelledError: res = None )rcs\jr|js|jdS|jr.jn*|j}|dk rJj|nj|jdS)N)rtrur@rHrIrT)innerrS)rrrrs  zshield.._done_callback)r r?rrkrO)rrrrr)rrr s   cs:tjstdtjjfdd}j|S)zsSubmit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result. zA coroutine object is requiredcsTytjtdWn6tk rN}zjr<j|WYdd}~XnXdS)N)r)rZ _chain_futurer rKZset_running_or_notify_cancelrH)rS)r3rUrrrcallbacks  z*run_coroutine_threadsafe..callback)rr%rb concurrentrr7Zcall_soon_threadsafe)r3rrr)r3rUrrr s    )N)'rY__all__concurrent.futuresrrmrQrrZrrrrrrr7rZ_PyTaskZ_asyncio ImportErrorZ_CTaskrrrrrjrrfrrrglobalsrVr rrr r r rrrrsZ        s  - -8  W5