Format: application/x-python-code
⬇ Download File (21.0 KB)
   1  o
   2  
   3  �h�i�@sdZddlZddlZddlZddlZddlZddlZddlZddlZddl	Z	ddl
   4  mZddlm
   5  Z
   6  mZddlmZmZddlmZddlmZmZmZmZmZddlZddlmZdd	lmZdd
   7  lmZdZdZ dZ!Gd
   8  d�d�Z"Gdd�d�Z#Gdd�de�Z$dS)z.Wrappers for forwarding stdout/stderr over zmq�N)�b2a_hex)�defaultdict�deque)�StringIO�
   9  TextIOBase)�local)�Any�Callable�Deque�Dict�Optional)�extract_header)�IOLoop)�	ZMQStream�i�c@s�eZdZdZd*dd�Zdd�Zdd�Zd	d
  10  �Zdd�Ze	d
  11  d��Z
  12  dd�Zdd�Zdd�Z
  13  dd�Zdd�Zdd�Zdd�Zdd�Zdd �Ze	d!d"��Zd#d$�Zd%d&�Zd'd(�Zd)S)+�IOPubThreadaAn object for sending IOPub messages in a background thread
  14  
  15      Prevents a blocking main thread from delaying output from threads.
  16  
  17      IOPubThread(pub_socket).background_socket is a Socket-API-providing object
  18      whose IO is always run in a thread.
  19      FcCs�||_d|_t|�|_t��|_||_tdd�|_	|r|�
  20  �t��|_
  21  t�|_i|_t��|_d|_d|_|��tj|jdd�|_d|j_d|j_d|j_d|j_dS)aCreate IOPub thread
  22  
  23          Parameters
  24          ----------
  25          socket : zmq.PUB Socket
  26              the socket on which messages will be sent.
  27          pipe : bool
  28              Whether this process should listen for IOPub messages
  29              piped from subprocesses.
  30          F)Zmake_current�
  31  N�IOPub)�target�nameT)�socket�_stopped�BackgroundSocketZbackground_socket�os�getpid�_master_pid�
  32  _pipe_flagr�io_loop�_setup_pipe_in�	threadingr�_localr�_events�_event_pipes�Lock�_event_pipe_gc_lock�_event_pipe_gc_seconds�_event_pipe_gc_task�_setup_event_pipe�Thread�_thread_main�thread�daemonZpydev_do_not_traceZis_pydev_daemon_threadr)�selfr�pipe�r.�Hc:\Users\shubh\Videos\agent\nova\Lib\site-packages\ipykernel/iostream.py�__init__1s(
  33  
  34  
  35  
  36  zIOPubThread.__init__csn�fdd�}�j�|��js�j���jdur.�fdd�}�js)�j�|�n�j���jjdd�dS)z.The inner loop that's actually run in a threadcst������_dS�N)�asyncio�
  37  ensure_future�_run_event_pipe_gcr&r.�r,r.r/�_start_event_gcTsz1IOPubThread._thread_main.<locals>._start_event_gcNc�s��j��dSr1)r&�cancelr.r5r.r/�_cancel`s�z)IOPubThread._thread_main.<locals>._cancelT)Zall_fds)rZrun_syncr�startr&r7�close)r,r6r8r.r5r/r)Qs
  38  
  39  
  40  zIOPubThread._thread_maincCsf|jj}|�tj�}d|_tt�d���d�}d|}|_	|�
  41  |�t||j�|_
  42  |j
  43  �|j�dS)zLCreate the PULL socket listening for events that should fire in this thread.r��asciizinproc://%sN)r�context�zmq�PULL�lingerrr�urandom�decode�_event_interface�bindrrZ
  44  _event_puller�on_recv�
  45  _handle_event)r,�ctx�pipe_in�_uuidZifacer.r.r/r'js
  46  zIOPubThread._setup_event_pipec
  47  �sd�	t�|j�IdHz	|��IdHWnty0}ztd|��tjd�WYd}~nd}~wwq)z&Task to run event pipe gc continuouslyTNz)Exception in IOPubThread._event_pipe_gc: ��file)r2�sleepr%�_event_pipe_gc�	Exception�print�sys�
  48  __stderr__)r,�er.r.r/r4vs� ���zIOPubThread._run_event_pipe_gcc�sh�|jsdS|j�!t|j���D]\}}|��s!|��|j|=qWd�dS1s-wYdS)z.run a single garbage collection on event pipesN)r"r$�list�items�is_aliver:)r,r*rr.r.r/rMs���"�zIOPubThread._event_pipe_gccCs�z|jj}W|StyD|jj}|�tj�}d|_|�|j	�||j_|j
  49  �||jt�
  50  �<Wd�Y|S1s<wYY|Sw)zSthread-local event pipe for signaling events that should be processed in the threadrN)r �
  51  event_pipe�AttributeErrorrr=r>�PUSHr@�connectrCr$r"r�current_thread)r,rVrGr.r.r/�_event_pipe�s 
  52  
  53  ����zIOPubThread._event_pipecCs,t|j�}t|�D]
  54  }|j��}|�q	dS)z�Handle an event on the event pipe
  55  
  56          Content of the message is ignored.
  57  
  58          Whenever *an* event arrives on the event stream,
  59          *all* waiting events are processed in order.
  60          N)�lenr!�range�popleft)r,�msgZn_events�_Zevent_fr.r.r/rF�s
  61  
  62  
  63  
  64  �zIOPubThread._handle_eventc
  65  Cs�|jj}t�d�|_|�tj�}d|_z|�d�|_	Wn&tj
  66  yA}ztjd|ddd�d|_
  67  |��WYd	}~d	Sd	}~wwt||j�|_|j�|j�d	S)
  68  z7setup listening pipe for IOPub from forked subprocessesr;rztcp://127.0.0.1z)Couldn't bind IOPub Pipe to 127.0.0.1: %sz'
  69  subprocess output will be unavailable.���
  70  stacklevelFN)rr=rrA�
  71  _pipe_uuidr>r?r@Zbind_to_random_port�
  72  _pipe_portZZMQError�warnings�warnrr:rrZ_pipe_inrE�_handle_pipe_msg)r,rGrHrRr.r.r/r�s(����	zIOPubThread._setup_pipe_incCsJ|jr|��s	dS|d|jkrtd|tjd�dS|�|dd��dS)z'handle a pipe message from a subprocessNrzBad pipe message: %srJr)r�_is_master_processrdrOrPrQ�send_multipart�r,r_r.r.r/rh�szIOPubThread._handle_pipe_msgcCs2t��}|�tj�}d|_|�d|j�||fS)Ni�ztcp://127.0.0.1:%i)r>�ContextrrXr@rYre)r,rG�pipe_outr.r.r/�_setup_pipe_out�s
  73  zIOPubThread._setup_pipe_outcC�t��|jkSr1�rrrr5r.r.r/ri��zIOPubThread._is_master_processcCs|jr|��r	tStS)z8check for forks, and switch to zmq pipeline if necessary)rri�MASTER�CHILDr5r.r.r/�_check_mp_mode�szIOPubThread._check_mp_modecCs"d|j_|j��t�|j�dS)zStart the IOPub threadrN)r*rr9�atexit�register�stopr5r.r.r/r9�s
  74  zIOPubThread.startcCshd|_|j��s
  75  dS|j�|jj�|jjdd�|j��r$d}t|��|j�	�D]\}}|�
  76  �q)dS)zStop the IOPub threadTN�)�timeoutz,IOPub thread did not terminate in 30 seconds)rr*rUrZadd_callbackrw�join�TimeoutErrorr"rTr:)r,r_�_threadrVr.r.r/rw�s
  77  
  78  
  79  �zIOPubThread.stopcCs|jrdS|j��d|_dS)zClose the IOPub thread.N)�closedrr:r5r.r.r/r:�s
  80  
  81  zIOPubThread.closecC�
  82  |jduSr1)rr5r.r.r/r}��
  83  zIOPubThread.closedcCs0|j��r|j�|�|j�d�dS|�dS)ztSchedule a function to be called in our IO thread.
  84  
  85          If the thread is not running, call immediately.
  86          �N)r*rUr!�appendr[�send)r,�fr.r.r/�schedules
  87  
  88  zIOPubThread.schedulecs�����fdd��dS)z�send_multipart schedules actual zmq send in my thread.
  89  
  90          If my thread isn't running (e.g. forked process), send immediately.
  91          cs�j�i���Sr1)�_really_sendr.��args�kwargsr,r.r/�<lambda>sz,IOPubThread.send_multipart.<locals>.<lambda>N)r��r,r�r�r.r�r/rjszIOPubThread.send_multipartcOsx|jrdS|��}|tkr|jj|g|�Ri|��dS|��\}}|j|jg|�g|�Ri|��|��|��dS)z)The callback that actually sends messagesN)	r}rtrsrrjrnrdr:�term)r,r_r�r�Zmp_moderGrmr.r.r/r�s zIOPubThread._really_sendN)F)�__name__�
  92  __module__�__qualname__�__doc__r0r)r'r4rM�propertyr[rFrrhrnrirtr9rwr:r}r�rjr�r.r.r.r/r(s.
  93   	
  94  	
  95  rcsHeZdZdZdZdd�Z�fdd�Z�fdd�Zd	d
  96  �Zdd�Z	�Z
  97  S)
  98  rz>Wrapper around IOPub thread that provides zmq send[_multipart]NcCs
  99  ||_dS)zInitialize the socket.N)�	io_thread)r,r�r.r.r/r0/rzBackgroundSocket.__init__csr|�d�r|�d�rt��|�|jdusJ�t|jj|�r3tjd|�d|��t	dd�t
 100  |jj|�St��|�S)z2Wrap socket attr access for backward-compatibility�__NzAccessing zmq Socket attribute �O on BackgroundSocket is deprecated since ipykernel 4.3.0 use .io_thread.socket.rarb)�
 101  startswith�endswith�super�__getattr__r��hasattrrrfrg�DeprecationWarning�getattr)r,�attr��	__class__r.r/r�3s��zBackgroundSocket.__getattr__csl|dks|�d�r|�d�rt��||�dStjd|�d|��tdd�|jdus,J�t|jj	||�dS)zSet an attribute on the socket.r�r�zSetting zmq Socket attribute r�rarbN)
 102  r�r�r��__setattr__rfrgr�r��setattrr)r,r��valuer�r.r/r�Ds��zBackgroundSocket.__setattr__cOs|j|gg|�Ri|��S)zSend a message to the socket.)rj)r,r_r�r�r.r.r/r�SszBackgroundSocket.sendcOs |jdusJ�|jj|i|��S)zSchedule send in IO threadN)r�rjr�r.r.r/rjWszBackgroundSocket.send_multipart)r�r�r�r�r�r0r�r�r�rj�
 103  __classcell__r.r.r�r/r*src@seZdZUdZdZdZdZdZdZe	e
 104  ed<dd�Zd	d
 105  �Z
 106  		d7ddd
 107  �dd�Zedd��Zejdd��Zdd�Zdd�Zdd�Zdd�Zdd�Zedd��Zdd �Zd!d"�Zd#d$�Zd%ed&e	efd'd(�Zd)d*�Zd+d,�Zd-d.�Z d/d0�Z!ed1d2��Z"d3d4�Z#d5d6�Z$dS)8�	OutStreamzpA file like object that publishes the stream to a 0MQ PUB socket.
 108  
 109      Output is handed off to an IO Thread
 110      rg�������?NzUTF-8�_exccCs$t|dd�dur|jSd}t�|��)z^
 111          Things like subprocess will peak and write to the fileno() of stderr/stdout.
 112          �_original_stdstream_copyN�fileno)r�r��io�UnsupportedOperationrkr.r.r/r�ls
 113  zOutStream.filenocCs�z4t�|jt�}|r,|jr2|�|jdd��t�|j|�t�|jt�}|r/|js
 114  WdSWdSWdSWdStyCt	�
 115  �|_YdSw)aj
 116          We've redirected standards streams 0 and 1 into a pipe.
 117  
 118          We need to watch in a thread and redirect them to the right places.
 119  
 120          1) the ZMQ channels to show in notebook interfaces,
 121          2) the original stdout/err, to capture errors in terminals.
 122  
 123          We cannot schedule this on the ioloop thread, as this might be blocking.
 124  
 125          �replace)�errorsN)r�read�_fid�PIPE_BUFFER_SIZE�
 126  _should_watch�writerBr�rNrP�exc_infor�)r,Zbtsr.r.r/�_watch_pipe_fdus
 127  
 128  "��zOutStream._watch_pipe_fdTF)�watchfd�isattyc
 129  Cs�|durtjdtdd�||_t|t�s&tjd|tdd�t|�}|��||_||_d|�	�|_
 130  t�d�|_
 131  |j
 132  �i�i|_i|_i|_t��|_d|_d|_|j|_t��|_tt�|_d|_t |�|_!d|_"t#�|_$|r�t%j&�'d	�s~t%j&�'d
 133  �r�dtj(vs�|dkr�d
 134  |_"|�)|�|r�t*|d�r�t*|d�r�|j"r�z|�+�}Wnt,y�d}Ynw|dur�||j-kr�t.�/t.�0|j1d��}||_dSd}	t2|	��dS)a�
 135          Parameters
 136          ----------
 137          session : object
 138              the session object
 139          pub_thread : threading.Thread
 140              the publication thread
 141          name : str {'stderr', 'stdout'}
 142              the name of the standard stream to replace
 143          pipe : object
 144              the pipe object
 145          echo : bool
 146              whether to echo output
 147          watchfd : bool (default, True)
 148              Watch the file descriptor corresponding to the replaced stream.
 149              This is useful if you know some underlying code will write directly
 150              the file descriptor by its number. It will spawn a watching thread,
 151              that will swap the give file descriptor for a pipe, read from the
 152              pipe, and insert this into the current Stream.
 153          isatty : bool (default, False)
 154              Indication of whether this stream has terminal capabilities (e.g. can handle colors)
 155  
 156          NzKpipe argument to OutStream is deprecated and ignored since ipykernel 4.2.3.rarbzISince IPykernel 4.3, OutStream should be created with IOPubThread, not %rsstream.�
 157  parent_headerF�linux�darwinZPYTEST_CURRENT_TEST�forceTr�r��wz(echo argument must be a file-like object)3rfrgr��session�
 158  isinstancerr9�
 159  pub_threadr�encode�topic�contextvars�
 160  ContextVar�_parent_header�set�_thread_to_parent�_thread_to_parent_header�_parent_header_globalrrr�_flush_pending�_subprocess_flush_pendingr�_io_loopr�RLock�_buffer_lockrr�_buffers�echo�bool�_isattyr�rr rP�platformr��environ�_setup_stream_redirectsr�r�rN�_original_stdstream_fdr��
 161  TextIOWrapper�FileIOr��
 162  ValueError)
 163  r,r�r�rr-r�r�r�Zecho_fdr_r.r.r/r0�s�"�
 164  ���
 165  
 166  
 167  
 168  �
 169  �
 170  �
 171  
 172  ���
 173  �zOutStream.__init__cCsrz|j��WSty8zt��j}||jvr"|j|}||jvs|j|WYSty7|j	YYSwwr1)
 174  r��get�LookupErrorrrZ�identr�r��KeyErrorr�)r,�identityr.r.r/r��s
 175  
 176  
 177  
 178  ���zOutStream.parent_headercCs||_|j�|�Sr1)r�r�r�)r,r�r.r.r/r�scCs|jS)zpReturn a bool indicating whether this is an 'interactive' stream.
 179  
 180          Returns:
 181              Boolean
 182          )r�r5r.r.r/r�szOutStream.isattycCsjt��\}}tt|���}|_t�|�|_t�||�||_	d|_
 183  tj|j
 184  d�|_d|j_|j��dS)N)rT)rr-r�rPr�r��dupr��dup2r�r�rr(r��watch_fd_threadr+r9)r,r�pr�pwZfnor.r.r/r�sz!OutStream._setup_stream_redirectscCror1rpr5r.r.r/ri&rqzOutStream._is_master_processcCst|�|_dS)zSet the parent header.N)r
 185  r�)r,�parentr.r.r/�
 186  set_parent)szOutStream.set_parentcCsj|jr d|_t�|jd�|j��t�|j|j�t�|j�|j	r0|j	\}}}t
 187  �|||�d|_dS)zClose the stream.F�N)
 188  r�rr�r�r�rzr�r�r:r��	traceback�print_exceptionr�)r,�etyper��tbr.r.r/r:-s
 189  
 190  zOutStream.closecCr~r1)r�r5r.r.r/r}=rzOutStream.closedcs,�jrdSd�_�fdd�}�j�|�dS)zuschedule a flush in the IO thread
 191  
 192          call this on write, to indicate that flush should be called soon.
 193          NTcs�j��j�j�dSr1)r��
 194  call_later�flush_interval�_flushr.r5r.r/�_schedule_in_threadKsz6OutStream._schedule_flush.<locals>._schedule_in_thread)r�r�r�)r,r�r.r5r/�_schedule_flushAs
 195  zOutStream._schedule_flushcCs�|jr<|jjdur<|jj��r<|jjjt��jkr<|j�|j�t��}|j�|j	�|�
 196  |j�s:tdt
 197  jd�dSdS|��dS)zStrigger actual zmq send
 198  
 199          send will happen in the background thread
 200          NzIOStream.flush timed outrJ)r�r*rUr�rrZr�r��Eventr��wait�
 201  flush_timeoutrOrPrQ)r,Zevtr.r.r/�flushPs�
 202  ��zOutStream.flushc
 203  Cs�d|_d|_|jdur5z|j��Wn"ty4}z|jtjur*td|��tjd�WYd}~nd}~ww|��D]8\}}|rqt	�
 204  �|j_|j
 205  |d�}|jjd||d�}|jD]}||�}|duredSqW|jj|j||jd�q9dS)	z�This is where the actual send happens.
 206  
 207          _flush should generally be called in the IO thread,
 208          unless the thread has been destroyed (e.g. forked subprocess).
 209          FNzFlush failed: rJ)r�text�stream)r�)r�)r�r�r�r��OSErrorrPrQrO�_flush_buffersrrr��pidrr_�_hooksr�r�r�)r,rRr��data�contentr_�hookr.r.r/r�hs6
 210  ��
 211  ����zOutStream._flush�string�returnc
 212  Cs|j}t|t�sdt|���}t|��|jdurCz|j�|�Wn"tyB}z|jtj	ur8t
 213  d|��tj	d�WYd}~nd}~ww|jdurNd}t|��|�
 214  �}|j�|jt|����|�Wd�n1smwY|r�|jrydSd|_|j�|j�t|�S|��t|�S)z�Write to current stream after encoding if necessary
 215  
 216          Returns
 217          -------
 218          len : int
 219              number of items from input parameter written to stream.
 220  
 221          z"write() argument must be str, not NzWrite failed: rJ�I/O operation on closed fileT)r�r��str�type�	TypeErrorr�r�r�rPrQrOr�r�rir�r��	frozensetrTr�r�r�r�r\)r,r�r�r_rRZis_childr.r.r/r��s6	
 222  
 223  ��
 224  
 225  ��zOutStream.writecCs.|jdurd}t|��|D]}|�|�q
 226  dS)zWrite lines to the stream.Nr�)r�r�r�)r,�sequencer_r�r.r.r/�
 227  writelines�s
 228  �zOutStream.writelinescCsdS)z$Test whether the stream is writable.Tr.r5r.r.r/�writable�szOutStream.writableccs>�|��}|��D]\}}|��}|��t|�|fVq	dS)z<clear the current buffer and return the current buffer data.N)�_rotate_buffersrT�getvaluer:�dict)r,�buffersZ
 229  frozen_parent�bufferr�r.r.r/r��s��zOutStream._flush_bufferscCs<|j�|j}tt�|_Wd�|S1swY|S)z@Returns the current buffer and replaces it with an empty buffer.N)r�r�rr)r,Zold_buffersr.r.r/r�s
 230  ��zOutStream._rotate_bufferscCst|jd�s
 231  g|j_|jjS)N�hooks)r�r rr5r.r.r/r��szOutStream._hookscCs|j�|�dS)a�
 232          Registers a hook with the thread-local storage.
 233  
 234          Parameters
 235          ----------
 236          hook : Any callable object
 237  
 238          Returns
 239          -------
 240          Either a publishable message, or `None`.
 241          The hook callable must return a message from
 242          the __call__ method if they still require the
 243          `session.send` method to be called after transformation.
 244          Returning `None` will halt that execution path, and
 245          session.send will not be called.
 246          N)r�r��r,r�r.r.r/�
 247  register_hook�szOutStream.register_hookcCs(z	|j�|�WdStyYdSw)aB
 248          Un-registers a hook with the thread-local storage.
 249  
 250          Parameters
 251          ----------
 252          hook : Any callable object which has previously been
 253              registered as a hook.
 254  
 255          Returns
 256          -------
 257          bool - `True` if the hook was removed, `False` if it wasn't
 258              found.
 259          TF)r��remover�rr.r.r/�unregister_hook�s�zOutStream.unregister_hook)NN)%r�r�r�r�r�r�r��encodingr�rr�__annotations__r�r�r0r�r��setterr�r�rir�r:r}r�r�r�r��intr�r�rr�rr�rr
 260  r.r.r.r/r�]sL
 261  	��n
 262  
 263  
 264  
 265  '+
 266  r�)%r�r2rur�r�rrPrr�rf�binasciir�collectionsrrrrr�typingrr	r
 267  rrr>Zjupyter_client.sessionr
 268  Ztornado.iolooprZzmq.eventloop.zmqstreamrrrrsr�rrr�r.r.r.r/�<module>s63