B
    \0                 @   s  d Z ddlmZ ddlmZ ddlmZ yddlmZ W n  ek
rX   ddl	mZ Y nX 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 y
ejZW n ek
r   ejZY nX ye W n ek
r   eZY nX dd ZG dd deZdS )zeImplements a fully blocking kernel client.

Useful for test suites and blocking terminal interfaces.
    )print_function)partial)getpass)EmptyN)Type)	HBChannel)KernelClient   )ZMQSocketChannelc                s^    fdd} j s|S  j dd\}}| g}d|krD|d |d d||_ |S )	Nc                s>   | dd}| dd } | f||}|s0|S | j||dS )NreplyFtimeout)r   )pop_recv_reply)selfargskwargsr   r   msg_id)meth =lib/python3.7/site-packages/jupyter_client/blocking/client.pywrapped(   s    zreqrep.<locals>.wrappedzReturns
r	   Z
Parametersz/
        Parameters
        ----------
        a  
        reply: bool (default: False)
            Whether to wait for and return reply
        timeout: float or None (default: None)
            Timeout to use when waiting for a reply

        Returns
        -------
        msg_id: str
            The msg_id of the request sent, if reply=False (default)
        reply: dict
            The reply message for this request, if reply=True
    
)__doc__splitstripappendjoin)r   r   Zbasedoc_partsr   )r   r   reqrep'   s    	
r   c               @   s   e Zd ZdZdddZeeZeeZeeZ	ee
ZdddZeejZeejZeejZeejZeejZeejZeejZdd Zd	d
 Zdd ZdddZdS )BlockingKernelClientzA KernelClient with blocking APIs
    
    ``get_[channel]_msg()`` methods wait for and return messages on channels,
    raising :exc:`queue.Empty` if no message arrives within ``timeout`` seconds.
    Nc             C   s  |dkrt d}nt | }ddlm} t| j|sfx.|  sdt |krXtd| td q8W xny| j	j
ddd	}W n tk
r   Y nX |d
 dkr| | P |  stdt |krhtd| qhW x2y| jj
ddd	}W q tk
r   P Y qX qW dS )aH  Waits for a response when a client is blocked
        
        - Sets future time for timeout
        - Blocks on shell channel until a message is received
        - Exit if the kernel has died
        - If client times out before receiving a message from the kernel, send RuntimeError
        - Flush the IOPub channel
        Ninf   )KernelManagerz?Kernel didn't respond to heartbeats in %d seconds and timed outg?Tr	   )blockr   msg_typeZkernel_info_replyz*Kernel died before replying to kernel_infoz#Kernel didn't respond in %d seconds)floattimeZmanagerr#   
isinstanceparentis_aliveRuntimeErrorZsleepshell_channelget_msgr   Z_handle_kernel_info_replyiopub_channel)r   r   Zabs_timeoutr#   msgr   r   r   wait_for_readyT   s4    	


z#BlockingKernelClient.wait_for_readyc             C   sv   |dk	rt  | }x^|dk	r,td|t   }y| j|d}W n tk
rX   tdY nX |d d|krnq|S dS )z0Receive and return the reply for a given requestNr   )r   zTimeout waiting for replyparent_headerr   )	monotonicmaxZget_shell_msgr   TimeoutErrorget)r   r   r   deadliner   r   r   r   r      s    
z BlockingKernelClient._recv_replyc             C   s   |d }| ddrt}ntjdk r*t}nt}y||d }W n6 tk
rV   d}Y n  tk
rt   tj	d dS X | j
 s| j s| | dS )	zHandle an input requestcontentZpasswordF)   promptr   N)r5   r   sysversion_infoZ	raw_inputinputEOFErrorKeyboardInterruptstdoutwritestdin_channelZ	msg_readyr,   )r   r/   r7   r9   Zraw_datar   r   r   _stdin_hook_default   s    
z(BlockingKernelClient._stdin_hook_defaultc             C   s   |d d }|d }|dkr:t t|d }||d  nB|dkr\tj|d d	d
 n |dkr|td|d tjd dS )z/Default hook for redisplaying plain-text outputheaderr%   r7   streamnametext)display_dataexecute_resultdataz
text/plain errorr   	traceback)fileN)getattrr;   rA   r@   r5   printr   stderr)r   r/   r%   r7   rE   r   r   r   _output_hook_default   s    z)BlockingKernelClient._output_hook_defaultc             C   s:   |d d }|dkr,|j |||d |d n
| | dS )z]Output hook when running inside an IPython kernel

        adds rich output support.
        rD   r%   )rH   rI   rL   r7   )r)   N)sendrR   )r   sessionsocketr1   r/   r%   r   r   r   _output_hook_kernel   s    z(BlockingKernelClient._output_hook_kernelFTc
             C   s  | j  std|dkr | j}|r6| j s6td| j||||||d}
|	dkrZ| j}	|dkrdtjkrddl	m
} | }t|dd	}|rt| j|jj|jj|jj}|dkr| j}|dk	rt | }nd}t }| j j}||tj |r| jj}||tj nd}x|dk	r4td|t  }d
| }t||}|sPtd||krt| jjdd}|	| q||krq| j jdd}|d d|
krq|| |d d dkr|d d dkrP qW |dk	rtd|t  }| j|
|dS )a!  Execute code in the kernel interactively

        Output will be redisplayed, and stdin prompts will be relayed as well.
        If an IPython kernel is detected, rich output will be displayed.

        You can pass a custom output_hook callable that will be called
        with every IOPub message that is produced instead of the default redisplay.

        .. versionadded:: 5.0

        Parameters
        ----------
        code : str
            A string of code in the kernel's language.

        silent : bool, optional (default False)
            If set, the kernel will execute the code as quietly possible, and
            will force store_history to be False.

        store_history : bool, optional (default True)
            If set, the kernel will store command history.  This is forced
            to be False if silent is True.

        user_expressions : dict, optional
            A dict mapping names to expressions to be evaluated in the user's
            dict. The expression values are returned as strings formatted using
            :func:`repr`.

        allow_stdin : bool, optional (default self.allow_stdin)
            Flag for whether the kernel can send stdin requests to frontends.

            Some frontends (e.g. the Notebook) do not support stdin requests.
            If raw_input is called from code executed from such a frontend, a
            StdinNotImplementedError will be raised.

        stop_on_error: bool, optional (default True)
            Flag whether to abort the execution queue, if an exception is encountered.

        timeout: float or None (default: None)
            Timeout to use when waiting for a reply

        output_hook: callable(msg)
            Function to be called with output messages.
            If not specified, output will be redisplayed.

        stdin_hook: callable(msg)
            Function to be called with stdin_request messages.
            If not specified, input/getpass will be called.

        Returns
        -------
        reply: dict
            The reply message for this request
        z/IOPub channel must be running to receive outputNz,stdin channel must be running to allow input)silentstore_historyuser_expressionsallow_stdinstop_on_errorIPythonr   )get_ipythonZkernelFg     @@zTimeout waiting for output)r   r1   r   rD   r%   Zstatusr7   Zexecution_stateZidle) r.   r*   r+   rZ   rB   executerC   r;   modulesr\   r]   rO   r   rV   Zdisplay_pubrT   Z
pub_socketr1   rR   r2   zmqZPollerrU   registerZPOLLINr3   dictZpollr4   r-   r5   r   )r   coderW   rX   rY   rZ   r[   r   Zoutput_hookZ
stdin_hookr   r]   ZipZ	in_kernelr6   Z
timeout_msZpollerZiopub_socketZstdin_socketZeventsZreqr/   r   r   r   execute_interactive   sx    :






z(BlockingKernelClient.execute_interactive)N)N)FTNNTNNN)__name__
__module____qualname__r   r0   r   r
   Zshell_channel_classZiopub_channel_classZstdin_channel_classr   Zhb_channel_classr   r   r   r^   historyZcompleteinspectZkernel_infoZ	comm_infoZshutdownrC   rR   rV   rd   r   r   r   r   r    M   s(   
2







  r    )r   Z
__future__r   	functoolsr   r   Zqueuer   ImportErrorZQueuer;   r'   r`   Z	traitletsr   Zjupyter_client.channelsr   Zjupyter_client.clientr   Zchannelsr
   r2   AttributeErrorr4   	NameErrorr+   r   r    r   r   r   r   <module>   s0   

&