
]c           @   s  d  Z  d d l Z d d l m Z d d l m Z y d d l m Z Wn! e k
 ri d d l m Z n Xy d d l	 m
 Z
 Wn! e k
 r d d l m
 Z
 n Xy e Wn e k
 r e Z n Xd 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 d e f d     YZ d e  f d     YZ! d e f d     YZ" d Z# d e f d     YZ$ e% e% d  Z& d   Z' d   Z( d S(   sQ   Module containing a preprocessor that executes the code cells
and updates outputsiN(   t   dedent(   t   contextmanager(   t	   monotonic(   t   time(   t   Empty(	   t   Listt   Unicodet   Boolt   Enumt   Anyt   Typet   Dictt   Integert   default(   t   output_from_msgi   (   t   Preprocessori   (   t   ConversionExceptiont   DeadKernelErrorc           B   s   e  Z RS(    (   t   __name__t
   __module__(    (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR      s   t   CellExecutionCompletec           B   s   e  Z d  Z RS(   s   
    Used as a control signal for cell execution across run_cell and
    process_message function calls. Raised when all execution requests
    are completed and no further messages are expected from the kernel
    over zeromq channels.
    (   R   R   t   __doc__(    (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR   "   s   t   CellExecutionErrorc           B   s8   e  Z d  Z d   Z d   Z d   Z e d    Z RS(   s   
    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         C   s#   t  t |   j |  | |  _ d  S(   N(   t   superR   t   __init__t	   traceback(   t   selfR   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR   2   s    c         C   s4   |  j    } t | t  s0 | j d d  } n  | S(   Nt   utf8t   replace(   t   __unicode__t
   isinstancet   strt   encode(   R   t   s(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   __str__6   s    c         C   s   |  j  S(   N(   R   (   R   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR   <   s    c         C   s[   d j  | j d g    } |  t j d | d | d | j d d  d | j d d    S(   sv   Instantiate from a code cell object and a message contents
        (message is either execute_reply or error)
        s   
R   t   cellt   enames   <Error>t   evaluet    (   t   joint   gett   exec_err_msgt   format(   t   clsR#   t   msgt   tb(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   from_cell_and_msg?   s    (   R   R   R   R   R"   R   t   classmethodR.   (    (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR   +   s
   			u   An error occurred while executing the following cell:
------------------
{cell.source}
------------------

{traceback}
{ename}: {evalue}
t   ExecutePreprocessorc           B   s  e  Z d  Z e d d e d e d  j d e  Z e d d0 d e d e d   j d e  Z
 e e d e d  j d e  Z e d	 d e d
  j d e  Z e e d e d  j d e  Z e e d e d  j d e  Z e e    Z e d d e d  j d e  Z e e d e d  j d e  Z e e d e d  j d e  Z e d d e d e d  j d e  Z e d d g d d d e d  j d e  Z e d d d d  j d e  Z e d e d d  Z e d  d    Z e d e d   Z  d   Z! e" d0 d   Z# d0 d0 d  Z$ d   Z% e d   Z& d!   Z' d0 d0 d"  Z( d#   Z) d$   Z* d%   Z+ d0 d&  Z, d'   Z- d(   Z. d) e d*  Z/ d+   Z0 d,   Z1 d-   Z2 d.   Z3 d/   Z4 RS(1   s.   
    Executes all the cells in a notebook
    i   t
   allow_nonet   helpsO  
            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`.
            t   configt   default_valuesX  
            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`.
            s   
            If execution of a cell times out, interrupt the kernel and
            continue executing other cells rather than throwing an error and
            stopping.
            i<   s   
            The time to wait (in seconds) for the kernel to start.
            If kernel startup takes longer, a RuntimeError is
            raised.
            sq  
            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.
            s  
            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&   s   
            Name of kernel to use to execute the cells.
            If not set, use the kernel_spec embedded in the notebook.
            s  
            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.
            s   
            If `True` (default), then the state of the Jupyter widgets created
            at the kernel will be stored in the metadata of the notebook.
            i   s  
            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.
            t   gracefult	   immediates  
            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.
            s   :memory:s  Path to file to use for SQLite history database for an IPython kernel.
        
        The specific value `:memory:` (including the colon
        at both end but not the back ticks), avoids creating a history file. Otherwise, IPython
        will create a history file for each kernel. 
        
        When running kernels simultaneously (e.g. via multiprocessing) saving history a single
        SQLite file can result in database errors, so using `:memory:` is recommended in non-interactive
        contexts.
        
        s    The kernel manager class to use.t   kernel_manager_classc         C   s8   y d d l  m } Wn t k
 r3 t d   n X| S(   sB   Use a dynamic default to avoid importing jupyter_client at startupi(   t   KernelManagersW   `nbconvert --execute` requires the jupyter_client package: `pip install jupyter_client`(   t   jupyter_clientR8   t   ImportError(   R   R8   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   _kernel_manager_class_default   s
    sP  
              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  s3 |  j j j d i   j d d  |  _  n  |  j d |  j  d |  j  } | j r |  j r |  j d j	 |  j  g 7_ n  | j
 d |  j |  | j   } | j   y | j d |  j  Wn( t k
 r | j   | j     n Xt | _ | | f S(	   s9  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`.
        t
   kernelspect   namet   pythont   kernel_nameR3   s   --HistoryManager.hist_file={}t   extra_argumentst   timeout(   R?   t   nbt   metadataR(   R7   R3   t	   ipykernelt   ipython_hist_fileR@   R*   t   start_kernelt   clientt   start_channelst   wait_for_readyt   startup_timeoutt   RuntimeErrort   stop_channelst   shutdown_kernelt   Falset   allow_stdin(   R   t   kwargst   kmt   kc(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   start_new_kernel  s$    	!


	c         k   s  | j  d i   j  d d  p! d } | |  _ i  |  _ i  |  _ i  |  _ | d k r | | d <|  j |   \ |  _ |  _ z | |  j |  j f VWd |  j j	   |  j j
 d |  j
 d k  x$ d d	 d
 g D] } t |  |  q WXn | |  _ | j s| j d |  j |  n  | j   |  _ |  j j   y |  j j d |  j  Wn! t k
 rl|  j j	     n Xt |  j _ z | |  j |  j f VWd x$ d d	 d
 g D] } t |  |  qWXd S(   sj  
        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 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.
        RC   t   pathR&   t   cwdNt   nowR6   RB   RQ   RR   R@   RA   (   R(   t   NoneRB   t   _display_id_mapt   widget_statet   widget_buffersRS   RQ   RR   RL   RM   t   delattrt
   has_kernelRF   R@   RG   RH   RI   RJ   RK   RN   RO   (   R   RB   t	   resourcesRQ   RP   RT   t   attr(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   setup_preprocessor0  s:     $				
		c         C   s   | s i  } n  |  j  | | d | t |  j j d |  j  t t |   j | |  \ } } |  j |  j j	    } | d d | j
 d <|  j   Wd QX| | f S(   s  
        Preprocess notebook executing each code cell.

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

        Parameters
        ----------
        nb : NotebookNode
            Notebook being executed.
        resources : dictionary (optional)
            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.
        RQ   s"   Executing notebook with kernel: %st   contentt   language_infoN(   R_   t   logt   infoR?   R   R0   t
   preprocesst   _wait_for_replyRR   t   kernel_infoRC   t   set_widgets_metadata(   R   RB   R]   RQ   t   info_msg(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyRd   v  s    	!c         C   s   |  j  r i i d   |  j  j   D d 6d d 6d d 6d 6|  j j _ xS |  j j j d d j   D]1 \ } } |  j j |  } | re | | d <qe qe Wn  d  S(	   Nc         S   s1   i  |  ]' \ } } d  | k r t  |  |  q S(   t   _model_name(   t   _serialize_widget_state(   t   .0t   model_idt   state(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pys
   <dictcomp>  s   	Rm   i   t   version_majori    t   version_minors)   application/vnd.jupyter.widget-state+jsont   buffers(   RY   t   itemsRB   RC   t   widgetsRZ   R(   (   R   t   keyt   widgetRp   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyRg     s    	*c   	      C   s   | j  d k s | j j   r) | | f S|  j | | |  \ } } | | _ |  j pn d | j j d g   k } |  j s | r x5 | j D]* } | j	 d k r t
 j | |   q q W| d k	 r | d d d k r t
 j | | d   q n  | | f S(   s}   
        Executes a single code cell. See base.py for details.

        To execute all cells see :meth:`preprocess`.
        t   codes   raises-exceptiont   tagst   errorR`   t   statusN(   t	   cell_typet   sourcet   stript   run_cellt   outputst   allow_errorsRC   R(   t   force_raise_errorst   output_typeR   R.   RW   (	   R   R#   R]   t
   cell_indext   store_historyt   replyR}   t   cell_allows_errorst   out(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   preprocess_cell  s    
	 c   	      C   s  | |  j  k r, |  j j d | |  j   d S| d d d k rQ d | d d <n  y t |  } Wn* t k
 r |  j j d | d  d SXxq |  j  | j   D]\ \ } } |  j d | } | d	 } x2 | D]* } | d
 | | d
 <| d | | d <q Wq Wd S(   s&   Update outputs with a given display_ids   display id %r not in %sNt   headert   msg_typet   update_display_datat   display_datas   unhandled iopub msg: t   cellsR}   t   dataRC   (   RX   Rb   t   debugR   t
   ValueErrorRw   Rq   RB   (	   R   t
   display_idR,   R   t   cell_idxt   output_indicesR#   R}   t
   output_idx(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   _update_display_id  s      
c         C   s[   y9 |  j  j j d |  } | d j d  | k r8 | SWn t k
 rV |  j   n Xd  S(   NRA   t   parent_headert   msg_id(   RR   t   shell_channelt   get_msgR(   R   t   _check_alive(   R   R   R#   RA   R,   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   _poll_for_reply  s    c         C   sV   |  j  d  k	 r- | d  k	 r- |  j  |  } n	 |  j } | sI | d k  rR d  } n  | S(   Ni    (   t   timeout_funcRW   RA   (   R   R#   RA   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   _get_timeout  s    		c         C   sP   |  j  j d |  j  |  j r@ |  j  j d  |  j j   n t d   d  S(   Ns(   Timeout waiting for execute reply (%is).s   Interrupting kernels   Cell execution timed out(   Rb   Rw   RA   t   interrupt_on_timeoutRQ   t   interrupt_kernelt   TimeoutError(   R   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   _handle_timeout  s    		c         C   s2   |  j  j   s. |  j j d  t d   n  d  S(   Ns,   Kernel died while waiting for execute reply.s   Kernel died(   RR   t   is_aliveRb   Rw   R   (   R   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR     s    	c         C   s   |  j  |  } d } d } x t r y |  j j j d |  } WnE t k
 r |  j   | | 7} | r | | k r |  j   Pq q X| d j d  | k r | Sq Wd  S(   Ni    i   RA   R   R   (	   R   t   TrueRR   R   R   R   R   R   R(   (   R   R   R#   RA   t   cummulative_timet   timeout_intervalR,   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyRe      s    	


c         C   sH   | d  k	 r/ | t   | k  r/ | t   } n  | d k  rD d } n  | S(   Ni    (   RW   R   (   R   RA   t   deadline(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   _timeout_with_deadline  s
    	c         C   s1   | d  k	 r- | t   d k r- |  j   t St S(   Ni    (   RW   R   R   R   RN   (   R   R   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   _passed_deadline  s    
i    c         C   s  |  j  j | j d | d |  j } |  j j d | j  |  j |  } d  } | d  k	 rl t   | } n  g  | _	 t
 |  _ t } t } xZ| s | r| r |  j |  r t
 } q n  |  j d |  }	 |  j | | |	  }
 |
 d  k	 r t
 } q n  | ry@ |  j }	 | r&|  j |	 |  }	 n  |  j  j j d |	  } Wqt k
 r| r[q n  |  j rst d   q|  j j d  t
 } q qXn  | d j d  | k rq n  y |  j | | |  Wq t k
 rt
 } q Xq W|
 | j	 f S(	   NR   t   stop_on_errors   Executing cell:
%si   RA   s    Timeout waiting for IOPub outputR   R   (   RR   t   executeRz   R~   Rb   R   R   RW   R   R}   RN   t   clear_before_next_outputR   R   R   R   t   iopub_timeoutt   iopub_channelR   R   t   raise_on_iopub_timeoutR   t   warningR(   t   process_messageR   (   R   R#   R   R   t   parent_msg_idt   exec_timeoutR   t   more_outputt   polling_exec_replyRA   t
   exec_replyR,   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR|   !  sR    		
		
c         C   sD  | d } |  j  j d |  | d } |  j  j d |  | j d i   j d d  } | r | d d d	 h k r |  j | |  n  d
 | k r | d
 | d
 <n  | d k r | d d k r@t    q@nr | d k r |  j | j | |  nM | j d  r|  j	 | j | |  n% | d k r@|  j
 | j | | |  Sd S(   s  
        Processes a kernel message, updates cell state, and returns the
        resulting output object that was appended to cell.outputs.

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

        Parameters
        ----------
        msg : dict
            The kernel message being processed.
        cell : nbformat.NotebookNode
            The cell which is currently being processed.
        cell_index : int
            The position of the cell within the notebook object.

        Returns
        -------
        output : dict
            The execution output payload (or None for no output).

        Raises
        ------
        CellExecutionComplete
          Once a message arrives which indicates computation completeness.

        R   s   msg_type: %sR`   s   content: %st	   transientR   t   execute_resultR   R   t   execution_countRx   t   execution_statet   idlet   clear_outputt   commt   execute_inputN(   R   R   (   Rb   R   R(   RW   R   R   R   R}   t
   startswitht   handle_comm_msgt   output(   R   R,   R#   R   R   R`   R   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR   g  s$    

c   	      C   s   | d } y t  |  } Wn& t k
 rB |  j j d |  d  SX|  j r| |  j j d  g  | (|  j |  t |  _ n  | r |  j j	 | i   } | j	 | g   } | j
 t |   n  | j
 |  | S(   NR   s   unhandled iopub msg: s   Executing delayed clear_output(   R   R   Rb   Rw   R   R   t   clear_display_id_mappingRN   RX   t
   setdefaultt   appendt   len(	   R   t   outsR,   R   R   R   R   t   cell_mapt   output_idx_list(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR     s"    
	c         C   s]   | d } | j  d  r5 |  j j d  t |  _ n$ |  j j d  g  | (|  j |  d  S(   NR`   t   waits   Wait to clear outputs   Immediate clear output(   R(   Rb   R   R   R   R   (   R   R   R,   R   R`   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR     s    
c         C   s=   x6 |  j  j   D]% \ } } | | k r g  | | <q q Wd  S(   N(   RX   Rq   (   R   R   R   R   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR     s    c         C   s   | d } | d } |  j  r d | k r |  j j | d i   j | d  d | k r | d r t |  |  j | d <q n  d  S(   NR`   R   Rm   t   comm_idt   buffer_paths(   t   store_widget_stateRY   R   t   updatet   _get_buffer_dataRZ   (   R   R   R,   R   R`   R   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR     s    

$N(5   R   R   R   R   R   R    t   tagRA   R	   RW   R   R   RN   R   RJ   R~   R   R   R   R@   R?   R   R   R   R   RM   RE   R
   R7   R   R;   R   RX   RS   R   R_   Rd   Rg   R   R   R   R   R   R   Re   R   R   R|   R   R   R   R   R   (    (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR0   T   s   																					
	%E&									F	4		
	c         K   sL   i  } | d k	 r& i | d 6| d <n  t |   } | j |  | d | d S(   s0  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
    RT   RC   RQ   i    N(   RW   R0   Rd   (   RB   RU   RQ   RP   R]   t   ep(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt	   executenb  s
    c         C   s;   i |  j  d  d 6|  j  d  d 6|  j  d  d 6|  d 6S(   sF   Serialize a widget state, following format in @jupyter-widgets/schema.Ri   t
   model_namet   _model_modulet   model_modulet   _model_module_versiont   model_module_versionRm   (   R(   (   Rm   (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyRj     s
    c         C   sz   g  } |  d d d } |  d } xQ t  | |  D]@ \ } } | j i t j |  j d  d 6d d 6| d 6 q2 W| S(	   NR`   R   R   Rp   s   utf-8t   base64t   encodingRT   (   t   zipR   R   t	   b64encodet   decode(   R,   t   encoded_bufferst   pathsRp   RT   t   buffer(    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyR     s    
	()   R   R   t   textwrapR    t
   contextlibR   R   R   R:   t   queueR   t   QueueR   t	   NameErrorRK   t	   traitletsR   R   R   R   R	   R
   R   R   R   t   nbformat.v4R   t   baseR   t   utils.exceptionsR   R   t	   ExceptionR   R   R)   R0   RW   R   Rj   R   (    (    (    s>   lib/python2.7/site-packages/nbconvert/preprocessors/execute.pyt   <module>   s:   
@	'  z	
