
    MhE                         d Z ddlZddlZddlmZ ddlmZ ddlmZm	Z	  G d d          Z
 G d d	ej                  Z G d
 de          Z G d de          ZdS )a
  Manage background (threaded) jobs conveniently from an interactive shell.

This module provides a BackgroundJobManager class.  This is the main class
meant for public usage, it implements an object which can create and manage
new background jobs.

It also provides the actual job classes managed by these BackgroundJobManager
objects, see their docstrings below.


This system was inspired by discussions with B. Granger and the
BackgroundCommand class described in the book Python Scripting for
Computational Science, by H. P. Langtangen:

http://folk.uio.no/hpl/scripting

(although ultimately no code from this text was used, as IPython's system is a
separate implementation).

An example notebook is provided in our documentation illustrating interactive
use of the system.
    N)get_ipython)AutoFormattedTB)errordebugc                       e Zd ZdZd Zed             Zed             Zed             Zd Z	d Z
d Zd	 Zd
 Zd Zd ZddZd Zd Zd Zd ZddZdS )BackgroundJobManagera  Class to manage a pool of backgrounded threaded jobs.

    Below, we assume that 'jobs' is a BackgroundJobManager instance.
    
    Usage summary (see the method docstrings for details):

      jobs.new(...) -> start a new job
      
      jobs() or jobs.status() -> print status summary of all jobs

      jobs[N] -> returns job number N.

      foo = jobs[N].result -> assign to variable foo the result of job N

      jobs[N].traceback() -> print the traceback of dead job N

      jobs.remove(N) -> remove (finished) job N

      jobs.flush() -> remove all finished jobs
      
    As a convenience feature, BackgroundJobManager instances provide the
    utility result and traceback methods which retrieve the corresponding
    information from the jobs list:

      jobs.result(N) <--> jobs[N].result
      jobs.traceback(N) <--> jobs[N].traceback()

    While this appears minor, it allows you to use tab completion
    interactively on the job manager instance.
    c                     g | _         g | _        g | _        i | _        g | _        g | _        t          j        | _        t          j	        | _
        t          j        | _        t          j        | _        d| _        d S )Nr   )_running
_completed_deadall_comp_report_dead_reportBackgroundJobBasestat_created_c
_s_createdstat_running_c
_s_runningstat_completed_c_s_completedstat_dead_c_s_dead_current_job_idselfs    Z/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/IPython/lib/backgroundjobs.py__init__zBackgroundJobManager.__init__I   sg     
-<-<->-9     c                 8    |                                   | j        S N)_update_statusr
   r   s    r   runningzBackgroundJobManager.running[   s    }r   c                 8    |                                   | j        S r    )r!   r   r   s    r   deadzBackgroundJobManager.dead`   s    zr   c                 8    |                                   | j        S r    )r!   r   r   s    r   	completedzBackgroundJobManager.completede   s    r   c                    t          |          r'|                    di           }t          |g|R i |}nt          |t                    r}|s#t          j        d          }|j        |j        }}nFt          |          dk    r|d         x}}n(t          |          dk    r|\  }}nt          d          t          |||          }nt          d          |                    dd          rd	|_        | j        |_        | xj        dz  c_        | j                            |           || j        |j        <   t'          d
|j        z             |                                 |S )a@  Add a new background job and start it in a separate thread.

        There are two types of jobs which can be created:

        1. Jobs based on expressions which can be passed to an eval() call.
        The expression must be given as a string.  For example:

          job_manager.new('myfunc(x,y,z=1)'[,glob[,loc]])

        The given expression is passed to eval(), along with the optional
        global/local dicts provided.  If no dicts are given, they are
        extracted automatically from the caller's frame.

        A Python statement is NOT a valid eval() expression.  Basically, you
        can only use as an eval() argument something which can go on the right
        of an '=' sign and be assigned to a variable.

        For example,"print 'hello'" is not valid, but '2+3' is.

        2. Jobs given a function object, optionally passing additional
        positional arguments:

          job_manager.new(myfunc, x, y)

        The function is called with the given arguments.

        If you need to pass keyword arguments to your function, you must
        supply them as a dict named kw:

          job_manager.new(myfunc, x, y, kw=dict(z=1))

        The reason for this asymmetry is that the new() method needs to
        maintain access to its own keywords, and this prevents name collisions
        between arguments to new() and arguments to your own functions.

        In both cases, the result is stored in the job.result field of the
        background job object.

        You can set `daemon` attribute of the thread by giving the keyword
        argument `daemon`.

        Notes and caveats:

        1. All threads running share the same standard output.  Thus, if your
        background jobs generate output, it will come out on top of whatever
        you are currently writing.  For this reason, background jobs are best
        used with silent functions which simply return their output.

        2. Threads also all work within the same global namespace, and this
        system does not lock interactive variables.  So if you send job to the
        background which operates on a mutable object for a long time, and
        start modifying that same mutable object interactively (or in another
        backgrounded job), all sorts of bizarre behaviour will occur.

        3. If a background job is spending a lot of time inside a C extension
        module which does not release the Python Global Interpreter Lock
        (GIL), this will block the IPython prompt.  This is simply because the
        Python interpreter can only switch between threads at Python
        bytecodes.  While the execution is inside C code, the interpreter must
        simply wait unless the extension module releases the GIL.

        4. There is no way, due to limitations in the Python threads library,
        to kill a thread once it has started.kw   r      z4Expression jobs take at most 2 args (globals,locals)zinvalid args for new jobdaemonFTz'Starting job # %s in a separate thread.)callablegetBackgroundJobFunc
isinstancestrsys	_getframe	f_globalsf_localslen
ValueErrorBackgroundJobExpr	TypeErrorr+   r   numr"   appendr   r   start)	r   func_or_expargskwargsr(   jobframegloblocs	            r   newzBackgroundJobManager.newj   sz   B K   	8**T"%%B#K;;;;;;CCS)) 	8 	Na((!OU^cTA!!W$ssTASS LN N N#Ks;;CC6777::h&& 	CJ&!C   7#'ABBB		
r   c                 X    t          |t                    r|n|j        }| j        |         S r    )r/   intr9   r   )r   job_keyr9   s      r   __getitem__z BackgroundJobManager.__getitem__   s(    #GS11Bggw{x}r   c                 *    |                                  S )zAn alias to self.status(),

        This allows you to simply call a job manager instance much like the
        Unix `jobs` shell command.)statusr   s    r   __call__zBackgroundJobManager.__call__   s     {{}}r   c                    | j         | j        | j        }}}| j        | j        | j        }}}t          |          D ]\  }}|j        }	|	|k    r|	|k    r5|                    |           | j	                            |           d||<   N|	|k    r4|                    |           | j
                            |           d||<   t          d|          |dd<   dS )a  Update the status of the job lists.

        This method moves finished jobs to one of two lists:
          - self.completed: jobs which completed successfully
          - self.dead: jobs which finished but died.

        It also copies those jobs to corresponding _report lists.  These lists
        are used to report jobs completed/dead since the last update, and are
        then cleared by the reporting function after each call.FN)r   r   r   r
   r   r   	enumerate	stat_coder:   r   r   filter)
r   srunscompsdeadr"   r&   r$   r9   r?   stats
             r   r!   z#BackgroundJobManager._update_status   s     "_d.?Ue $(=$/4:D "'** 	% 	%HC=Dt||  %%%!((---$C   !((---$D'**


r   c                     |r@t          d|z             |D ]}t          |j        d|           t                       dS dS )zYReport summary for a given job group.

        Return True if the group had any elements.z%s jobs:z : TN)printr9   )r   groupnamer?   s       r   _group_reportz"BackgroundJobManager._group_report   sd    
  	*t#$$$ 1 1377733/0000GGG4	 	r   c           	          t          |          }|r:ddi                    |d          }t          d|d|d|d           g |dd<   d	S dS )
zKFlush a given job group

        Return True if the group had any elements.r)    sz	Flushing  z job.NT)r5   
setdefaultrT   )r   rU   rV   njobsplurals        r   _group_flushz!BackgroundJobManager._group_flush   so    
 E

 	V&&uS11FEUUU444?@@@E!!!H4		 	r   c                     |                                   |                     | j        d          }|                     | j        d          }g | j        dd<   g | j        dd<   |p|S )zPrint the status of newly finished jobs.

        Return True if any new jobs are reported.

        This call resets its own state every time, so it only reports jobs
        which have finished since the last time it was called.	Completedz'Dead, call jobs.traceback() for detailsN)r!   rW   r   r   )r   new_compnew_deads      r   _status_newz BackgroundJobManager._status_new  sz     	%%d&7EE%%d&7&OQ Q!!!!!!!!#8#r   r   c                     |                                   |                     | j        d           |                     | j        d           |                     | j        d           g | j        dd<   g | j        dd<   dS )z3Print a status of all jobs currently being managed.Runningrb   DeadN)r!   rW   r"   r&   r$   r   r   )r   verboses     r   rI   zBackgroundJobManager.status  s     	4<	2224>+66649V,,,!!!!!!!!r   c                 P   	 | j         |         }|j        }|| j        k    rt          d|z             dS || j        k    r| j                            |           dS || j        k    r| j                            |           dS dS # t          $ r t          d|z             Y dS w xY w)z*Remove a finished (completed or dead) job.z0Job #%s is still running, it can not be removed.NJob #%s not found)
r   rM   r   r   r   r&   remover   r$   KeyError)r   r9   r?   rM   s       r   rl   zBackgroundJobManager.remove'  s    	&(3-C IDO++H3NOOOd///%%c*****dl**	  %%%%% +*  	- 	- 	-%+,,,,,,	-s   B B%$B%c                     | j         }| j        | j        z   D ]
}||j        = |                     | j        d          }|                     | j        d          }|s|st          d           dS dS dS )a  Flush all finished jobs (completed and dead) from lists.

        Running jobs are never flushed.

        It first calls _status_new(), to update info. If any jobs have
        completed since the last _status_new() call, the flush operation
        aborts.rb   rh   zNo jobs to flush.N)r   r&   r$   r9   r`   rT   )r   alljobsr?   fl_compfl_deads        r   flushzBackgroundJobManager.flush8  s     (>$)+ 	" 	"C   ##DNK@@##DIv66 	'7 	'%&&&&&	' 	' 	' 	'r   c                 n    	 | j         |         j        S # t          $ r t          d|z             Y dS w xY w)z(result(N) -> return the result of job N.rk   N)r   resultrm   r   )r   r9   s     r   rt   zBackgroundJobManager.resultL  sN    	-8C='' 	- 	- 	-%+,,,,,,	-s    44c                     t          |t                    r|n|j        }	 | j        |                                          d S # t
          $ r t          d|z             Y d S w xY w)Nrk   )r/   rE   r9   r   	tracebackrm   r   )r   r?   r9   s      r   
_tracebackzBackgroundJobManager._tracebackS  sw    S))6ccsw	-HSM##%%%%% 	- 	- 	-%+,,,,,,	-s   A A! A!Nc                     |U|                                   | j        D ]7}t          d|z             |                     |           t                       8d S |                     |           d S )NzTraceback for: %r)r!   r$   rT   rw   )r   r?   deadjobs      r   rv   zBackgroundJobManager.tracebackZ  s    ;!!!9  )G3444((( 
 OOC     r   )r   r    )__name__
__module____qualname____doc__r   propertyr"   r$   r&   rC   rG   rJ   r!   rW   r`   re   rI   rl   rr   rt   rw   rv    r   r   r   r   )   sP        >! ! !$   X   X   X[ [ [z    + + +B
 
 

 
 
$ $ $ 	" 	" 	" 	"& & &"' ' '(- - -- - -! ! ! ! ! !r   r   c                   V    e Zd ZdZdZdZdZdZdZdZ	dZ
d	Zd
 Zd Zd Zd Zd Zd ZdS )r   a  Base class to build BackgroundJob classes.

    The derived classes must implement:

    - Their own __init__, since the one here raises NotImplementedError.  The
      derived constructor must call self._init() at the end, to provide common
      initialization.

    - A strform attribute used in calls to __str__.

    - A call() method, which will make the actual execution call and must
      return a value to be held in the 'result' field of the job object.
    Createdr   rg   r)   rb   r*   z3Dead (Exception), call jobs.traceback() for detailsc                      t          d          )ztMust be implemented in subclasses.

        Subclasses must call :meth:`_init` for standard initialisation.
        z,This class can not be instantiated directly.)NotImplementedErrorr   s    r   r   zBackgroundJobBase.__init__}  s    
 ""PQQQr   c                    dD ]}t          | |          sJ d|z               d| _        t          j        | _        t          j        | _        d| _        d| _        	 t                      j
        j        n#  t          ddd	          j        Y nxY wfd
| _        d| _        t          j                            |            dS )z3Common initialization for all BackgroundJob objects)callstrformzMissing attribute <%s>NFz!<BackgroundJob has not completed>Contextnocolorr)   )modecolor_scheme	tb_offsetc                        d d d           S r    r   )make_tbs   r   <lambda>z)BackgroundJobBase._init.<locals>.<lambda>  s    tT!:!: r   )hasattrr9   r   stat_createdrI   r   rM   finishedrt   r   InteractiveTBtextr   _make_tb_tb	threadingThreadr   )r   attrr   s     @r   _initzBackgroundJobBase._init  s     ' 	G 	GD4%%FF'?$'FFFFF *7*9<	!mm16GG	%Y!   GG
 ;::: !!$'''''s   A5 5Bc                     | j         S r    )r   r   s    r   __str__zBackgroundJobBase.__str__  s
    |r   c                 $    d| j         | j        fz  S )Nz<BackgroundJob #%d: %s>)r9   r   r   s    r   __repr__zBackgroundJobBase.__repr__  s    (DHdl+CCCr   c                 .    t          | j                   d S r    )rT   r   r   s    r   rv   zBackgroundJobBase.traceback  s    dhr   c                 r   	 t           j        | _        t           j        | _        |                                 | _        t           j        | _        t           j        | _        d| _	        d S #  t           j
        | _        t           j        | _        d | _	        d| _        |                                 | _        Y d S xY w)NTz7<BackgroundJob died, call jobs.traceback() for details>)r   stat_runningrI   r   rM   r   rt   stat_completedr   r   	stat_deadr   r   r   r   s    r   runzBackgroundJobBase.run  s    	".;DK.=DN!YY[[DK /=DK.?DN!DMMM	-.8DK.:DN!DMWDK!]]__DHHHHs   ;A( (AB6N)rz   r{   r|   r}   r   r   r   r   r   r   r   r   r   r   r   r   rv   r   r   r   r   r   r   e  s         " LL NQ"2JIKR R R( ( (>  D D D  " " " " "r   r   c                        e Zd ZdZddZd ZdS )r7   zDEvaluate an expression as a background job (uses a separate thread).Nc                     t          |dd          | _        |i n|}|i n|}|x| _        | _        || _        || _        |                                  dS )zCreate a new job from a string which can be fed to eval().

        global/locals dicts can be provided, which will be passed to the eval
        call.z<BackgroundJob compilation>evalN)compilecode
expressionr   rA   rB   r   )r   r   rA   rB   s       r   r   zBackgroundJobExpr.__init__  s_     J'DVLL	\rrtKbbS)33$,	

r   c                 B    t          | j        | j        | j                  S r    )r   r   rA   rB   r   s    r   r   zBackgroundJobExpr.call  s    DIdi111r   )NNrz   r{   r|   r}   r   r   r   r   r   r7   r7     s=        NN    2 2 2 2 2r   r7   c                       e Zd ZdZd Zd ZdS )r.   zARun a function call as a background job (uses a separate thread).c                     t          |          st          d          || _        || _        || _        t          |          | _        |                                  dS )zCreate a new job from a callable object.

        Any positional arguments and keyword args given to this constructor
        after the initial callable are passed directly to it.z4first argument to BackgroundJobFunc must be callableN)r,   r8   funcr=   r>   r0   r   r   )r   r   r=   r>   s       r   r   zBackgroundJobFunc.__init__  sb     ~~ 	HFH H H 		 4yy

r   c                 0     | j         | j        i | j        S r    )r   r=   r>   r   s    r   r   zBackgroundJobFunc.call  s    ty$)3t{333r   Nr   r   r   r   r.   r.     s8        KK  &4 4 4 4 4r   r.   )r}   r1   r   IPythonr   IPython.core.ultratbr   loggingr   r   r   r   r   r7   r.   r   r   r   <module>r      s)   > 


           0 0 0 0 0 0                y! y! y! y! y! y! y! y!x	U" U" U" U" U"	( U" U" U"p2 2 2 2 2) 2 2 2.4 4 4 4 4) 4 4 4 4 4r   