
    <hE                         S r SSKrSSKrSSKJr  SSKJr  SSKJrJ	r	   " S S5      r
 " S S	\R                  5      r " S
 S\5      r " S S\5      rg)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                       \ rS rSrSrS r\S 5       r\S 5       r\S 5       r	S r
S rS	 rS
 rS rS rS rSS jrS rS rS rS rSS jrSrg)BackgroundJobManager)   a  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                    / U l         / U l        / U l        0 U l        / U l        / U l        [        R                  U l        [        R                  U l
        [        R                  U l        [        R                  U l        SU l        g )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    mC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\IPython/lib/backgroundjobs.py__init__BackgroundJobManager.__init__I   sm     
-<<-<<->>-99     c                 :    U R                  5         U R                  $ N)_update_statusr   r   s    r   runningBackgroundJobManager.running[   s    }}r    c                 :    U R                  5         U R                  $ r"   )r#   r   r   s    r   deadBackgroundJobManager.dead`   s    zzr    c                 :    U R                  5         U R                  $ r"   )r#   r   r   s    r   	completedBackgroundJobManager.completede   s    r    c                    [        U5      (       a"  UR                  S0 5      n[        U/UQ70 UD6nO[        U[        5      (       aw  U(       d.  [
        R                  " S5      nUR                  UR                  pO5[        U5      S:X  a  US   =pxO[        U5      S:X  a  Uu  pxO[        S5      e[        XU5      nO[        S5      eUR                  SS5      (       a  S	Ul        U R                  Ul        U =R                  S-  sl        U R                   R#                  U5        XPR$                  UR                  '   ['        S
UR                  -  5        UR)                  5         U$ )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	TypeErrorr0   r   numr$   appendr   r   start)	r   func_or_expargskwargsr-   jobframegloblocs	            r   newBackgroundJobManager.newj   s0   B K  **T"%B#K;;;CS))a(!OOU^^cTA!!W$sTAS LN N#Ks;C677::h&&CJ&&!C 7#''AB		
r    c                 f    [        U[        5      (       a  UOUR                  nU R                  U   $ r"   )r4   intr>   r   )r   job_keyr>   s      r   __getitem__ BackgroundJobManager.__getitem__   s'    #GS11gw{{xx}r    c                 "    U R                  5       $ )zzAn 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__BackgroundJobManager.__call__   s     {{}r    c                    U R                   U R                  U R                  p2nU R                  U R                  U R
                  pen[        U5       H  u  pxUR                  n	X:X  a  M  X:X  a2  UR                  U5        U R                  R                  U5        SXG'   MO  X:X  d  MV  UR                  U5        U R                  R                  U5        SXG'   M     [        SU5      USS& g)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'   r>   rD   stats
             r   r#   #BackgroundJobManager._update_status   s     "__d.?.?U $(==$//4::D "'*HC==D|  %!!((-$C !!((-$ + D'*
r    c                     U(       a>  [        SU-  5        U H  n[        UR                  < SU< 35        M!     [        5         gg)zQReport summary for a given job group.

Return True if the group had any elements.z%s jobs:z : TN)printr>   )r   groupnamerD   s       r   _group_report"BackgroundJobManager._group_report   s<    
 *t#$3773/0 G r    c           	          [        U5      nU(       a2  SS0R                  US5      n[        SU< SU< SU< S35        / USS& g	g)
zCFlush a given job group

Return True if the group had any elements.r.    sz	Flushing  z job.NT)r:   
setdefaultr]   )r   r^   r_   njobsplurals        r   _group_flush!BackgroundJobManager._group_flush   sF    
 E
V&&uS1FU4?@E!H	 r    c                     U R                  5         U R                  U R                  S5      nU R                  U R                  S5      n/ U R                  SS& / U R                  SS& U=(       d    U$ )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#   r`   r   r   )r   new_compnew_deads      r   _status_new BackgroundJobManager._status_new  so     	%%d&7&7E%%d&7&7&OQ!!!!#8#r    c                    U R                  5         U R                  U R                  S5        U R                  U R                  S5        U R                  U R                  S5        / U R
                  SS& / U R                  SS& g)z3Print a status of all jobs currently being managed.Runningrm   DeadN)r#   r`   r$   r*   r'   r   r   )r   verboses     r   rP   BackgroundJobManager.status  sl     	4<<	24>>+6499V,!!!!r    c                 `    U R                   U   nUR                  nX0R                  :X  a  [        SU-  5        gX0R                  :X  a  U R
                  R                  U5        gX0R                  :X  a  U R                  R                  U5        gg! [         a    [        SU-  5         gf = f)z*Remove a finished (completed or dead) job.z0Job #%s is still running, it can not be removed.NJob #%s not found)
r   rU   r   r   r   r*   remover   r'   KeyError)r   r>   rD   rU   s       r   ry   BackgroundJobManager.remove'  s    	&((3-C IOO+H3NO///%%c*ll*		  % +  	-%+,	-s   B B-,B-c                    U R                   nU R                  U R                  -    H  nXR                  	 M     U R	                  U R                  S5      nU R	                  U R                  S5      nU(       d  U(       d  [        S5        ggg)zFlush 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.rm   rt   zNo jobs to flush.N)r   r*   r'   r>   rj   r]   )r   alljobsrD   fl_compfl_deads        r   flushBackgroundJobManager.flush8  sq     ((>>$))+C  , ##DNNK@##DIIv67%& #r    c                 r     U R                   U   R                  $ ! [         a    [        SU-  5         gf = f)z(result(N) -> return the result of job N.rx   N)r   resultrz   r   )r   r>   s     r   r   BackgroundJobManager.resultL  s8    	-88C=''' 	-%+,	-s    66c                     [        U[        5      (       a  UOUR                  n U R                  U   R	                  5         g ! [
         a    [        SU-  5         g f = f)Nrx   )r4   rK   r>   r   	tracebackrz   r   )r   rD   r>   s      r   
_tracebackBackgroundJobManager._tracebackS  sO    S))csww	-HHSM##% 	-%+,	-s   A AANc                     UcM  U R                  5         U R                   H,  n[        SU-  5        U R                  U5        [        5         M.     g U R                  U5        g )NzTraceback for: %r)r#   r'   r]   r   )r   rD   deadjobs      r   r   BackgroundJobManager.tracebackZ  sN    ;!99)G34( %
 OOC r    )r   r   r   r   r   r   r   r   r   r   r   )r   r"   )__name__
__module____qualname____firstlineno____doc__r   propertyr$   r'   r*   rH   rM   rQ   r#   r`   rj   rp   rP   ry   r   r   r   r   __static_attributes__ r    r   r   r   )   s    >!$      [z+B

$ 	"&"'(--!r    r   c                   \    \ rS rSrSrSrSrSrSrSr	Sr
S	rS
rS rS rS rS rS rS rSrg)r   ie  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   rs   r.   rm   r/   z3Dead (Exception), call jobs.traceback() for detailsc                     [        S5      e)zdMust be implemented in subclasses.

Subclasses must call :meth:`_init` for standard initialisation.
z,This class can not be instantiated directly.)NotImplementedErrorr   s    r   r   BackgroundJobBase.__init__}  s    
 ""PQQr    c                   ^ S H  n[        X5      (       a  M   SU-  5       e   SU l        [        R                  U l        [        R
                  U l        SU l        SU l         [        5       R                  R                  mU4S
 jU l        SU l        [        R                   R#                  U 5        g!   [        SSSS	9R                  m NK= f)z3Common initialization for all BackgroundJob objects)callstrformzMissing attribute <%s>NFz!<BackgroundJob has not completed>Contextnocolorr.   )modecolor_scheme	tb_offsetc                     > T " S S S 5      $ r"   r   )make_tbs   r   <lambda>)BackgroundJobBase._init.<locals>.<lambda>  s    tT!:r    )hasattrr>   r   stat_createdrP   r   rU   finishedr   r   InteractiveTBtextr   _make_tb_tb	threadingThreadr   )r   attrr   s     @r   _initBackgroundJobBase._init  s     'D4%%F'?$'FF% ' *77*99<	!m1166G ; !!$'	%Y!d s   %B5 5Cc                     U R                   $ r"   )r   r   s    r   __str__BackgroundJobBase.__str__  s    ||r    c                 8    SU R                   U R                  4-  $ )Nz<BackgroundJob #%d: %s>)r>   r   r   s    r   __repr__BackgroundJobBase.__repr__  s    (DHHdll+CCCr    c                 .    [        U R                  5        g r"   )r]   r   r   s    r   r   BackgroundJobBase.traceback  s    dhhr    c                     [         R                  U l        [         R                  U l        U R                  5       U l        [         R                  U l        [         R                  U l        SU l	        g !   [         R                  U l        [         R                  U l        S U l	        SU l        U R                  5       U l         g = f)NTz7<BackgroundJob died, call jobs.traceback() for details>)r   stat_runningrP   r   rU   r   r   stat_completedr   r   	stat_deadr   r   r   r   s    r   runBackgroundJobBase.run  s    	".;;DK.==DN!YY[DK /==DK.??DN!DM	-.88DK.::DN!DMWDK!]]_DHs   ?A3 3AC)r   r   r   r>   r   rU   rP   N)r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r    r   r   r   e  sO    " LL NQ"2JIKR(>D"r    r   c                   (    \ rS rSrSrSS jrS rSrg)r<   i  zDEvaluate an expression as a background job (uses a separate thread).Nc                     [        USS5      U l        Uc  0 OUnUc  0 OUnU=U l        U l        X l        X0l        U R                  5         g)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   rF   rG   r   )r   r   rF   rG   s       r   r   BackgroundJobExpr.__init__  sL     J'DVL	\rtKbS)33$,	

r    c                 X    [        U R                  U R                  U R                  5      $ r"   )r   r   rF   rG   r   s    r   r   BackgroundJobExpr.call  s    DIIdii11r    )r   r   rF   rG   r   )NNr   r   r   r   r   r   r   r   r   r    r   r<   r<     s    N 2r    r<   c                   $    \ rS rSrSrS rS rSrg)r3   i  zARun a function call as a background job (uses a separate thread).c                     [        U5      (       d  [        S5      eXl        X l        X0l        [        U5      U l        U R                  5         g)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)r1   r=   funcrB   rC   r5   r   r   )r   r   rB   rC   s       r   r   BackgroundJobFunc.__init__  sF     ~~FH H 		 4y

r    c                 N    U R                   " U R                  0 U R                  D6$ r"   )r   rB   rC   r   s    r   r   BackgroundJobFunc.call  s    yy$))3t{{33r    )rB   r   rC   r   Nr   r   r    r   r3   r3     s    K&4r    r3   )r   r6   r   IPythonr   IPython.core.ultratbr   loggingr   r   r   r   r   r<   r3   r   r    r   <module>r      sW   >    0  y! y!x	U"	(( U"p2) 2.4) 4r    