o
    i                     @  s  U d Z ddlmZ ddlZddlZddlZddlZddlZddl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mZmZ ddlmZ ddlmZ ddlmZmZmZmZmZ d	d
lmZ ejdkrqddlm Z  ndZ zddl!m"Z# W n e$y   ej#Z#Y nw 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/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 ddl9m:Z: ddl;m<Z< d	dl=m>Z> d	dl?m@Z@ d	dlAmBZBmCZC dZDdeEd< eFdZGdd ZHG dd  d e-ZIdS )!z9Base class for a kernel that talks to frontends over 0MQ.    )annotationsN)Mapping)Context
ContextVarcopy_context)datetime)partial)SIGINTSIGTERMSignalsdefault_int_handlersignal   )CONTROL_THREAD_NAMEwin32)SIGKILLzwindown-SIGKILL-sentinel)utcnowStdinNotImplementedError)Session)ioloop)SingletonConfigurable)
AnyBoolDictFloatInstanceIntegerListUnicodedefaultobserve)	ZMQStream)
json_clean)kernel_protocol_version)	OutStream)LazyDict_async_in_contextaa  For consistency across implementations, it is recommended that `{func_name}` either be a coroutine function (`async def`) or return an awaitable object (like an `asyncio.Future`). It might become a requirement in the future. Coroutine functions and awaitables have been supported since ipykernel 6.0 (2021). {target} does not seem to return an awaitablestr_AWAITABLE_MESSAGETc                 C  s`   t | j}t|d}|D ]}||}|o|j|j|jfv p*t	dd |
 D ||< q|S )NFc                 s  s    | ]	}|j |jkV  qd S N)kindVAR_KEYWORD).0p r0   O/var/www/edux/Edux_v2/venv/lib/python3.10/site-packages/ipykernel/kernelbase.py	<genexpr>U   s    z&_accepts_parameters.<locals>.<genexpr>)inspect	signature
parametersdictfromkeysgetr,   KEYWORD_ONLYPOSITIONAL_OR_KEYWORDanyvalues)methparam_namesr5   acceptsparam
param_specr0   r0   r1   _accepts_parametersL   s   
rB   c                      s`  e Zd ZU dZedZi Zded< eddd Z	e
edd	Ze
d
dd	Ze
edd	ZeddZded< ded< ded< ded< eddd Zeddd Ze
edd	Ze Ze Ze Ze Ze Ze Ze
ejdd	Zded< edZ e! Z"eddd Z#i Z$ded< e Z%ded < e&dd!dj'dd"Z(e&dd#dj'dd"Z)e&d$Z*e+i Z,d%ed&< d'Z-d(ed)< d*ed+< d,ed-< d.ed/< d0ed1< d2ed3< e.d4d5 Z/e0d6j'dd"Z1e0d7j'dd"Z2e0d8dd9d:Z3dZ4e+ Z5d;Z6e
e7j8Z9g d<Z:g e:d=d>d?d@dAZ; fdBdCZ<dDdE Z=dFdG Z>dHdI Z?dddLdMZ@dNdO ZAdPdQ ZBdRdS ZCdTdU ZDdVdW ZEdXdY ZFddZd[ZGd\d] ZHd^d_ ZIdd`daZJddbdcZKddde ZLddgdhZMddidjZNddodpZO				$			ddqdrZPdsdt ZQdudv ZRdwdx ZS			$ddddydzd{ZTd|d} ZUd~d ZVdd ZWdddZXdd ZY						$dddZZdd Z[e.dd Z\dd Z]dd Z^dd Z_dd Z`dd Zadd Zbdd Zcdd Zddd ZedddZfdd Zgdd ZhdddZidddZjdddZkdd Zle&d$ZmdddZnddddZodd Zpdd ZqdddZrdddZsdddZtdd Zudd Zvdd ZwddĄ Zxe.ddƄ Zy  ZzS )KernelzThe base kernel class.Nzdict[str, psutil.Process]	processes	eventloopc                 C  s(   t j }|jdur|| j dS dS )z&schedule call to eventloop from IOLoopN)r   IOLoopcurrentnewadd_callbackenter_eventloop)selfchangeloopr0   r0   r1   _update_eventloopf   s   

zKernel._update_eventloopT)
allow_nonez"IPython.core.profiledir.ProfileDirzDeprecated shell_streams alias. Use shell_stream

        .. versionchanged:: 6.0
            shell_streams is deprecated. Use shell_stream.
        )helpzList[t.Any]shell_streamsr(   implementationimplementation_versionbannerc                 C  s&   t jdtdd | jd ur| jgS g S )NLKernel.shell_streams is deprecated in ipykernel 6.0. Use Kernel.shell_stream   
stacklevel)warningswarnDeprecationWarningshell_streamrK   r0   r0   r1   _shell_streams_default}   s   
zKernel._shell_streams_defaultc                 C  sH   t jdtdd t|jdkrt jdtdd |jr"|jd | _d S d S )NrU   rV   rW   r   zJKernel only supports one shell stream. Additional streams will be ignored.r   )rY   rZ   r[   lenrH   RuntimeWarningr\   )rK   rL   r0   r0   r1   _shell_streams_changed   s   zKernel._shell_streams_changedzlogging.Loggerlogidentc                 C  s   t t S r+   )r(   uuiduuid4r]   r0   r0   r1   _default_ident   s   zKernel._default_identzdict[str, object]language_infozList[dict[str, str]]
help_linkszSSet to False if you want to debug python standard and dependent libraries.
        )configzhWhether to use appnope for compatibility with OS X App Nap.

        Only affects OS X >= 10.9.
        FzDict[str, t.Any]_control_parent    bytes_control_parent_identzContextVar[dict[str, Any]]_shell_parentzContextVar[bytes]_shell_parent_identr   _shell_contextzMapping[str, bytes]_parent_identzasyncio.Lock_main_asyncio_lockc                 C  s   t jdtdd |  S )NzEKernel._parent_header is deprecated in ipykernel 6. Use .get_parent()rV   rW   )rY   rZ   r[   
get_parentr]   r0   r0   r1   _parent_header   s   zKernel._parent_headergMb@?{Gz?        a  time (in seconds) to wait for messages to arrive
        when aborting queued requests after an error.

        Requests that arrive within this window after an error
        will be cancelled.

        Increase in the event of unusually slow network
        causing significant delays,
        which can manifest as e.g. "Run all" in a notebook
        aborting some, but not all, messages after an error.
        )rj   rP   r   )
execute_requestcomplete_requestinspect_requesthistory_requestcomm_info_requestkernel_info_requestconnect_requestshutdown_requestis_complete_requestinterrupt_requestdebug_requestusage_requestcreate_subshell_requestdelete_subshell_requestlist_subshell_requestc                   s   t  jdi | tj _tj _i  _ jD ]
}t	 | j|< qi  _
 jD ]
}t	 | j
|< q(t jddg _i  _d _td _ ji  td _ jd t  _t fdd fddd	 _t  _d
S )zInitialize the kernel.	cell_metacell_idrl   shell_parentshell_parent_identc                     s    j S r+   )rn   r0   r]   r0   r1   <lambda>J  s    z!Kernel.__init__.<locals>.<lambda>c                     s      jS r+   )_get_shell_context_varrp   r0   r]   r0   r1   r   K  s    )controlshellNr0   )super__init__sysstdout_stdoutstderr_stderrshell_handlers	msg_typesgetattrcontrol_handlerscontrol_msg_typesrB   
do_execute_do_exec_accepted_paramsrk   rn   r   ro   setrp   r   rq   r&   rr   asyncioLockrs   )rK   kwargsmsg_type	__class__r]   r1   r   %  s2   






zKernel.__init__c              	     sR   | j 4 I dH  | |I dH  W d  I dH  dS 1 I dH s"w   Y  dS )zMDispatch a control request, ensuring only one message is processed at a time.N)_control_lockprocess_controlrK   msgr0   r0   r1   dispatch_controlQ  s   .zKernel.dispatch_controlc                   sB  | j sdS | j j|dd\}}z| j j|ddd}W n ty-   | jjddd Y dS w | jd| | j||d	d
 | dd	 |d }|d }| j	
|d}|du r^| jd| n%z|| j||}t|rp|I dH  W n ty   | jjddd Y nw tjdurtj  tjdurtj  | dd	| j dS )zdispatch control requestsNFcopyTcontentr   zInvalid Control Messageexc_infozControl received: %sr   channelbusyheaderr   z UNKNOWN CONTROL MESSAGE TYPE: %rzException in control handler:idle)sessionfeed_identitiesdeserialize	Exceptionrb   errordebug
set_parent_publish_statusr   r8   control_streamr3   isawaitabler   r   flushr   _publish_status_and_flush)rK   r   identsr   r   handlerresultr0   r0   r1   r   W  s>   





zKernel.process_controlc                 C  s   dS )a"  Check whether a shell-channel message should be handled

        Allows subclasses to prevent handling of certain messages (e.g. aborted requests).

        .. versionchanged:: 7
            Subclass should_handle _may_ be async.
            Base class implementation is not async.
        Tr0   )rK   streamr   r   r0   r0   r1   should_handle|  s   	zKernel.should_handlesubshell_id
str | Nonec          
        sH  t |dkr!|d jdkr!|du rd| _dS | jj|d dS | js&dS | jr5t	 | j
| jfvs5J | jj|dd\}}z| jj|ddd}W n ty\   | jjd	dd
 Y dS w | j||dd | dd |d d }|d d|ks|J | jr| jj|}n| j}|dkr|du r| j}n| jj|}|r| ||| | dd| dS | jd| | jd|d  | |||}t|r|I dH }|s| dd| | jd||d d dS | j|d}|du r| jd| n| jd|| z|   W n ty   | jjddd
 Y nw zOz||||}	t|	r/|	I dH  W n! tyB   | jjddd
 Y n tyQ   | jd Y nw W z|    W n+ tyk   | jjddd
 Y nw z|    W w  ty   | jjddd
 Y w w t!j"durt!j"#  t!j$durt!j$#  | dd| dS )zdispatch shell requestsr   r      stop abortingNFr   Tr   zInvalid Messager   r   r   r   r   r   r   rx   r   z
*** MESSAGE TYPE:%s***z   Content: %s
   --->
   r   zNot handling %s:%smsg_idzUnknown message type: %rz%s: %sz%Unable to signal in pre_handler_hook:zException in message handler:z#KeyboardInterrupt caught in kernel.z&Unable to signal in post_handler_hook:)%r_   buffer	_abortingshell_channel_threadmanagerset_subshell_abortingr   _supports_kernel_subshells	threadingcurrent_threadcontrol_threadr   r   r   rb   r   r   r   r8   $get_subshell_to_shell_channel_socketr\   get_subshell_aborting_send_abort_replyr   r   r   r3   r   r   warningpre_handler_hookKeyboardInterruptpost_handler_hookr   r   r   r   )
rK   r   r   r   r   r   abortingr   r   r   r0   r0   r1   dispatch_shell  s   





zKernel.dispatch_shellc                 C  s   t tt| _dS )z.Hook to execute before calling message handlerN)r   r	   r   saved_sigint_handlerr]   r0   r0   r1   r     s   zKernel.pre_handler_hookc                 C  s   t t| j dS )z-Hook to execute after calling message handlerN)r   r	   r   r]   r0   r0   r1   r     s   zKernel.post_handler_hookc                   sV   j dj jdu rj d dS fdd  fdd  dS )zenter eventloopzEntering eventloop %sNz Exiting as there is no eventloopc                     sp   j  urjd  d S jd  z  W n ty+   jd Y nw j  u r6  d S d S )Nzexiting eventloop %szAdvancing eventloop %sz"KeyboardInterrupt caught in kernel)rE   rb   infor   r   r   r0   )rE   schedule_nextrK   r0   r1   advance_eventloop  s   


z1Kernel.enter_eventloop.<locals>.advance_eventloopc                     s   j d jd  dS )z*Schedule the next advance of the eventloopzScheduling eventloop advancegMbP?N)rb   r   io_loop
call_laterr0   )r   rK   r0   r1   r   
  s   z-Kernel.enter_eventloop.<locals>.schedule_next)rb   r   rE   r]   r0   )r   rE   r   rK   r1   rJ     s   
zKernel.enter_eventloopc                   s   t  | _d S r+   )r   r   r   r]   r0   r0   r1   _create_control_lock  s   zKernel._create_control_lockc                 C  s   t j | _| jr| jj| jdd | jr#tj	dk r#| jj
| j nt | _| jrN| jr@| jj| j | jj| jdd n| jjtt| jddd | dd dS )z register dispatchers for streamsFr   )   
   Nstartingr   )r   rF   rG   r   r   on_recvr   r   r   version_inforI   r   r   r   r   r\   r   r   set_on_recv_callback
shell_mainshell_channel_thread_mainr'   r   r   r]   r0   r0   r1   start  s   
zKernel.startc              	     s  t  | jks
J | jj4 I dH l | jdu r$	 W d  I dH  dS | jj|dd\}}z(| jj|ddd}|d d}| jj}|	|}|dusNJ |j
|dd W n tyg   | jjddd	 Y nw W d  I dH  dS W d  I dH  dS 1 I dH sw   Y  dS )
z;Handler for shell messages received on shell_channel_threadNFr   r   r   r   zInvalid messageTr   )r   r   r   asyncio_lockr   r   r   r8   r   $get_shell_channel_to_subshell_socketsend_multipartr   rb   r   )rK   r   _msg2msg3r   subshell_managersocketr0   r0   r1   r   7  s*   

.z Kernel.shell_channel_thread_mainc              	     s   | j r+|du rt | jjksJ | j}nt | j| jjfvs#J | jj|}n	|du s1J | j}|dus:J |4 I dH  | j||dI dH  W d  I dH  dS 1 I dH s\w   Y  dS )z/Handler of shell messages for a single subshellN)r   )	r   r   r   r   parent_threadrs   r   get_subshell_asyncio_lockr   )rK   r   r   r   r0   r0   r1   r   N  s$   
.zKernel.shell_mainc                 C  s
   || _ dS )zRecord the ports that this kernel is using.

        The creator of the Kernel instance must call this methods if they
        want the :meth:`connect_request` method to return the port numbers.
        N)_recorded_ports)rK   portsr0   r0   r1   record_portsh  s   
zKernel.record_portsc                 C  s2   | j sdS | j j| jd||d|| dd dS )z-Publish the code request on the iopub stream.Nexecute_input)codeexecution_countparentrd   )r   sendiopub_socket_topic)rK   r   r   r   r0   r0   r1   _publish_execute_inputt  s   
zKernel._publish_execute_inputc                 C  s:   | j sdS | j j| jdd|i|p| || dd dS )z send status (busy/idle) on IOPubNstatusexecution_stater   r   r   r   rt   r   )rK   r  r   r   r0   r0   r1   r     s   
zKernel._publish_statusc                 C  s>   |  ||| |rt|dr| js|tj dS dS dS dS )zfsend status on IOPub and flush specified stream to ensure reply is sent before handling the next replyr   N)r   hasattrr   r   zmqPOLLOUT)rK   r  r   r   r   r0   r0   r1   r     s   z Kernel._publish_status_and_flushc                 C  s0   | j sd S | j j| jd||  | dd d S )Ndebug_eventr   r  )rK   eventr0   r0   r1   _publish_debug_event  s   
zKernel._publish_debug_eventr   c                 C  s<   |dkr|| _ || _dS | j| | j| t | _dS )a  Set the current parent request

        Side effects (IOPub messages) and replies are associated with
        the request that caused them via the parent_header.

        The parent identity is used to route input_request messages
        on the stdin channel.
        r   N)rn   rk   rp   r   ro   r   rq   )rK   rd   r   r   r0   r0   r1   r     s   	
zKernel.set_parentc                 C  s:   |du rt  jtkrd}nd}|dkr| jS | | jS )aR  Get the parent request associated with a channel.

        .. versionadded:: 6

        Parameters
        ----------
        channel : str
            the name of the channel ('shell' or 'control')

        Returns
        -------
        message : dict
            the parent message for the most recent request on the channel.
        Nr   r   )r   r   namer   rk   r   ro   )rK   r   r0   r0   r1   rt     s   zKernel.get_parentvarContextVar[T]returnr*   c                 C  s(   z|  W S  ty   | j|  Y S w )zLookup a ContextVar, falling back on the shell context

        Allows for user-launched Threads to still resolve to the shell's main context

        necessary for e.g. display from threads.
        )r8   LookupErrorrq   )rK   r  r0   r0   r1   r     s
   
zKernel._get_shell_context_varc
           
      C  s,   | j sdS | j |||| |	|||||	S )a  Send a response to the message we're currently processing.

        This accepts all the parameters of :meth:`jupyter_client.session.Session.send`
        except ``parent``.

        This relies on :meth:`set_parent` having been called for the current
        message.
        N)r   r   rt   )
rK   r   msg_or_typer   rd   bufferstrackr   metadatar   r0   r0   r1   send_response  s   zKernel.send_responsec                 C  s
   dt  iS )zRInitialize metadata.

        Run at the beginning of execution requests.
        started)now)rK   r   r0   r0   r1   init_metadata  s   zKernel.init_metadatac                 C  s   |S )zXFinish populating metadata.

        Run after completing an execution request.
        r0   )rK   r   r  reply_contentr0   r0   r1   finish_metadata  s   zKernel.finish_metadatac                   s  | j sdS z.|d }|d }|dd}|d| }|di }|dd}	|d	i }
|
d
}W n tyK   | jd | jd| Y dS w |dd}| |}|sh|  jd7  _| ||| j |||||	d}| jd ry|
|d< | jd r||d< |d d}| j	di |}t
|r|I dH }ntjtjd| j	dtdd tjdurtj  tjdurtj  | jrt| j t|}| |||}| j j|d||||d}| jd| |s|d d dkr|r|d d}| | dS dS dS dS )zhandle an execute_requestNr   r   silentFstore_historyuser_expressionsallow_stdinr  cellIdzGot bad msg: %sstop_on_errorTr   )r   r  r  r  r  r   r   r   r   r   	func_nametargetrW   execute_reply)r  rd   r  r   r0   )r   r8   r   rb   r   r  r   r   r   r   r3   r   rY   rZ   r)   formatPendingDeprecationWarningr   r   r   r   _execute_sleeptimesleepr#   r  r   r   _abort_queues)rK   r   rd   r   r   r   r  r  r  r  r   r   r  r  do_execute_argsr   r  	reply_msgr0   r0   r1   rx     s|   







	zKernel.execute_request)r   r   c                C  s   t )z4Execute user code. Must be overridden by subclasses.NotImplementedError)rK   r   r  r  r  r  r   r   r0   r0   r1   r   a  s   zKernel.do_executec                   s   | j sdS |d }|d }|d }| ||}t|r#|I dH }ntjtjd| jdtdd t	|}| j 
|d	||| dS )
zHandle a completion request.Nr   r   
cursor_posdo_completer   r   rW   complete_reply)r   r/  r3   r   rY   rZ   r)   r$  r%  r#   r   )rK   r   rd   r   r   r   r.  matchesr0   r0   r1   ry   o  s    
zKernel.complete_requestc                 C  s   g ||i ddS )+Override in subclasses to find completions.ok)r1  
cursor_endcursor_startr  r  r0   )rK   r   r.  r0   r0   r1   r/    s   zKernel.do_completec              
     s   | j sdS |d }| |d |d |ddt|dg }t|r+|I dH }ntjtj	d| jd	t
d
d t|}| j |d|||}| jd| dS )zHandle an inspect request.Nr   r   r.  detail_levelr   omit_sections
do_inspectr   r   rW   inspect_replyr  )r   r8  r8   r   r3   r   rY   rZ   r)   r$  r%  r#   r   rb   r   rK   r   rd   r   r   r  r   r0   r0   r1   rz     s(   

zKernel.inspect_requestr0   c                 C  s   di i ddS )z.Override in subclasses to allow introspection.r3  F)r  datar  foundr0   )rK   r   r.  r6  r7  r0   r0   r1   r8    s   zKernel.do_inspectc                   s   | j sdS |d }| jd	i |}t|r|I dH }ntjtjd| jdtdd t	|}| j 
|d|||}| jd| dS )
zHandle a history request.Nr   
do_historyr   r   rW   history_replyr  r0   )r   r=  r3   r   rY   rZ   r)   r$  r%  r#   r   rb   r   r:  r0   r0   r1   r{     s   
zKernel.history_requestc
           
      C  s
   dg dS )z)Override in subclasses to access history.r3  )r  historyr0   )
rK   hist_access_typeoutputrawr   r   stopnpatternuniquer0   r0   r1   r=    s   
zKernel.do_historyc                   sN   | j sdS | jr| j ni }d|d< | j |d|||}| jd| dS )zHandle a connect request.Nr3  r  connect_replyr  )r   r   r   r   rb   r   rK   r   rd   r   r   r   r0   r0   r1   r~     s   zKernel.connect_requestc                 C  sL   ddl m} g }| jr|d |r|d t| j| j| j| j| j	|dS )Nr   )_is_debugpy_availablezkernel subshellsdebugger)protocol_versionrR   rS   rh   rT   ri   supported_features)
rJ  rI  r   appendr$   rR   rS   rh   rT   ri   )rK   rI  rL  r0   r0   r1   kernel_info  s   

zKernel.kernel_infoc                   sF   | j sdS ddi}|| j | j |d|||}| jd| dS )zHandle a kernel info request.Nr  r3  kernel_info_replyr  )r   updaterN  r   rb   r   rH  r0   r0   r1   r}     s   zKernel.kernel_info_requestc                   s|   | j sdS |d }|dd t| dr# fdd| jj D }ni }t|dd}| j |d	|||}| j	d
| dS )zHandle a comm info request.Nr   target_namecomm_managerc                   s0   i | ]\}}|j  ks d u r|t|j dqS )NrQ  )rQ  r6   )r.   kvrS  r0   r1   
<dictcomp>  s
    z,Kernel.comm_info_request.<locals>.<dictcomp>r3  )commsr  comm_info_replyr  )
r   r8   r  rR  rW  itemsr6   r   rb   r   )rK   r   rd   r   r   rW  r  r   r0   rS  r1   r|     s   


zKernel.comm_info_requestc                 C  s   t jdkr| jd d S t  }t |}|r9||kr9tt dr9z	t |t W d S  t	y8   t 
|t  w t 
|t d S )Nntz*Interrupt message not supported on Windowskillpg)osr
  rb   r   getpidgetpgidr  r[  r	   OSErrorkill)rK   pidpgidr0   r0   r1   _send_interrupt_children	  s   

zKernel._send_interrupt_childrenc              
     s   | j sdS ddi}z|   W n& ty6 } zddl}d| tt|jt|d}W Y d}~nd}~ww | j j|d|||d dS )	zHandle an interrupt request.Nr  r3  r   r   )r  	tracebackenameevalueinterrupt_replyrd   )	r   rc  r_  rd  format_stackr(   type__name__r   )rK   r   rd   r   r   errrd  r0   r0   r1   r     s"   
zKernel.interrupt_requestc                   s   | j sdS | |d d }t|r|I dH }ntjtjd| jdtdd | j j	|d|||d	 | j 
d||| _|  I dH  | jd
 | jrV| jj}||j | jd | j| jj | jrz| jj| jkr|| jj}||j dS dS dS )zHandle a shutdown request.Nr   restartdo_shutdownr   r   rW   shutdown_replyrh  zStopping control ioloopzStopping shell ioloop)r   rn  r3   r   rY   rZ   r)   r$  r%  r   r   _shutdown_message_at_shutdownrb   r   r   r   rI   rC  r\   )rK   r   rd   r   r   control_io_loopshell_io_loopr0   r0   r1   r   .  s0   
zKernel.shutdown_requestc                 C  s
   d|dS )z]Override in subclasses to do things when the frontend shuts down the
        kernel.
        r3  )r  rm  r0   )rK   rm  r0   r0   r1   rn  L  s   
zKernel.do_shutdownc                   s   | j sdS |d }|d }| |}t|r|I dH }ntjtjd| jdtdd t	|}| j 
|d|||}| jd	| dS )
zHandle an is_complete request.Nr   r   do_is_completer   r   rW   is_complete_replyr  )r   rt  r3   r   rY   rZ   r)   r$  r%  r#   r   rb   r   )rK   r   rd   r   r   r   r  r+  r0   r0   r1   r   R  s    

zKernel.is_complete_requestc                 C  s   ddiS )r2  r  unknownr0   )rK   r   r0   r0   r1   rt  f  s   zKernel.do_is_completec                   s~   | j sdS |d }| |}t|r|I dH }ntjtjd| jdtdd t	|}| j 
|d|||}| jd| dS )	zHandle a debug request.Nr   do_debug_requestr   r   rW   debug_replyr  )r   rw  r3   r   rY   rZ   r)   r$  r%  r#   r   rb   r   )rK   r   rd   r   r   r  r+  r0   r0   r1   r   j  s"   

zKernel.debug_requestc                 C  s<   zt || }|durt ||W S |W S  ty   Y dS w )zGet the process metric value.Nr   )r   BaseException)rK   processr
  	attributemetric_valuer0   r0   r1   get_process_metric_value~  s   zKernel.get_process_metric_valuec           	        s  j sdS t t d}t }|g|jdd}fdd|D _t	fddj
 D |d	< t| d
r?d
nd t	 fddj
 D |d< t }|durb|dkrb||d< tjdd|d< tt  |d< j |d|||}jd| dS )zHandle a usage request.N)hostnamera  T	recursivec                   s    i | ]}|j  j|j |qS r0   )ra  rD   r8   r.   rz  r]   r0   r1   rV    s    z(Kernel.usage_request.<locals>.<dictcomp>c                   s   g | ]	}  |d dqS )cpu_percentNr}  r  r]   r0   r1   
<listcomp>      z(Kernel.usage_request.<locals>.<listcomp>
kernel_cpupssrssc                   s   g | ]	} |d  qS )memory_full_infor  r  mem_info_typerK   r0   r1   r    r  kernel_memoryrw   host_cpu_percent)logical	cpu_counthost_virtual_memoryusage_replyr  )r   r   gethostnamer\  r]  psutilProcesschildrenrD   sumr<   r  r  r  r  r6   virtual_memory_asdictr   rb   r   )	rK   r   rd   r   r  current_processall_processesr  r+  r0   r  r1   r     s6   

zKernel.usage_requestc                   s   t r+   r,  r   r0   r0   r1   rw    s   zKernel.do_debug_requestNonec                   n   | j sdS | js| jd dS t jtksJ | jj	j
j}|ddi | }| j |d||| dS )zGHandle a create subshell request.

        .. versionadded:: 7
        N*Subshells are not supported by this kernelrj  createcreate_subshell_replyr   r   rb   r   r   r   r
  r   r   r   control_to_shell_channelfrom_socket	send_json	recv_jsonr   rK   r   rd   r   control_socketreplyr0   r0   r1   r     s   zKernel.create_subshell_requestc                   s   | j sdS | js| jd dS t jtksJ z
|d }|d }W n ty5   | jd| Y dS w | j	j
jj}|d|d | }| j |d||| dS )	zGHandle a delete subshell request.

        .. versionadded:: 7
        NzKERNEL SUBSHELLS NOT SUPPORTEDr   r   zGot bad msg from parent: %sdelete)rj  r   delete_subshell_reply)r   r   rb   r   r   r   r
  r   r   r   r   r  r  r  r  r   )rK   r   rd   r   r   r   r  r  r0   r0   r1   r     s$   zKernel.delete_subshell_requestc                   r  )zEHandle a list subshell request.

        .. versionadded:: 7
        Nr  rj  listlist_subshell_replyr  r  r0   r0   r1   r     s   zKernel.list_subshell_requestc                 C  s   d| j  }| d|  S )z!prefixed topic for IOPub messagesz	kernel.%s.)rd   encode)rK   topicbaser0   r0   r1   r     s   
zKernel._topicc                 C  s4   | j j}||}|dusJ d}|j|dd dS )znPost a dummy message to the correct subshell that when handled will unset
        the _aborting flag.
        Nr   Fr   )r   r   r   r   )rK   r   r   r   r   r0   r0   r1   !_post_dummy_stop_aborting_message  s
   
z(Kernel._post_dummy_stop_aborting_messagec                   s   |d u rd _ n jj|d  jd  jr$ jj j| d S  j	r/ j
s/ j	   fdd} jrZ j j|  jd urVt jdrX j jd  d S d S d S  j| d S )NTzAborting queuec                     s    j d d _d S )NzFinishing abortF)rb   r   r   r0   r]   r0   r1   stop_aborting&  s   
z+Kernel._abort_queues.<locals>.stop_aborting_schedule_exitrv   )r   r   r   r   rb   r   r   rI   r  r\   r   r   stop_on_error_timeoutr   rE   r  r  )rK   r   r  r0   r]   r1   r)    s$   
zKernel._abort_queuesc                 C  s   | j sdS | jd|d d |d d  |d d ddd d	 }d
di}| |}| |||}|| | j j||||||d dS )z"Send a reply to an aborted requestNzAborting %s: %sr   r   r   r   r   r   _replyr  aborted)r  r   r   rd   )r   rb   r   rsplitr  r  rP  r   )rK   r   r   r   
reply_typer  mdr0   r0   r1   r   7  s     


zKernel._send_abort_replyc                 C  s   d}t |)zPRaise StdinNotImplementedError if active frontend doesn't support
        stdin.z?raw_input was called, but this frontend does not support stdin.r   r   r0   r0   r1   _no_raw_inputK  s   zKernel._no_raw_input c                 C  sR   | j s	d}t||durddl}|jdtdd | j|| | j| ddd	S )
zForward getpass to frontends

        Raises
        ------
        StdinNotImplementedError if active frontend doesn't support stdin.
        zFgetpass was called, but this frontend does not support input requests.Nr   zTThe `stream` parameter of `getpass.getpass` will have no effect when using ipykernelrV   rW   r   Tpassword)	_allow_stdinr   rY   rZ   UserWarning_input_requestr   rp   rt   )rK   promptr   r   rY   r0   r0   r1   getpassQ  s    
zKernel.getpassc                 C  s6   | j s	d}t|| jt|| | j| dddS )zForward raw_input to frontends

        Raises
        ------
        StdinNotImplementedError if active frontend doesn't support stdin.
        zHraw_input was called, but this frontend does not support input requests.r   Fr  )r  r   r  r(   r   rp   rt   )rK   r  r   r0   r0   r1   	raw_inputj  s   
zKernel.raw_inputc              
   C  s~  t jd ur
t j  t jd urt j  	 z	| jtj W n tjy8 } z|j	tj
kr3W Y d }~n d }~ww q| jd usAJ tt||d}| jj| jd|||d 	 z&t| jgg | jgd\}}}	|sj|	r{| j| j\}}
||
fdkr{W n!W n ty   d}t|d  ty   | jjddd	 Y nw qVz|
d
 d }W n ty   | jd| d}Y nw |dkrt|S )NT)r  r  input_requestrh  rv   )NNzInterrupted by userzInvalid Message:r   r   valuezBad input_reply: %sr  )r   r   r   r   stdin_socketrecv_multipartr  NOBLOCKZMQErrorerrnoEAGAINr   r#   r6   r   selectrecvr   r   rb   r   r   EOFError)rK   r  rd   r   r  er   rlistr   xlistr  r   r  r0   r0   r1   r  {  sR   



	
zKernel._input_requestc              	   C  sr   t |}|  D ]-}| jd|| z|tkr|  n|tkr&|  n|| W q	 t	j
y6   Y q	w dS )z
        Send a signal to all our children

        Like `killpg`, but does not include the current process
        (or possible parents).
        zSending %s to subprocess %sN)r   _process_childrenrb   r   r
   	terminater   r`  send_signalr  NoSuchProcess)rK   signumsig_repr/   r0   r0   r1   _signal_children  s   



zKernel._signal_childrenc              	   C  sr   t  }|jdd}tjdkr|S t }g }|D ]}zt|j}W n	 ty,   Y qw ||kr6|	| q|S )zRetrieve child processes in the kernel's process group

        Avoids:
        - including parents and self with killpg
        - including all children that may have forked-off a new group
        Tr  rZ  )
r  r  r  r\  r
  getpgrpr^  ra  r_  rM  )rK   kernel_processall_childrenkernel_pgidprocess_group_childrenchild
child_pgidr0   r0   r1   r    s    

zKernel._process_childrenc                   s   d}|   s| jd d S ttfD ],}|D ]'}|   }|s)| jd   d S | | | jd|| t|I d H  qqd S )N)rv   gQ?g?g333333?r   r   r   zKernel has no children.z.No more children, continuing shutdown routine.z?Will sleep %s sec before checking for children and retrying. %s)r  rb   r   r
   r   r  r   r(  )rK   sleepsr  delayr  r0   r0   r1   %_progressively_terminate_all_children  s(   
z,Kernel._progressively_terminate_all_childrenc                   s   zPz	|   I dH  W n ty$ } z| jd| W Y d}~nd}~ww W | jdurD| jrD| jj| j| j| dd | j	d| j | j
rP| j
tj dS dS | jdurp| jrp| jj| j| j| dd | j	d| j | j
r{| j
tj w w )zCActions taken at shutdown by the kernel, called by python's atexit.Nz,Exception during subprocesses termination %sshutdownrh  r  )r  r   rb   	exceptionrp  r   r   r   r   r   r   r   r  r  )rK   r  r0   r0   r1   rq    s8   zKernel._at_shutdownc                 C  s
   | j d uS r+   )r   r]   r0   r0   r1   r     s   
z!Kernel._supports_kernel_subshellsr+   )r   r   )r   )r  r  r  r*   )NNNFNNN)TNF)r   r0   )NNNNNF)r  r  )r   r   r  r  )r  N)r  )F){rk  
__module____qualname____doc__r   rE   rD   __annotations__r!   rN   r   r   r   profile_dirr"   r\   r   rQ   r    r^   ra   r   debug_shell_socketr   r   r   iopub_threadr  loggingLoggerrb   r   int_idr   rd   rg   rh   ri   r   tagdebug_just_my_code_darwin_app_napr  r   rk   rn   propertyru   r   r&  _poll_intervalr  rp  r   r   r   r   r   r   r   r   r   r   r   r   r   r   rJ   r   r   r   r   r   r   r   r   r	  r   rt   r   r  r  r  rx   r   ry   r/  rz   r8  r{   r=  r~   rN  r}   r|   rc  r   r   rn  r   rt  r   r}  r   rw  r   r   r   r   r   r  r)  r   r  r  r  r  r  r  r  rq  r   __classcell__r0   r0   r   r1   rC   Z   sF  
 




		

	,%b%






"Z


	
	
$



)


4rC   )Jr  
__future__r   r   r3   r  r\  r   r   r   r'  typingtre   rY   collections.abcr   contextvarsr   r   r   r   	functoolsr   r   r	   r
   r   r   threadr   platformr   jupyter_client.sessionr   r  ImportErrorr  r  IPython.core.errorr   r   tornador   traitlets.config.configurabler   traitlets.traitletsr   r   r   r   r   r   r   r   r    r!   zmq.eventloop.zmqstreamr"   ipykernel.jsonutilr#   _versionr$   iostreamr%   utilsr&   r'   r)   r  TypeVarr*   rB   rC   r0   r0   r0   r1   <module>   sX    

0

