ñÕYf¶gã @sCdZddddddddd d d d d g ZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddl m Z ddl mZddl mZGdd„dejƒZejjZejjZejjZedddddedd„ƒZdd„Zedddd„ƒZedd„ƒZddddd d„Zedddd!d„ƒZddd"d#„Zeeƒd Cs z!Task.all_tasks..)rrÚ _all_tasks)rrr)rrÚ all_tasks;s  zTask.all_tasksrcsŒtj|ƒs!tt|ƒƒ‚tƒjd|ƒ|jrG|jd=||_d|_d|_ |j j |j ƒ|j jj|ƒdS)NrrFéÿÿÿÿ)rÚ iscoroutineÚAssertionErrorÚreprÚsuperÚ__init__Ú_source_tracebackÚ_coroÚ _fut_waiterÚ _must_cancelrÚ call_soonÚ_stepÚ __class__r!Úadd)ÚselfÚcoror)r/rrr(Es!     z Task.__init__cCsg|jtjkrS|jrSd|ddi}|jrC|j|d<|jj|ƒtjj|ƒdS)NÚtaskÚmessagez%Task was destroyed but it is pending!Zsource_traceback) Z_staterZ_PENDINGÚ_log_destroy_pendingr)rZcall_exception_handlerÚFutureÚ__del__)r1Úcontextrrrr7Ts   z Task.__del__csrtƒjƒ}|jr"d|déz wait_for=%r)r'Ú _repr_infor,rZ_format_coroutiner*Úinsertr+)r1Úinfor2)r/rrr:_s  zTask._repr_infoÚlimitc Cs g}y|jj}Wntk r6|jj}YnX|dk rœxI|dk rŽ|dk ru|dkrkP|d8}|j|ƒ|j}qFW|jƒnj|jdk r|jj}xL|dk r|dk ré|dkrßP|d8}|j|j ƒ|j }qºW|S)a�Return 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. Nrr) r*Úcr_frameÚAttributeErrorÚgi_frameÚappendÚf_backÚreverseÚ _exceptionÚ __traceback__Útb_frameÚtb_next)r1r=ZframesÚfÚtbrrrÚ get_stackms0             zTask.get_stackÚfilec Cs]g}tƒ}x•|jd|ƒD]�}|j}|j}|j}|j} ||krr|j|ƒtj|ƒtj |||j ƒ} |j ||| | fƒq"W|j } |sÍt d|d|ƒn7| dk rðt d|d|ƒnt d|d|ƒtj|d|ƒ| dk rYx3tj| j| ƒD]} t | d|ddƒq9WdS) 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=zNo stack for %rrKNz)Traceback for %r (most recent call last):z%Stack for %r (most recent call last):ÚendÚ)ÚsetrJÚf_linenoÚf_codeÚ co_filenameÚco_namer0Ú linecacheÚ checkcacheÚgetlineÚ f_globalsrArDÚprintÚ tracebackÚ print_listÚformat_exception_onlyr/) r1r=rKÚextracted_listZcheckedrHÚlinenoÚcoÚfilenameÚnameÚlineÚexcrrrÚ print_stackœs0               zTask.print_stackcCsHd|_|jƒrdS|jdk r;|jjƒr;dSd|_dS)a‚Request 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_tracebackÚdoner+Úcancelr,)r1rrrrd¿s   z Task.cancelcs@|jƒ s%tdj||ƒƒ‚|jrUt|tjƒsLtjƒ}d|_|j}d|_||j j |j .)rÚisfuturerr$Ú TypeErrorÚtyperyÚ ValueErrorrrrrfrrrNÚ_wait)Úfsrr€r�r)rrrLs   cGs|jƒs|jdƒdS)N)rcrm)ÚwaiterÚargsrrrÚ_release_waiterls rŠccs |dkrtjƒ}|dkr-|EdHS|jƒ}|j|t|ƒ}tjt|ƒ}t|d|ƒ}|j|ƒz|y |EdHWn/t j k rÀ|j |ƒ|j ƒ‚YnX|j ƒr×|jƒS|j |ƒ|j ƒt jƒ‚Wd|j ƒXdS)a€Wait 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)rrÚ create_futureÚ call_laterrŠÚ functoolsÚpartialr rsrrhÚremove_done_callbackrdrcrwÚ TimeoutError)Úfutr€rrˆÚtimeout_handleÚcbrrrrqs,             c #s|stdƒ‚|jƒ‰d‰|dk rE|j|tˆƒ‰t|ƒ‰‡‡‡‡fdd†}x|D]}|j|ƒqsWz ˆEdHWdˆdk r°ˆjƒXtƒtƒ}}xD|D]<}|j|ƒ|j ƒrú|j |ƒqË|j |ƒqËW||fS)zeInternal helper for wait() and wait_for(). The fs argument must be a collection of Futures. zSet of Futures is empty.Ncs€ˆd8‰ˆdksMˆtksMˆtkr||jƒ r||jƒdk r|ˆdk rcˆjƒˆjƒs|ˆjdƒdS)Nrr)rrÚ cancelledÚ exceptionrdrcrm)rH)Úcounterr�r’rˆrrÚ_on_completion¬s      z_wait.._on_completion) r%r‹rŒrŠÚlenrsrdrNr�rcr0)r‡r€r�rr—rHrcÚpendingr)r–r�r’rˆrr†Ÿs(          r†c#sLtj|ƒstj|ƒr7tdt|ƒjƒ‚ˆdk rIˆn tjƒ‰‡fdd†t |ƒDƒ‰ddl m }|dˆƒ‰d‰‡‡‡fdd †}‡‡‡fd d †‰t ‡fd d †ƒ}xˆD]}|j ˆƒqèWˆr#|dk r#ˆj||ƒ‰x"ttˆƒƒD]}|ƒVq6WdS)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 %sNcs"h|]}t|dˆƒ’qS)r)r )rrH)rrrr ás zas_completed..r)ÚQueuercs9x(ˆD] }|jˆƒˆjdƒqWˆjƒdS)N)r�Ú put_nowaitÚclear)rH)r—rcÚtodorrÚ _on_timeoutæs  z!as_completed.._on_timeoutcsEˆs dSˆj|ƒˆj|ƒˆ rAˆdk rAˆjƒdS)N)Úremover›rd)rH)rcr’r�rrr—ìs   z$as_completed.._on_completionc3s0ˆjƒEdH}|dkr&tj‚|jƒS)N)rrr�rw)rH)rcrrÚ _wait_for_oneôs  z#as_completed.._wait_for_one)rr‚rr$rƒr„ryrrrNZqueuesršrrsrŒÚranger˜)r‡rr€ršržr rHÚ_r)r—rcrr’r�rrÌs  c csv|dkrdV|S|dkr-tjƒ}|jƒ}|jj|tj||ƒ}z |EdHSWd|jƒXdS)z9Coroutine that completes after a given time (in seconds).rN)rrr‹rrŒrZ_set_result_unless_cancelledrd)ZdelayrwrrxÚhrrrrs       cCs&tjdtddƒt|d|ƒS)z«Wrap 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()Ú stacklevelr9r)ÚwarningsÚwarnÚDeprecationWarningr )Úcoro_or_futurerrrrÚasync_s r©cCsÅtj|ƒr:|dk r6||jk r6tdƒ‚|Stj|ƒr‡|dkratjƒ}|j|ƒ}|j rƒ|j d=|St j rµt j |ƒrµtt|ƒd|ƒStdƒ‚dS)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 Futurerrz:An asyncio.Future, a coroutine or an awaitable is requiredr#)rr‚rr…rr$rrZ create_taskr)rZPY35ruZ isawaitabler Ú_wrap_awaitablerƒ)r¨rr3rrrr +s     ccs|jƒEdHS)z¦Helper 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 awaitablerrrrªBsrªcs:eZdZdZdd‡fdd†Zdd„Z‡S)Ú_GatheringFuturez®Helper for gather(). This overrides cancel() to cancel all the children and act more like Task.cancel(), which doesn't immediately mark itself as cancelled. rNcs tƒjd|ƒ||_dS)Nr)r'r(Ú _children)r1Úchildrenr)r/rrr(Tsz_GatheringFuture.__init__cCs@|jƒrdSd}x#|jD]}|jƒr d}q W|S)NFT)rcr­rd)r1ZretZchildrrrrdXs   z_GatheringFuture.cancel)ryrzr{r|r(rdrr)r/rr¬Ls r¬Úreturn_exceptionsFcs|s;|dkrtjƒ}|jƒ‰ˆjgƒˆSi‰x™t|ƒD]‹}tj|ƒs–t|d|ƒ}|dkrŠ|j}d|_ n9|}|dkr´|j}n|j|k rÏt dƒ‚|ˆ|’s zgather..rcsLjjƒr&|jƒs"|jƒdS|jƒrXtjƒ}ˆs–ˆj|ƒdSn>|jdk r�|jƒ}ˆs–ˆj|ƒdSn |j}|ˆ|<ˆd7‰ˆˆkrÈjˆƒdS)Nr) rcr”r•rrhrlrDZ_resultrm)Úir‘Úres)Ú nchildrenÚ nfinishedÚouterÚresultsr¯rrÚ_done_callback˜s&            zgather.._done_callback)rrr‹rmrNrr‚r rr5r…r˜r¬Ú enumeratersr�rŽ)rr¯Zcoros_or_futuresr°r‘r®r¹r³r)r±rµr¶r·r¸r¯rr bs8            csZt|d|ƒ}|jƒr"|S|j}|jƒ‰‡fdd†}|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~ˆjƒr&|jƒs"|jƒdS|jƒr?ˆjƒn;|jƒ}|dk rgˆj|ƒnˆj|jƒƒdS)N)r”r•rdrlrmrw)Úinnerra)r·rrr¹×s       zshield.._done_callback)r rcrr‹rs)r°rr»r¹r)r·rr ¶s    csStjˆƒstdƒ‚tjjƒ‰‡‡‡fdd†}ˆj|ƒˆS)zsSubmit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result. zA coroutine object is requiredcshy tjtˆdˆƒˆƒWnAtk rc}z!ˆjƒrNˆj|ƒ‚WYdd}~XnXdS)Nr)rZ _chain_futurer roZset_running_or_notify_cancelrl)ra)r2rxrrrÚcallbackôs    z*run_coroutine_threadsafe..callback)rr$rƒÚ concurrentrr6Zcall_soon_threadsafe)r2rr¼r)r2rxrrr ës   )$r|Ú__all__Zconcurrent.futuresr½r�rurSrXr¥r}rMrrrrrr6rrrrrrŠrr†rrr©Úglobalsryr rªr¬r r r rrrrÚsP        ÿ0    --8   T5