
    Rh                         d Z ddlZddlZddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddlm
Z
 ddlmZ  G d	 d
ej                        Z G d d      ZddddZd Zy))Runnerrun    N   )
coroutines)events)
exceptions)tasks)	constantsc                       e Zd ZdZdZdZy)_StatecreatedinitializedclosedN)__name__
__module____qualname__CREATEDINITIALIZEDCLOSED     &/usr/lib/python3.12/asyncio/runners.pyr   r      s    GKFr   r   c                   N    e Zd ZdZddddZd Zd Zd Zd Zdd	d
Z	d Z
d Zy)r   a5  A context manager that controls event loop life cycle.

    The context manager always creates a new event loop,
    allows to run async functions inside it,
    and properly finalizes the loop at the context manager exit.

    If debug is True, the event loop will be run in debug mode.
    If loop_factory is passed, it is used for new event loop creation.

    asyncio.run(main(), debug=True)

    is a shortcut for

    with asyncio.Runner(debug=True) as runner:
        runner.run(main())

    The run() method can be called multiple times within the runner's context.

    This can be useful for interactive console (e.g. IPython),
    unittest runners, console tools, -- everywhere when async code
    is called from existing sync framework and where the preferred single
    asyncio.run() call doesn't work.

    Ndebugloop_factoryc                    t         j                  | _        || _        || _        d | _        d | _        d| _        d| _        y )Nr   F)	r   r   _state_debug_loop_factory_loop_context_interrupt_count_set_event_loop)selfr   r   s      r   __init__zRunner.__init__0   s:    nn)
 !$r   c                 &    | j                          | S N)
_lazy_initr%   s    r   	__enter__zRunner.__enter__9   s    r   c                 $    | j                          y r(   )close)r%   exc_typeexc_valexc_tbs       r   __exit__zRunner.__exit__=   s    

r   c                 F   | j                   t        j                  ury	 | j                  }t	        |       |j                  |j                                |j                  |j                  t        j                               | j                  rt        j                  d       |j                          d| _        t        j                  | _         y# | j                  rt        j                  d       j                          d| _        t        j                  | _         w xY w)zShutdown and close event loop.N)r   r   r   r!   _cancel_all_tasksrun_until_completeshutdown_asyncgensshutdown_default_executorr
   THREAD_JOIN_TIMEOUTr$   r   set_event_loopr-   r   )r%   loops     r   r-   zRunner.close@   s    ;;f000	(::Dd###D$;$;$=>##..y/L/LMO ##%%d+JJLDJ --DK	 ##%%d+JJLDJ --DKs   A$C AD c                 :    | j                          | j                  S )zReturn embedded event loop.)r)   r!   r*   s    r   get_loopzRunner.get_loopQ   s    zzr   contextc                   t        j                  |      st        dj                  |            t	        j
                         t        d      | j                          || j                  }| j                  j                  ||      }t        j                         t        j                         u rzt        j                  t        j                         t        j"                  u rGt%        j&                  | j(                  |      }	 t        j                  t        j                   |       nd}d| _        	 | j                  j-                  |      |Yt        j                  t        j                         |u r3t        j                  t        j                   t        j"                         S S S # t        $ r d}Y w xY w# t.        j0                  $ r4 | j*                  dkD  r#t3        |dd      }| |       dk(  r
t5                w xY w# |Yt        j                  t        j                         |u r3t        j                  t        j                   t        j"                         w w w xY w)z/Run a coroutine inside the embedded event loop.z"a coroutine was expected, got {!r}Nz7Runner.run() cannot be called from a running event loopr<   )	main_taskr   uncancel)r   iscoroutine
ValueErrorformatr   _get_running_loopRuntimeErrorr)   r"   r!   create_task	threadingcurrent_threadmain_threadsignal	getsignalSIGINTdefault_int_handler	functoolspartial
_on_sigintr#   r4   r   CancelledErrorgetattrKeyboardInterrupt)r%   coror=   tasksigint_handlerr@   s         r   r   z
Runner.runV   s   %%d+AHHNOO##%1IK K 	?mmGzz%%dG%<$$&)*?*?*AA  /63M3MM&..t$ON&fmm^< "N !	I::006 *$$V]]3~EfmmV-G-GH F +%  & "&	& (( 	$$q("4T:'HJ!O+--	 *$$V]]3~EfmmV-G-GH F +s,   $F, 6F= ,F:9F:=AHH AI$c                 $   | j                   t        j                  u rt        d      | j                   t        j                  u ry | j
                  Lt        j                         | _        | j                  s<t        j                  | j                         d| _	        n| j                         | _        | j                  %| j                  j                  | j                         t        j                         | _        t        j                  | _         y )NzRunner is closedT)r   r   r   rE   r   r    r   new_event_loopr!   r$   r8   r   	set_debugcontextvarscopy_contextr"   r*   s    r   r)   zRunner._lazy_init   s    ;;&--'122;;&,,,%..0DJ'' %%djj1'+$++-DJ;;"JJ  -#002((r   c                     | xj                   dz  c_         | j                   dk(  r=|j                         s-|j                          | j                  j	                  d        y t               )Nr   c                       y r(   r   r   r   r   <lambda>z#Runner._on_sigint.<locals>.<lambda>   s    r   )r#   donecancelr!   call_soon_threadsaferS   )r%   signumframer?   s       r   rP   zRunner._on_sigint   sT    "  A%inn.>JJ++L9!!r   )r   r   r   __doc__r&   r+   r1   r-   r;   r   r)   rP   r   r   r   r   r      s=    6 !%4 %("
 $( +IZ)&"r   r   r   c                    t        j                         t        d      t        ||      5 }|j	                  |       cddd       S # 1 sw Y   yxY w)az  Execute the coroutine and return the result.

    This function runs the passed coroutine, taking care of
    managing the asyncio event loop, finalizing asynchronous
    generators and closing the default executor.

    This function cannot be called when another asyncio event loop is
    running in the same thread.

    If debug is True, the event loop will be run in debug mode.

    This function always creates a new event loop and closes it at the end.
    It should be used as a main entry point for asyncio programs, and should
    ideally only be called once.

    The executor is given a timeout duration of 5 minutes to shutdown.
    If the executor hasn't finished within that duration, a warning is
    emitted and the executor is closed.

    Example:

        async def main():
            await asyncio.sleep(1)
            print('hello')

        asyncio.run(main())
    Nz8asyncio.run() cannot be called from a running event loopr   )r   rD   rE   r   r   )mainr   r   runners       r   r   r      sT    8 !-FH 	H 
e,	7  6zz$     s   AAc                 B   t        j                  |       }|sy |D ]  }|j                           | j                  t        j                  |ddi       |D ]G  }|j                         r|j                         %| j                  d|j                         |d       I y )Nreturn_exceptionsTz1unhandled exception during asyncio.run() shutdown)message	exceptionrU   )r	   	all_tasksr`   r4   gather	cancelledrk   call_exception_handler)r9   	to_cancelrU   s      r   r3   r3      s    %I  	ELL)LtLM >>>>'''N!^^-) 	r   )__all__rZ   enumrN   rG   rJ    r   r   r   r	   r
   Enumr   r   r   r3   r   r   r   <module>ru      sW   
          TYY I" I"X $ " Jr   