B
    íº]\BL  ã               @   sÐ   d Z ddlmZ ddlmZ yddlmZ W n  ek
rL   ddlmZ Y nX ddl	m
Z
mZmZmZ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 G dd„ deƒZdZG dd„ deƒZddd„ZdS )zQModule containing a preprocessor that executes the code cells
and updates outputsé    )Údedent)Úcontextmanager)ÚEmpty)	ÚListÚUnicodeÚBoolÚEnumÚAnyÚTypeÚDictÚIntegerÚdefault)Úoutput_from_msgé   )ÚPreprocessoré   )ÚConversionExceptionc                   s<   e Zd ZdZ‡ fdd„Zdd„ Zdd„ Zedd	„ ƒZ‡  Z	S )
ÚCellExecutionErrorzâ
    Custom exception to propagate exceptions that are raised during
    notebook execution to the caller. This is mostly useful when
    using nbconvert as a library, since it allows to deal with
    failures gracefully.
    c                s   t t| ƒ |¡ || _d S )N)Úsuperr   Ú__init__Ú	traceback)Úselfr   )Ú	__class__© ú>lib/python3.7/site-packages/nbconvert/preprocessors/execute.pyr      s    zCellExecutionError.__init__c             C   s"   |   ¡ }t|tƒs| dd¡}|S )NÚutf8Úreplace)Ú__unicode__Ú
isinstanceÚstrÚencode)r   Úsr   r   r   Ú__str__"   s    
zCellExecutionError.__str__c             C   s   | j S )N)r   )r   r   r   r   r   (   s    zCellExecutionError.__unicode__c          	   C   s8   d  | dg ¡¡}| tj||| dd¡| dd¡dƒS )zvInstantiate from a code cell object and a message contents
        (message is either execute_reply or error)
        Ú
r   Úenamez<Error>ÚevalueÚ )Úcellr   r$   r%   )ÚjoinÚgetÚexec_err_msgÚformat)Úclsr'   ÚmsgÚtbr   r   r   Úfrom_cell_and_msg+   s    

z$CellExecutionError.from_cell_and_msg)
Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   r"   r   Úclassmethodr/   Ú__classcell__r   r   )r   r   r      s
   r   z‰An error occurred while executing the following cell:
------------------
{cell.source}
------------------

{traceback}
{ename}: {evalue}
c                   sŒ  e Zd ZdZeddedƒdjddZeddedƒd	jddZ	e
d
edƒdjddZededƒdjddZe
d
edƒdjddZe
d
edƒdjddZeeƒ ƒZededƒdjddZe
d
edƒdjddZedd
edƒdjddZeddgdedƒdjddZedddZedƒdd„ ƒZeedƒdZd d!„ Zed/d"d#„ƒZd0‡ fd$d%„	Z d&d'„ Z!d(d)„ Z"d1d*d+„Z#d2d-d.„Z$‡  Z%S )3ÚExecutePreprocessorz.
    Executes all the cells in a notebook
    é   TaO  
            The time to wait (in seconds) for output from executions.
            If a cell execution takes longer, an exception (TimeoutError
            on python 3+, RuntimeError on python 2) is raised.

            `None` or `-1` will disable the timeout. If `timeout_func` is set,
            it overrides `timeout`.
            )Ú
allow_noneÚhelp)ÚconfigNaX  
            A callable which, when given the cell source as input,
            returns the time to wait (in seconds) for output from cell
            executions. If a cell execution takes longer, an exception
            (TimeoutError on python 3+, RuntimeError on python 2) is
            raised.

            Returning `None` or `-1` will disable the timeout for the cell.
            Not setting `timeout_func` will cause the preprocessor to
            default to using the `timeout` trait for all cells. The
            `timeout_func` trait overrides `timeout` if it is not `None`.
            )Údefault_valuer8   r9   Fz·
            If execution of a cell times out, interrupt the kernel and
            continue executing other cells rather than throwing an error and
            stopping.
            )r9   é<   z¢
            The time to wait (in seconds) for the kernel to start.
            If kernel startup takes longer, a RuntimeError is
            raised.
            aq  
            If `False` (default), when a cell raises an error the
            execution is stopped and a `CellExecutionError`
            is raised.
            If `True`, execution errors are ignored and the execution
            is continued until the end of the notebook. Output from
            exceptions is included in the cell output in both cases.
            a  
            If False (default), errors from executing the notebook can be
            allowed with a `raises-exception` tag on a single cell, or the
            `allow_errors` configurable option for all cells. An allowed error
            will be recorded in notebook output, and execution will continue.
            If an error occurs when it is not explicitly allowed, a
            `CellExecutionError` will be raised.
            If True, `CellExecutionError` will be raised for any error that occurs
            while executing the notebook. This overrides both the
            `allow_errors` option and the `raises-exception` cell tag.
            r&   z‹
            Name of kernel to use to execute the cells.
            If not set, use the kernel_spec embedded in the notebook.
            a  
            If `False` (default), then the kernel will continue waiting for
            iopub messages until it receives a kernel idle message, or until a
            timeout occurs, at which point the currently executing cell will be
            skipped. If `True`, then an error will be raised after the first
            timeout. This option generally does not need to be used, but may be
            useful in contexts where there is the possibility of executing
            notebooks with memory-consuming infinite loops.
            é   a  
            The time to wait (in seconds) for IOPub output. This generally
            doesn't need to be set, but on some slow networks (such as CI
            systems) the default timeout might not be long enough to get all
            messages.
            ZgracefulÚ	immediatea  
            If `graceful` (default), then the kernel is given time to clean
            up after executing all cells, e.g., to execute its `atexit` hooks.
            If `immediate`, then the kernel is signaled to immediately
            terminate.
            )r;   r9   z The kernel manager class to use.)r:   r9   Úkernel_manager_classc             C   s2   yddl m} W n tk
r,   tdƒ‚Y nX |S )zBUse a dynamic default to avoid importing jupyter_client at startupr   )ÚKernelManagerzW`nbconvert --execute` requires the jupyter_client package: `pip install jupyter_client`)Zjupyter_clientr@   ÚImportError)r   r@   r   r   r   Ú_kernel_manager_class_defaultÊ   s
    z1ExecutePreprocessor._kernel_manager_class_defaultaP  
              mapping of locations of outputs with a given display_id
              tracks cell index and output index within cell.outputs for
              each appearance of the display_id
              {
                   'display_id': {
                  cell_idx: [output_idx,]
                   }
              }
              c             K   s    | j s | jj di ¡ dd¡| _ | j| j | jd}|jf d| ji|—Ž | ¡ }| 	¡  y|j
| jd W n& tk
r   | ¡  | ¡  ‚ Y nX d|_||fS )a9  Creates a new kernel manager and kernel client.

        Parameters
        ----------
        kwargs :
            Any options for `self.kernel_manager_class.start_kernel()`. Because
            that defaults to KernelManager, this will likely include options
            accepted by `KernelManager.start_kernel()``, which includes `cwd`.

        Returns
        -------
        km : KernelManager
            A kernel manager as created by self.kernel_manager_class.
        kc : KernelClient
            Kernel client as created by the kernel manager `km`.
        Z
kernelspecÚnameZpython)Úkernel_namer:   Úextra_arguments)ÚtimeoutF)rD   ÚnbÚmetadatar)   r?   r:   Ústart_kernelrE   ÚclientÚstart_channelsÚwait_for_readyÚstartup_timeoutÚRuntimeErrorÚstop_channelsÚshutdown_kernelÚallow_stdin)r   ÚkwargsÚkmÚkcr   r   r   Ústart_new_kernelà   s     
z$ExecutePreprocessor.start_new_kernelc          
   c   s:  |  di ¡  dd¡pd}|| _i | _|dkr| j|d\| _| _z|| j| jfV  W d| j ¡  | jj| jdkd xdD ]}t| |ƒ qzW X n¦|| _|j	s²|j
f d	| jit—Ž | ¡ | _| j ¡  y| jj| jd
 W n  tk
rú   | j ¡  ‚ Y nX d| j_z|| j| jfV  W dxdD ]}t| |ƒ q W X dS )aj  
        Context manager for setting up the class to execute a notebook.

        The assigns `nb` to `self.nb` where it will be modified in-place. It also creates
        and assigns the Kernel Manager (`self.km`) and Kernel Client(`self.kc`).

        It is intended to yield to a block that will execute codeself.

        When control returns from the yield it stops the client's zmq channels, shuts
        down the kernel, and removes the now unused attributes.

        Parameters
        ----------
        nb : NotebookNode
            Notebook being executed.
        resources : dictionary
            Additional resources used in the conversion process. For example,
            passing ``{'metadata': {'path': run_path}}`` sets the
            execution path to ``run_path``.
        km : KernerlManager (optional)
            Optional kernel manaher. If none is provided, a kernel manager will
            be created.

        Returns
        -------
        nb : NotebookNode
            The executed notebook.
        resources : dictionary
            Additional resources used in the conversion process.
        rH   Úpathr&   N)Úcwdr>   )Znow)rG   rS   rT   rE   )rF   F)r)   rG   Ú_display_id_maprU   rS   rT   rO   rP   ÚdelattrZ
has_kernelrI   rE   rR   rJ   rK   rL   rM   rN   rQ   )r   rG   Ú	resourcesrS   rV   Úattrr   r   r   Úsetup_preprocessor  s4     





z&ExecutePreprocessor.setup_preprocessorc          	      sn   | j |||dP | j d| j ¡ tt| ƒ ||¡\}}|  | j 	¡ ¡}|d d |j
d< W dQ R X ||fS )a  
        Preprocess notebook executing each code cell.

        The input argument `nb` is modified in-place.

        Parameters
        ----------
        nb : NotebookNode
            Notebook being executed.
        resources : dictionary
            Additional resources used in the conversion process. For example,
            passing ``{'metadata': {'path': run_path}}`` sets the
            execution path to ``run_path``.
        km: KernelManager (optional)
            Optional kernel manager. If none is provided, a kernel manager will
            be created.

        Returns
        -------
        nb : NotebookNode
            The executed notebook.
        resources : dictionary
            Additional resources used in the conversion process.
        )rS   z"Executing notebook with kernel: %sÚcontentZlanguage_infoN)r\   ÚlogÚinforD   r   r6   Ú
preprocessÚ_wait_for_replyrT   Zkernel_inforH   )r   rG   rZ   rS   Zinfo_msg)r   r   r   r`   F  s    zExecutePreprocessor.preprocessc             C   s¨   |j dks|j ¡ s||fS |  ||¡\}}||_| jpHd|j dg ¡k}| jsT|s x"|D ]}|j	dkrZt
 ||¡‚qZW |dk	r |d d dkr t
 ||d ¡‚||fS )z}
        Executes a single code cell. See base.py for details.

        To execute all cells see :meth:`preprocess`.
        Úcodezraises-exceptionZtagsÚerrorNr]   Ústatus)Z	cell_typeÚsourceÚstripÚrun_cellÚoutputsÚallow_errorsrH   r)   Úforce_raise_errorsZoutput_typer   r/   )r   r'   rZ   Ú
cell_indexZreplyrh   Zcell_allows_errorsÚoutr   r   r   Úpreprocess_cellh  s    


z#ExecutePreprocessor.preprocess_cellc       	      C   sÖ   || j kr | j d|| j ¡ dS |d d dkr<d|d d< yt|ƒ}W n( tk
rp   | j d|d  ¡ dS X x^| j |  ¡ D ]L\}}| jd | }|d	 }x,|D ]$}|d
 || d
< |d || d< q¦W q‚W dS )z&Update outputs with a given display_idzdisplay id %r not in %sNÚheaderÚmsg_typeÚupdate_display_dataÚdisplay_datazunhandled iopub msg: Zcellsrh   ÚdatarH   )rX   r^   Údebugr   Ú
ValueErrorrc   ÚitemsrG   )	r   Ú
display_idr-   rl   Zcell_idxZoutput_indicesr'   rh   Z
output_idxr   r   r   Ú_update_display_id  s     

z&ExecutePreprocessor._update_display_idc             C   sÜ   xÖyH| j d k	r"|d k	r"|   |¡}n| j}|r4|dk r8d }| jjj|d}W np tk
rº   | j d| j ¡ | jrŒ| j d¡ | j	 
¡  P n*yt}W n tk
r¬   t}Y nX |dƒ‚Y nX |d  d¡|kr|S qqW d S )Nr   )rF   z(Timeout waiting for execute reply (%is).zInterrupting kernelzCell execution timed outÚparent_headerÚmsg_id)Útimeout_funcrF   rT   Zshell_channelÚget_msgr   r^   rc   Úinterrupt_on_timeoutrS   Zinterrupt_kernelÚTimeoutErrorÚ	NameErrorrN   r)   )r   ry   r'   rF   r-   Z	exceptionr   r   r   ra   •  s.    

z#ExecutePreprocessor._wait_for_replyr   c             C   s  | j  |j¡}| j d|j¡ |  ||¡}g  }|_xÂy| j jj| j	d}W n2 t
k
r€   | j d¡ | jrztdƒ‚nP Y nX |d  d¡|kr–q8|d }| j d|¡ |d }d	|krÈ|d	 |d	< |d
krä|d dkr8P nq8n`|dkrðq8nT|dkr6g |d d …< x*| j ¡ D ]\}	}
||
krg |
|< qW q8n| d¡rDq8d }	|dkrˆ|d  di ¡ dd ¡}	|	r||  |	|¡ |dkrˆq8yt|ƒ}W n( tk
r¼   | j d| ¡ w8Y nX |	rì| j |	i ¡}
|
 |g ¡}| t|ƒ¡ | |¡ q8W ||fS )NzExecuting cell:
%s)rF   z Timeout waiting for IOPub outputrx   ry   ro   z
output: %sr]   Zexecution_countrd   Zexecution_stateZidleZexecute_inputZclear_outputZcomm>   Úexecute_resultrq   rp   Z	transientrv   rp   zunhandled iopub msg: )rT   Zexecutere   r^   rs   ra   rh   Ziopub_channelr{   Úiopub_timeoutr   ZwarningÚraise_on_iopub_timeoutrN   r)   rX   ru   Ú
startswithrw   r   rt   rc   Ú
setdefaultÚappendÚlen)r   r'   rk   ry   Z
exec_replyZoutsr-   ro   r]   rv   Zcell_maprl   Zoutput_idx_listr   r   r   rg   µ  sf    





zExecutePreprocessor.run_cell)N)N)N)r   )&r0   r1   r2   r3   r   r   ÚtagrF   r	   rz   r   r|   rM   ri   rj   r   r   rE   rD   r   r€   r   rP   r
   r?   r   rB   r   rX   rU   r   r\   r`   rm   rw   ra   rg   r5   r   r   )r   r   r6   @   sx   







	


	

#B"
 r6   Nc             K   s6   i }|dk	rd|i|d< t f |Ž}|j| ||dd S )a0  Execute a notebook's code, updating outputs within the notebook object.

    This is a convenient wrapper around ExecutePreprocessor. It returns the
    modified notebook object.

    Parameters
    ----------
    nb : NotebookNode
      The notebook object to be executed
    cwd : str, optional
      If supplied, the kernel will run in this directory
    km : KernelManager, optional
      If supplied, the specified kernel manager will be used for code execution.
    kwargs :
      Any other options for ExecutePreprocessor, e.g. timeout, kernel_name
    NrV   rH   )rS   r   )r6   r`   )rG   rW   rS   rR   rZ   Zepr   r   r   Ú	executenb  s
    
r‡   )NN)r3   Útextwrapr   Ú
contextlibr   Zqueuer   rA   ZQueueZ	traitletsr   r   r   r   r	   r
   r   r   r   Znbformat.v4r   Úbaser   Zutils.exceptionsr   r   r*   r6   r‡   r   r   r   r   Ú<module>   s"   ,'   D