j fUi@sRdZddddddddd d d d d dgZddlZddlZddlZddlZddlZddlZddl Z ddl m Z ddl m Z ddl m Z ddl mZddl mZGdddejZejjZejjZejjZedddddeddZddZeddddZeddZddddd dZedddd!dZddd"d Zddd#d Zed$d%ZGd&d'd'ejZddd(d)d*d Zddd+d Z d,d Z!ddd-dZ"Gd.d/d/Z#dS)0z0Support for tasks, coroutines and the scheduler.TaskFIRST_COMPLETEDFIRST_EXCEPTION ALL_COMPLETEDwaitwait_for as_completedsleepasyncgathershield ensure_futurerun_coroutine_threadsafetimeoutN)compat) coroutines)events)futures) coroutinecseZdZdZejZiZdZe dddZ e dddZ ddfd d Z e jrd d Znfd dZddddZddddddZddZdfddZddZS)rz A coroutine wrapped in a Future.TNcCs+|dkrtj}n|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)clsloopr2/opt/alt/python34/lib64/python3.4/asyncio/tasks.py current_task0s zTask.current_taskcs5dkrtjnfdd|jDS)z|Return a set of all tasks for an event loop. By default all tasks for the current event loop are returned. Ncs%h|]}|jkr|qSr)_loop).0t)rrr Ds z!Task.all_tasks..)rr _all_tasks)rrr)rr all_tasks<s zTask.all_tasksrcsntjd||jr)|jd=n||_d|_d|_|jj|j|j j j |dS)NrrF) super__init___source_traceback_coro _fut_waiter _must_cancelr call_soon_step __class__r"add)selfcoror)r-rrr&Fs     z Task.__init__cCso|jtjkr[|jr[i|d6dd6}|jrH|j|dz wait_for=%r)r% _repr_infor*rZ_format_coroutiner(insertr))r/infor0)r-rrr8`s  zTask._repr_infolimitc Csg}y|jj}Wntk r6|jj}YnX|dk rxO|dk r|dk r{|dkrnPn|d8}n|j||j}qFW|jns|jdk r|jj}xU|dk r|dk r|dkrPn|d8}n|j|j |j }qWn|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. Nrr) r(Zcr_frameAttributeErrorgi_frameappendf_backreverse _exception __traceback__tb_frametb_next)r/r;Zframesftbrrr get_stackns0            zTask.get_stackfilec Cscg}t}x|jd|D]}|j}|j}|j}|j} ||kru|j|tj|ntj |||j } |j ||| | fq"W|j } |st d|d|n7| dk rt d|d|nt d|d|tj|d|| dk r_x6tj| j| D]} t | d|ddq<WndS) 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 %rrHNz)Traceback for %r (most recent call last):z%Stack for %r (most recent call last):end)setrGf_linenof_code co_filenameco_namer. linecache checkcachegetline f_globalsr>rAprint traceback print_listformat_exception_onlyr-) r/r;rHextracted_listZcheckedrElinenocofilenamenamelineexcrrr print_stacks0              zTask.print_stackcCsB|jrdS|jdk r5|jjr5dSnd|_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)doner)cancelr*)r/rrrras  z Task.cancelcs|jr6t|tjs*tj}nd|_n|j}d|_||jj|j.)rbrr4r iscoroutine TypeErrortypert ValueErrorrrrrmrrrK_wait)fsrrr{r)rrr?s! cGs |js|jdndS)N)r`rg)waiterargsrrr_release_waiter_s rccs|dkrtj}n|dkr0|DdHStjd|}|j|t|}tjt|}t|d|}|j |z|y |DdHWn/tj k r|j ||j YnX|j r|jS|j ||j tjWd|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. Nr)rrrr4 call_laterr functoolspartialr rnrcremove_done_callbackrar`rr TimeoutError)futrrrtimeout_handlecbrrrrds,           c #stjd|d|dk r<|j|tnt|fdd}x|D]}|j|qjWz DdHWddk rjnXtt}}xD|D]<}|j||j r|j |q|j |qW||fS)zfInternal helper for wait() and _wait_for(). The fs argument must be a collection of Futures. rNcsd8dksMtksMtkr|j r|jdk rdk rfjnjsjdqndS)Nrr)rr cancelled exceptionrar`rg)rE)counterr{rrrr_on_completions      z_wait.._on_completion) rr4rrlenrnrarKrr`r.)rrr{rrrEr`pendingr)rr{rrrrs&        rc#sUt|tjs!tj|r=tdt|jndk rOn tj fddt |Dddl m }|ddfdd }fd d t fd d }xD]}|jqWr,|dk r,j||nx"ttD]}|Vq?WdS)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|dqS)r)r )rrE)rrrr!s zas_completed..r)Queuercs9x(D] }|jjdqWjdS)N)r put_nowaitclear)rE)rr`todorr _on_timeouts  z!as_completed.._on_timeoutcsHs dSj|j| rDdk rDjndS)N)removerra)rE)r`rrrrrs   z$as_completed.._on_completionc3s3jDdH}|dkr)tjn|jS)N)rrrrr)rE)r`rr _wait_for_ones  z#as_completed.._wait_for_one)rbrr4rr|r}r~rtrrrKZqueuesrrrnrranger)rrrrrrrE_r)rr`rrrrrs ! c csd|dkrdV|Stjd|}|jj|tj||}z |DdHSWd|jXdS)z9Coroutine that completes after a given time (in seconds).rNr)rr4rrZ_set_result_unless_cancelledra)Zdelayrrrrshrrrrs    cCs tjdtt|d|S)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()r)warningswarnDeprecationWarningr )coro_or_futurerrrrr s cCst|tjr@|dk r<||jk r<tdn|Stj|r|dkrjtj}n|j |}|j r|j d=n|St j rt j|rtt|d|StddS)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 Futurerrz1A Future, a coroutine or an awaitable is requiredr$)rbrr4rrrr|rrZ create_taskr'rZPY35rpZ isawaitabler _wrap_awaitabler})rrr1rrrr s   ccs|jDdHS)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)Z __await__)Z awaitablerrrr,srcs:eZdZdZddfddZddZS)_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. rNcs tjd|||_dS)Nr)r%r& _children)r/childrenr)r-rrr&>sz_GatheringFuture.__init__cCs2|jrdSx|jD]}|jqWdS)NFT)r`rra)r/ZchildrrrraBs  z_GatheringFuture.cancel)rtrurvrwr&rarr)r-rr6s rreturn_exceptionsFcsv|s)tjd|jgSixt|D]}t|tjst|d|}|dkr~|j}nd|_n<|}|dkr|j}n|j|k rtdn||ts zgather..rcsjr)|js%|jndS|jr[tj}sj|dSn>|jdk r|j}sj|dSn |j}||<d7krjndS)Nr) r`rrrrcrjrAZ_resultrg)irres) nchildren nfinishedouterresultsrrr_done_callbackzs&            zgather.._done_callback)rr4rgrKrbr rr3rrr enumeraternrr)rrZcoros_or_futuresrrrrrr)rrrrrrrr Js4        cs`t|d|}|jr"|S|j}tjd|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 rcsjr)|js%|jndS|jrBjn;|j}|dk rjj|nj|jdS)N)rrrarjrgrr)innerr^)rrrrs       zshield.._done_callback)r r`rrr4rn)rrrrr)rrr s   csVtjstdntjjfdd}j|S)zsSubmit a coroutine object to a given event loop. Return a concurrent.futures.Future to access the result. zA coroutine object is requiredcsky tjtdWnDtk rf}z$jrQj|nWYdd}~XnXdS)Nr)rZ _chain_futurer riZset_running_or_notify_cancelrj)r^)r0rsrrrcallbacks   z*run_coroutine_threadsafe..callback)rr|r} concurrentrr4Zcall_soon_threadsafe)r0rrr)r0rsrrr s  cCs+|dkrtj}nt|d|S)ahA factory which produce a context manager with timeout. Useful in cases when you want to apply timeout logic around block of code or in cases when asyncio.wait_for is not suitable. For example: >>> with asyncio.timeout(0.001): ... yield from coro() timeout: timeout value in seconds loop: asyncio compatible event loop Nr)rr_Timeout)rrrrrrs c@s@eZdZddZddZddZddZd S) rcCs1||_||_d|_d|_d|_dS)NF)_timeoutr_task _cancelled_cancel_handler)r/rrrrrr&s     z_Timeout.__init__cCsXtjd|j|_|jdkr6tdn|jj|j|j|_|S)Nrz4Timeout context manager should be used inside a task) rrrrrlrr _cancel_taskr)r/rrr __enter__s  z_Timeout.__enter__cCsY|tjkr6|jr6d|_d|_tjn|jjd|_d|_dS)N)rrcrrrrra)r/exc_typeZexc_valZexc_tbrrr__exit__s     z_Timeout.__exit__cCs|jj|_dS)N)rrar)r/rrrrsz_Timeout._cancel_taskN)rtrurvr&rrrrrrrrs   r)$rw__all__Zconcurrent.futuresrrrprPrUrrxrJrrrrrr4rrrrrrrrrrr r rrr r r rrrrrrsP          "    --8 N5