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)rcsNtj|d|jr|jd=||_d|_d|_|jj|j|j j j |dS)N)rrF) super__init___source_traceback_coro _fut_waiter _must_cancelr call_soon_step __class__r"add)selfcoror)r-rrr&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__)r/contextrrrr5Ss  z Task.__del__cCs tj|S)N)rZ_task_repr_info)r/rrr _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)r/r8rrr get_stackaszTask.get_stack)r8filecCstj|||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)r/r8r: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*)r/rrrr=s  z Task.cancelcsf|jr t|tjstj}d|_|j}d|_||jj|j<zy"|dkrT|j d}n |j |}Wnt k r}z.|jrd|_|j tjn |j |jWYdd}~Xntjk rtjYn|tk r}z|j |WYdd}~XnPtk r(}z|j |WYdd}~Xn Xt|dd}|dk r|j|jk rl|jj|jtdj||n||r||kr|jj|jtdj|n2d|_|j|j||_|jr|jjrd|_n|jj|jtdj||n^|dkr|jj|jnDtj|r.|jj|jtdj||n|jj|jtdj|Wd|jjj|jd}XdS)NF_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* isinstancerCancelledErrorr(r)r-rrsendthrow StopIteration set_exception set_resultvaluer%r= Exception BaseExceptiongetattrr+r, RuntimeErrorformatr>add_done_callback_wakeupinspectZ isgeneratorpop)r/excr0resultZblocking)r-rrr,s~           z Task._stepcCsJy |jWn,tk r8}z|j|WYdd}~Xn X|jd}dS)N)rQrGr,)r/futurerPrrrrMs  z Task._wakeup)N)N)N)__name__ __module__ __qualname____doc__weakrefWeakSetr"rr3 classmethodrr#r&rZPY34r5r7r9r;r=r,rM __classcell__rr)r-rrs"     !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..)risfuturer iscoroutine TypeErrortyperS ValueErrorrrrrKrrset_wait)fsrr[r\r)rrrscGs|js|jddS)N)r<rE)waiterargsrrr_release_waiter<srh)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_laterrh functoolspartialr rLrr@remove_done_callbackr=r<rQ TimeoutError)futr[rrftimeout_handlecbrrrrAs,       c #s|jd|dk r"|j|tt|fdd}x|D]}|j|qBWzEdHWddk rtjXtt}}x4|D],}|j||jr|j |q|j |qW||fS)zeInternal helper for wait() and wait_for(). The fs argument must be a collection of Futures. Ncs\d8dks6tks6tkrX|j rX|jdk rXdk rFjjsXjddS)Nrr)rr cancelled exceptionr=r<rE)r])counterr\rprfrr_on_completion|s z_wait.._on_completion) rirjrhlenrLr=rcrmr<r.)rer[r\rrur]r<pendingr)rtr\rprfrrdos&     rd)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)rm put_nowaitclear)r])rur<todorr _on_timeouts  z!as_completed.._on_timeoutcs6sdSj|j| r2dk r2jdS)N)removeryr=)r])r<rpr{rrrus   z$as_completed.._on_completionc3s$jEdH}|dkrtj|jS)N)rrrnrQ)r])r<rr _wait_for_onesz#as_completed.._wait_for_one)rr^rr_r`rarSrrrcZqueuesrxrrLrjrangerv)rerr[rxr|r~r]_r)rur<rrpr{rrs      c csX|dkrdV|S|dkr"tj}|j}|jj|tj||}z |EdHS|jXdS)z9Coroutine that completes after a given time (in seconds).rN)rrrirrjrZ_set_result_unless_cancelledr=)ZdelayrQrrRhrrrrs 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$)rr^rrbrr_rrZ create_taskr'rZPY35rNZ isawaitabler _wrap_awaitabler`)rrr1rrrr 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)r/childrenr)r-rrr&$sz_GatheringFuture.__init__cCs:|jr dSd}x|jD]}|jrd}qW|r6d|_|S)NFT)r<rr=r)r/ZretZchildrrrr=)s z_GatheringFuture.cancel)rSrTrUrVr&r=rZrr)r-rrsrF)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<rrrsrr@rDZ _exceptionZ_resultrrE)irores) nchildren nfinishedouterresultsrrr_done_callbackns*   zgather.._done_callback)rrrirErcrr^r rr3rbrvr enumeraterLrkrl)rrZcoros_or_futuresrrorrrr)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)rrrsr=rDrErQ)innerrP)rrrrs  zshield.._done_callback)r r<rrirL)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 rGZset_running_or_notify_cancelrD)rP)r0rRrrrcallbacks  z*run_coroutine_threadsafe..callback)rr_r` concurrentrr4Zcall_soon_threadsafe)r0rrr)r0rRrrr s    )N)'rV__all__concurrent.futuresrrkrNrrWrrrrrrr4rZ_PyTaskZ_asyncio ImportErrorZ_CTaskrrrrrhrrdrrrglobalsrSr rrr r r rrrrsZ        s  - -8  W5