wL iEdZddlZddlZddlmZddlmZddlmZm Z GddZ Gdd ejZ Gd d e Z Gd d e Zy)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)errordebugceZdZdZdZedZedZedZdZ dZ dZ d Z d Z d Zd Zdd ZdZdZdZdZddZy)BackgroundJobManageraClass 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. cg|_g|_g|_i|_g|_g|_t j|_t j|_ t j|_ t j|_d|_y)Nr)_running _completed_deadall _comp_report _dead_reportBackgroundJobBasestat_created_c _s_createdstat_running_c _s_runningstat_completed_c _s_completed stat_dead_c_s_dead_current_job_idselfs `/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/IPython/lib/backgroundjobs.py__init__zBackgroundJobManager.__init__Ism  -<<-<<->>-99  c:|j|jSN)_update_statusr rs rrunningzBackgroundJobManager.running[s }}rc:|j|jSr )r!r rs rdeadzBackgroundJobManager.dead`s zzrc:|j|jSr )r!r rs r completedzBackgroundJobManager.completedes rct|r"|jdi}t|g|i|}nt|trs|s.t j d}|j|j}}n5t|dk(r|dx}}nt|dk(r|\}}n tdt|||}n td|jddrd |_ |j|_|xjdz c_|j j#|||j$|j<t'd |jz|j)|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.kwrz4Expression jobs take at most 2 args (globals,locals)zinvalid args for new jobdaemonFTz'Starting job # %s in a separate thread.)callablegetBackgroundJobFunc isinstancestrsys _getframe f_globalsf_localslen ValueErrorBackgroundJobExpr TypeErrorr+rnumr"appendr rstart) r func_or_expargskwargsr(jobframegloblocs rnewzBackgroundJobManager.newjs-B K **T"%B#K;;;C  S ) a(!OOU^^cTA!!W$sTAS LNN#Ks;C67 7 ::h &CJ&& ! C  7#''AB  rc\t|tr|n |j}|j|Sr )r/intr9r )rjob_keyr9s r __getitem__z BackgroundJobManager.__getitem__s$#GS1gw{{xx}rc"|jS)zAn alias to self.status(), This allows you to simply call a job manager instance much like the Unix `jobs` shell command.)statusrs r__call__zBackgroundJobManager.__call__s {{}rc|j|j|j}}}|j|j|j }}}t |D]\}}|j} | |k(r| |k(r2|j||jj|d||<O| |k(sU|j||jj|d||<td||ddy)aUpdate 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) rrrr r r enumerate stat_coder:rrfilter) rsrunscompsdeadr"r&r$r9r?stats rr!z#BackgroundJobManager._update_statuss"__d.?.?Ue$(==$//4::D"'* %HC==Dt|  %!!((-$  C !!((-$  %D'* rc||r:td|z|D]}t|jd|tyy)zYReport summary for a given job group. Return True if the group had any elements.z%s jobs:z : TN)printr9)rgroupnamer?s r _group_reportz"BackgroundJobManager._group_reportsA  *t# $ 13773/0 1 G rc |t|}|r/ddij|d}td|d|d|dg|ddy y) zKFlush a given job group Return True if the group had any elements.r)sz Flushing  z job.NT)r5 setdefaultrT)rrUrVnjobsplurals r _group_flushz!BackgroundJobManager._group_flushsF E  V&&uS1F U4? @E!H rc|j|j|jd}|j|jd}g|jddg|jdd|xs|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!rWrr)rnew_compnew_deads r _status_newz BackgroundJobManager._status_new so %%d&7&7E%%d&7&7&OQ!!!!#8#rc|j|j|jd|j|jd|j|jdg|j ddg|j ddy)z3Print a status of all jobs currently being managed.RunningrbDeadN)r!rWr"r&r$rr)rverboses rrIzBackgroundJobManager.statussl  4<< 2 4>>+6 499V,!!!!rc^ |j|}|j}||jk(rtd|zy||jk(r|j j |y||jk(r|jj |yy#t$rtd|zYywxYw)z*Remove a finished (completed or dead) job.z0Job #%s is still running, it can not be removed.NJob #%s not found) r rMrrrr&removerr$KeyError)rr9r?rMs rrlzBackgroundJobManager.remove's &((3-C IDOO+H3NOd///%%c*dll*   %+ - %+ , -sBB,+B,c|j}|j|jzD]}||j=|j |jd}|j |jd}|s|s t dyyy)aFlush 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.rbrhzNo jobs to flush.N)r r&r$r9r`rT)ralljobsr?fl_compfl_deads rflushzBackgroundJobManager.flush8sx((>>$))+ "C  "##DNNK@##DIIv67 % &#rcp |j|jS#t$rtd|zYywxYw)z(result(N) -> return the result of job N.rkN)r resultrmr)rr9s rrtzBackgroundJobManager.resultLs8 -88C='' ' - %+ , -s 55ct|tr|n |j} |j|j y#t $rt d|zYywxYw)Nrk)r/rEr9r tracebackrmr)rr?r9s r _tracebackzBackgroundJobManager._tracebackSsLS)csww - HHSM # # % - %+ , -s>AANc|K|j|jD]+}td|z|j|t-y|j|y)NzTraceback for: %r)r!r$rTrw)rr?deadjobs rrvzBackgroundJobManager.tracebackZsS ;    !99 )G34(  OOC r)rr )__name__ __module__ __qualname____doc__rpropertyr"r$r&rCrGrJr!rWr`rerIrlrrrtrwrvrrrr)s>!$[z+B  $ "&"'(--!rrcTeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZy)raBase 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. Createdrrgr)rbr*z3Dead (Exception), call jobs.traceback() for detailsctd)ztMust be implemented in subclasses. Subclasses must call :meth:`_init` for standard initialisation. z,This class can not be instantiated directly.)NotImplementedErrorrs rrzBackgroundJobBase.__init__}s ""PQQrcdD]}t||rJd|zd|_tj|_tj |_d|_d|_ tjjfd |_ d|_tj j#|y#tddd jYMxYw) z3Common initialization for all BackgroundJob objects)callstrformzMissing attribute <%s>NFz!Contextnocolorr))mode color_scheme tb_offsetcdddSr r)make_tbsrz)BackgroundJobBase._init..stT!:r)hasattrr9r stat_createdrIrrMfinishedrtr InteractiveTBtextr_make_tb_tb threadingThreadr)rattrrs @r_initzBackgroundJobBase._inits' GD4% F'?$'F F% G*77 *99 <  !m1166G; !!$' %Y!d s B..C c|jSr )rrs r__str__zBackgroundJobBase.__str__s ||rc8d|j|jfzS)Nz)r9rrs r__repr__zBackgroundJobBase.__repr__s(DHHdll+CCCrc.t|jyr )rTrrs rrvzBackgroundJobBase.tracebacks  dhhrc tj|_tj|_|j |_tj|_tj|_d|_ y#tj|_tj|_d|_ d|_|j|_ YyxYw)NTz7)r stat_runningrIrrMrrtstat_completedrr stat_deadrrrrs rrunzBackgroundJobBase.runs ".;;DK.==DN!YY[DK/==DK.??DN!DM -.88DK.::DN!DMWDK!]]_DHs ?A33ACN)rzr{r|r}rrrrrrrrrrrrrvrrrrrresO "LL NQ"2JIKR(>D"rrceZdZdZddZdZy)r7zDEvaluate an expression as a background job (uses a separate thread).Nct|dd|_|in|}|in|}|x|_|_||_||_|j y)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.zevalN)compilecode expressionrrArBr)rrrArBs rrzBackgroundJobExpr.__init__sPJ'DVL \rtKbS)33$,  rcXt|j|j|jSr )rrrArBrs rrzBackgroundJobExpr.callsDIIdii11r)NNrzr{r|r}rrrrrr7r7sN 2rr7ceZdZdZdZdZy)r.zARun a function call as a background job (uses a separate thread).ct|s td||_||_||_t ||_|jy)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,r8funcr=r>r0rr)rrr=r>s rrzBackgroundJobFunc.__init__sJ ~FH H   4y  rcN|j|ji|jSr )rr=r>rs rrzBackgroundJobFunc.calls tyy$))3t{{33rNrrrrr.r.sK&4rr.)r}r1rIPythonrIPython.core.ultratbrloggingrrrrrr7r.rrrrsW> 0 y!y!x U" ((U"p2)2.4)4r