B
    U[H                 @   sB  d Z ddlZddlmZ ddlm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mZ ddlmZ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 d
dlmZ d
dl m!Z! yddl"m#Z# W n e$k
r   dZ#Y nX yddl%m&Z'm(Z) dZ*W n e$k
r   dZ*Y nX dZ+G dd deZ,G dd de,ZdS )z!The IPython kernel implementation    N)contextmanager)partial)release)builtin_modPY3unicode_typesafe_unicode)token_at_cursorline_at_cursor)gen)InstanceTypeAnyListBool   )CommManager)Kernel)ZMQInteractiveShell)_asyncio_runner)rectify_completionsprovisionalcompleterTFZ_jupyter_types_experimentalc            
       s  e Zd ZedddZeeZedddj	ddZ
e Zdd Zeed	dd
Zdd Ze Ze Z fddZeddejd	d  dddddddddddddddddddgj	ddZdZejZd ej d! d"dejd! d#d$erd%nd d d&d'Zed(d) Z  fd*d+Z! fd,d-Z" fd.d/Z#d0d1 Z$dNd3d4Z%d5d6 Z&ed7d8 Z'e'j(d9d8 Z'e)d:d; Z*e+j,dOd<d=Z-d>d? Z.d@dA Z/dPdBdCZ0dQdDdEZ1dFdG Z2dHdI Z3dJdK Z4dLdM Z5  Z6S )RIPythonKernelz1IPython.core.interactiveshell.InteractiveShellABCT)
allow_nonezUSet this flag to False to deactivate the use of experimental IPython completion APIs.)help)Zconfigc             C   s   | j d k	r|| j _d S )N)shelluser_module)selfnameoldnew r!   1lib/python3.7/site-packages/ipykernel/ipkernel.py_user_module_changed,   s    
z"IPythonKernel._user_module_changedN)argsr   c             C   s    | j d k	r|| j _| j   d S )N)r   user_nsZinit_user_ns)r   r   r   r    r!   r!   r"   _user_ns_changed1   s    
zIPythonKernel._user_ns_changedc                s   t t| jf | | jj| | j| j| j| d| _| j	| jj
_	| j| jj
_| d| jj
_| j	| jj_	| j| jj_t| | d| _| jj| j dddg}x|D ]}t| j|| j|< qW d S )N)parentprofile_dirr   r%   kernelZexecute_result)r'   r)   Z	comm_openZcomm_msgZ
comm_close)superr   __init__shell_classinstancer(   r   r%   r   sessiondisplayhookiopub_socketZ
pub_socket_topicZtopicZdisplay_pubr   Zcomm_managerZconfigurablesappendgetattrZshell_handlers)r   kwargsZcomm_msg_typesZmsg_type)	__class__r!   r"   r+   ;   s     


zIPythonKernel.__init__zPython Referencezhttps://docs.python.org/%i.%i   )textZurlzIPython Referencez&https://ipython.org/documentation.htmlzNumPy Referencez+https://docs.scipy.org/doc/numpy/reference/zSciPy Referencez+https://docs.scipy.org/doc/scipy/reference/zMatplotlib Referencez$https://matplotlib.org/contents.htmlzSymPy Referencez'http://docs.sympy.org/latest/index.htmlzpandas Referencez-https://pandas.pydata.org/pandas-docs/stable/ZipythonZpythonr   ztext/x-python)r   versionz	ipython%d   z.py)r   r8   ZmimetypeZcodemirror_modeZpygments_lexerZnbconvert_exporterZfile_extensionc             C   s   | j jS )N)r   banner)r   r!   r!   r"   r:      s    zIPythonKernel.bannerc                s   d| j _tt|   d S )NF)r   exit_nowr*   r   start)r   )r5   r!   r"   r<      s    zIPythonKernel.startc                s"   t t| || | j| dS )zmOverridden from parent to tell the display hook and output streams
        about the parent message.
        N)r*   r   
set_parentr   )r   identr'   )r5   r!   r"   r=      s    zIPythonKernel.set_parentc                s&   t t| |}|d| jd |S )zVInitialize metadata.

        Run at the beginning of each execution request.
        T)dependencies_metZengine)r*   r   init_metadataupdater>   )r   r'   Zmd)r5   r!   r"   r@      s
    zIPythonKernel.init_metadatac             C   s0   |d |d< |d dkr,|d dkr,d|d< |S )zXFinish populating metadata.

        Run after completing an execution request.
        statuserrorenameZUnmetDependencyFr?   r!   )r   r'   metadatareply_contentr!   r!   r"   finish_metadata   s    zIPythonKernel.finish_metadataFc                sX   | _ trtj _ jt_n(tj _tj _ jt_d fdd	t_tj _ jt_dS )zZForward raw_input and getpass to the current frontend.

        via input_request
         c                s   t  | S )N)eval	raw_input)prompt)r   r!   r"   <lambda>   s    z.IPythonKernel._forward_input.<locals>.<lambda>N)rH   )	Z_allow_stdinr   r   input_sys_raw_inputrJ   _sys_eval_inputgetpass_save_getpass)r   allow_stdinr!   )r   r"   _forward_input   s    
zIPythonKernel._forward_inputc             C   s*   t r| jt_n| jt_| jt_| jt_dS )zRestore raw_input, getpassN)r   rN   r   rM   rJ   rO   rQ   rP   )r   r!   r!   r"   _restore_input   s
    
zIPythonKernel._restore_inputc             C   s   | j jS )N)r   execution_count)r   r!   r!   r"   rU      s    zIPythonKernel.execution_countc             C   s   d S )Nr!   )r   valuer!   r!   r"   rU      s    c          
   #   sl   t  dd }t|| |t|  fdd}ttj|}z
dV  W dttj| X dS )aP  ContextManager for capturing SIGINT and cancelling a future

        SIGINT raises in the event loop when running async code,
        but we want it to halt a coroutine.

        Ideally, it would raise KeyboardInterrupt,
        but this turns it into a CancelledError.
        At least it gets a decent traceback to the user.
        c             S   s    |   s|  rd S |   d S )N)	cancelleddoneZcancel)fZ_ignoredr!   r!   r"   cancel_unless_done   s    z;IPythonKernel._cancel_on_sigint.<locals>.cancel_unless_donec                 s   fdd} j | d S )Nc                  s"      s  rd S  d d S )Nr   )rW   rX   Z
set_resultr!   )sigint_futurer!   r"   set_sigint_result   s    zQIPythonKernel._cancel_on_sigint.<locals>.handle_sigint.<locals>.set_sigint_result)Zio_loopZadd_callback)r$   r\   )r   r[   r!   r"   handle_sigint   s    z6IPythonKernel._cancel_on_sigint.<locals>.handle_sigintN)asyncioZFutureZadd_done_callbackr   signalSIGINT)r   ZfuturerZ   r]   Zsave_sigintr!   )r   r[   r"   _cancel_on_sigint   s    	
zIPythonKernel._cancel_on_sigintc          	   #   s  | j  | | i }t dr6t dr6 j} j}ndd }tj fdd}zltr||r jtkrt	
  r||||d}	t	|	}
| |
 |
V }W d Q R X n j|||d}W d |   X |jd k	r|j}n|j}|jrd|d	< nJd
|d	< | jpg tt|jt|d t| j| jdd}||d<  jd |d< d|krj| jdd|d  |d	 dkr  |pi |d< ni |d<  j!" |d<  j!#  |S )Nrun_cell_asyncshould_run_asyncc             S   s   dS )NFr!   )Zcellr!   r!   r"   rL     s    z*IPythonKernel.do_execute.<locals>.<lambda>c                 s    j | |S )N)run_cell)r$   r4   )r   r!   r"   rd     s    z*IPythonKernel.do_execute.<locals>.run_cell)store_historysilentokrB   rC   )	tracebackrD   evalueZexecute)engine_uuid	engine_idmethodengine_infor   rU   rh   z Exception in execute request:
%s
user_expressionsZpayload)$r   rS   hasattrrb   rc   r   	coroutiner   Zloop_runnerr^   Zget_event_loopZ
is_runningZensure_futurera   rd   rT   Zerror_before_execZerror_in_execZsuccessrA   _last_tracebackr   type__name__r   dictr>   int_idrU   loginfojoinro   Zpayload_managerZread_payloadZclear_payload)r   coderf   re   ro   rR   rF   rd   rc   coroZcoro_futureZreserre_infor!   )r   r"   
do_execute   sR    









zIPythonKernel.do_executec             C   sh   t r| jr| ||S |d kr&t|}t||\}}|| }| jd||\}}|||t| i ddS )NrH   rg   )matches
cursor_endcursor_startrE   rB   )_use_experimental_60_completionuse_experimental_completions_experimental_do_completelenr
   r   Zcomplete)r   rz   
cursor_poslineoffsetZline_cursorZtxtr   r!   r!   r"   do_completeZ  s    

zIPythonKernel.do_completec       
   
   C   s   |dkrt |}t T | jj||}tt||}g }x*|D ]"}|t|j	|j
|j|jd q@W W dQ R X |r|d j	}|d j
}dd |D }	n|}|}g }	|	||t|iddS )zE
        Experimental completions from IPython, using Jedi. 
        N)r<   endr7   rs   r   c             S   s   g | ]
}|j qS r!   )r7   ).0cr!   r!   r"   
<listcomp>  s    z;IPythonKernel._experimental_do_complete.<locals>.<listcomp>rg   )r   r   r   rE   rB   )r   _provisionalcompleterr   Z	Completercompletionslist_rectify_completionsr2   ru   r<   r   r7   rs   _EXPERIMENTAL_KEY_NAME)
r   rz   r   Zraw_completionsr   compscompser   r!   r!   r"   r   m  s0    


z'IPythonKernel._experimental_do_completec             C   s   t ||}ddi}i |d< i |d< y<|d | jj||d | jjsT|d d d|d< W n tk
rz   d	|d< Y nX |S )
NrB   rg   datarE   )detail_levelz	text/htmlTfoundF)r	   rA   r   Zobject_inspect_mimeZenable_html_pagerpopKeyError)r   rz   r   r   r   rF   r!   r!   r"   
do_inspect  s    

zIPythonKernel.do_inspectc
             C   sv   |dkr | j jj|||dd}
nH|dkrB| j jj|||||d}
n&|dkrd| j jj|||||	d}
ng }
dt|
d	S )
NtailT)rawoutputZinclude_latestrange)r   r   search)r   r   nuniquerg   )rB   history)r   Zhistory_managerZget_tailZ	get_ranger   r   )r   Zhist_access_typer   r   r.   r<   stopr   patternr   Zhistr!   r!   r"   
do_history  s    
zIPythonKernel.do_historyc             C   s   d| j _td|dS )NTrg   )rB   restart)r   r;   ru   )r   r   r!   r!   r"   do_shutdown  s    zIPythonKernel.do_shutdownc             C   s2   | j j|\}}d|i}|dkr.d| |d< |S )NrB   Z
incomplete indent)r   Zinput_splitterZcheck_complete)r   rz   rB   Zindent_spacesrr!   r!   r"   do_is_complete  s
    zIPythonKernel.do_is_completec          
   C   s  ddl m}m} | j}y|j}dt|dd d }	|||dd\}
}}t|
dd	}|	d	 }|	d
 }|	d }|	d }||
|||||d i}|| d||||f }zt	||j
|j ||}W d x|D ]}|| qW X ||| jj| jjd}W n tk
r } z|  |jpg tt|jt|d}t| j| jdd}||d< | j| jd|| dd | jdd|d  g }d|d< W d d }~X Y n
X ddi}||fS )Nr   )serialize_objectunpack_apply_message_-rH   F)copyrt   rY   r$   r4   resultz%s = %s(*%s,**%s))buffer_thresholditem_threshold)rh   rD   ri   Zapply)rj   rk   rl   rm   rC   )r>   zException in apply request:
%srn   rh   rB   rg   ) Z	serializer   r   r   r%   strreplacer3   rA   execZuser_global_nsgetr   r.   r   r   BaseExceptionZshowtracebackrr   r   rs   rt   r   ru   r>   rv   Zsend_responser0   r1   rw   rx   ry   )r   ZcontentZbufsZmsg_idZreply_metadatar   r   r   ZworkingprefixrY   r$   r4   fnameargnameZ	kwargnameZ
resultnamensrz   r   keyZ
result_bufr   rF   r}   r!   r!   r"   do_apply  sH    


zIPythonKernel.do_applyc             C   s   | j d tddS )NFrg   )rB   )r   resetru   )r   r!   r!   r"   do_clear  s    zIPythonKernel.do_clear)F)TNF)r   )r   r   NNNF)7rt   
__module____qualname__r   r   r   r   r,   r   tagr   r   r   r#   ru   r%   r&   rN   rO   r+   r   sysversion_infoZ
help_linksimplementationr   r8   Zimplementation_versionsplitr   Zlanguage_infopropertyr:   r<   r=   r@   rG   rS   rT   rU   setterr   ra   r   rq   r~   r   r   r   r   r   r   r   r   __classcell__r!   r!   )r5   r"   r   "   sz   

/ X$
 
7r   c                   s   e Zd Z fddZ  ZS )r   c                s*   dd l }|dt tt| j|| d S )Nr   z@Kernel is a deprecated alias of ipykernel.ipkernel.IPythonKernel)warningswarnDeprecationWarningr*   r   r+   )r   r$   r4   r   )r5   r!   r"   r+     s    zKernel.__init__)rt   r   r   r+   r   r!   r!   )r5   r"   r     s   r   )-__doc__r^   
contextlibr   	functoolsr   rP   r_   r   ZIPython.corer   Zipython_genutils.py3compatr   r   r   r   ZIPython.utils.tokenutilr	   r
   Ztornador   Z	traitletsr   r   r   r   r   Zcommr   Z
kernelbaser   Z
KernelBaseZzmqshellr   ZIPython.core.interactiveshellr   ImportErrorZIPython.core.completerr   r   r   r   r   r   r   r!   r!   r!   r"   <module>   s:   

   e