o
    wi                     @   s  d dl mZ d dlmZ d dlmZ d dlmZ d dlZd dl	Z	d dl
Z
d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZe
jdd Zedk r^d dlmZ nd dlZd	d
 Ze
jdk rudXddZed n	edZdXddZze W n e y   e!ZY nw dd Z"edd Z#dd Z$dd Z%dd Z&dd Z'e
j(dkZ)G dd  d e*Z+d!d" Z,dYd$d%Z-d&d' Z.G d(d) d)e/Z0G d*d+ d+e/Z1G d,d- d-ej2Z3d.d/ Z4e4ej5_4dZd0d1Z6ze	j78d2d39d4Z:W n   e;ed5e	j7 d6d7 Z<d8d9 Z=G d:d; d;e/Z>e>d g d<d= d>D Z?G d?d@ d@e>Z@G dAdB dBe>ZAdCdD ZBG dEdF dFe>ZCG dGdH dHe/ZDG dIdJ dJejEZFG dKdL dLe/ZGG dMdN dNeGZHG dOdP dPeGZI	 G dQdR dRe/ZJG dSdT dTe/ZKd[dVdWZLdS )\    )with_statement)contextmanager)
attrgetter)gettextN   )      )load_sourcec                 C   s*   t j| |}t j|}|j| |S N)	importlibutilspec_from_file_locationmodule_from_specloaderexec_module)dotnamepathspecmod r   E/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/plac_ext.pyr	      s   r	   3c                 C   sB   |d u rt d}|j}|d u r|j}~n|d u r|}td d S )N   zexec _code_ in _globs_, _locs_)sys	_getframe	f_globalsf_localsexec)_code__globs__locs_framer   r   r   exec_#   s   
r"   z>
def raise_(tp, value=None, tb=None):
    raise tp, value, tb
r   c                 C   sH   |durt | trtd|dur| |}n| }|j|ur"|||)z
        A function that matches the Python 2.x ``raise`` statement. This
        allows re-raising exceptions with the cls value and traceback on
        Python 2 and 3.
        Nz0instance exception may not have a separate value)
isinstance	Exception	TypeError__traceback__with_traceback)tpvaluetbexcr   r   r   raise_5   s   


r,   c                 C   s(   z|  dW S  ty   t|  Y S w )z:
    Decode an object assuming the encoding is UTF-8.
    zutf-8)decodeAttributeErrorstr)valr   r   r   r-   K   s
   r-   c                 c   s*    t j}| t _z	dV  W |t _dS |t _w )z8usage: with stdout(file('out.txt', 'a')): do_something()N)r   stdout)fileobjorig_stdoutr   r   r   r1   Y   s   r1   c                 C   s   t jt|  t j  dS )z2Write str(x) on stdout and flush, no newline addedN)r   r1   writer/   flush)xr   r   r   r4   d   s   r4   c                 c   s    | V  dS )z/Return a generator object with a single elementNr   )r)   r   r   r   gen_valj   s   
r7   c                 c   s    t | || dV  dS )z.Return a generator object raising an exceptionN)r,   )etyper+   r*   r   r   r   gen_exco   s   
r9   c                 C   sN   t jddgt jd}z|j|  W n	 ty   Y nw |j  |  dS )zSend a text to less via a pipeless-c)stdinN)
subprocessPopenPIPEr<   r4   IOErrorclosewait)textpor   r   r   r:   u   s   
r:   win32c                   @      e Zd ZdS )TerminatedProcessN__name__
__module____qualname__r   r   r   r   rG          rG   c                 C   s   t r
   )rG   )signumr!   r   r   r   terminatedProcess      rN    c                 C   s$   t | tr
| |S t| |  S )z4Read a line from stdin, using readline when possible)r#   ReadlineInputreadliner4   )r<   promptr   r   r   	read_line   s   

rT   c                 c   sb    	 g }	 |   }|sdS | }|sq|d |kr$||dd  n|| qd|V  q)z
    Read multiple lines from stdin until the terminator character is found,
    then yield a single space-separated long line.
    TN )rR   stripappendjoin)r<   
terminatorlinesliner   r   r   read_long_line   s"   
r]   c                   @   sD   e Zd ZdZdddZdd Zdd	 Zd
d ZdddZdd Z	dS )rQ   zA
    An iterable with a .readline method reading from stdin.
    TNc                 C   sN   || _ || _|| _|sdd |D | _ dd l}|| _|d || j d S )Nc                 S      g | ]}|  qS r   )upper).0cr   r   r   
<listcomp>       z*ReadlineInput.__init__.<locals>.<listcomp>r   ztab: complete)completionscase_sensitivehistfilerR   rlparse_and_bindset_completercomplete)selfrd   re   rf   rR   r   r   r   __init__   s   
zReadlineInput.__init__c                 C   sB   | j  | _z| jr| j | j W | S W | S  ty    Y | S w r
   )rg   get_completerold_completerrf   read_history_filer@   rk   r   r   r   	__enter__   s   zReadlineInput.__enter__c                 C   s*   | j | j | jr| j | j d S d S r
   )rg   ri   rn   rf   write_history_file)rk   r8   r+   r*   r   r   r   __exit__   s   zReadlineInput.__exit__c                    s>   | j s   z fdd| jD | W S  ty   Y d S w )Nc                    s   g | ]	}|  r|qS r   
startswith)r`   kkwr   r   rb          z*ReadlineInput.complete.<locals>.<listcomp>)re   r_   rd   
IndexError)rk   rx   stater   rw   r   rj      s   zReadlineInput.completerP   c                 C   s$   zt |d W S  ty   Y dS w )N
rP   )	raw_inputEOFError)rk   rS   r   r   r   rR      s
   zReadlineInput.readlinec                 C   s   t | jdS NrP   )iterrR   rp   r   r   r   __iter__      zReadlineInput.__iter__)TNrP   )
rI   rJ   rK   __doc__rl   rq   rs   rj   rR   r   r   r   r   r   rQ      s    
	
	rQ   c                   @   s4   e Zd ZdZedd Zdd Zdd Zdd	 Zd
S )HelpSummaryz7Build the help summary consistently with the cmd modulec                 C   s   t |}tj|  d}|jd |dt|dd |dt|jdd |dt|j	dd |dt|j
dd t|j|_d S )	N)r1   r|   special commands   P   zcustom commands"commands run in external processesthreaded commands)	plac_coreparser_fromcmdCmdr1   r4   print_topicssortedcommands
mpcommands
thcommandsr/   helpsummary)clsobjspecialcommandspra   r   r   r   add   s    

zHelpSummary.addc                 C   s
   g | _ d S r
   )_lsrp   r   r   r   rl      s   
zHelpSummary.__init__c                 C      | j | d S r
   )r   rX   )rk   sr   r   r   r4         zHelpSummary.writec                 C   s   d | jS r   )rY   r   rp   r   r   r   __str__   r   zHelpSummary.__str__N)	rI   rJ   rK   r   classmethodr   rl   r4   r   r   r   r   r   r      s    
r   c                       s   e Zd Z fddZ  ZS )PlacFormatterc                    s4   |j pi }tdd | D |_ tt| ||S )z.Remove special commands from the usage messagec                 s   s&    | ]\}}| d s||fV  qdS ).Nrt   )r`   nra   r   r   r   	<genexpr>   s   
 z3PlacFormatter._metavar_formatter.<locals>.<genexpr>)choicesdictitemssuperr   _metavar_formatter)rk   actiondefault_metavarr   	__class__r   r   r      s
   

z PlacFormatter._metavar_formatter)rI   rJ   rK   r   __classcell__r   r   r   r   r      s    r   c                 C   s,   z| j W S  ty   ttj|   Y S w )z:Attached to plac_core.ArgumentParser for plac interpreters)r   r.   r   r   ArgumentParserformat_helprp   r   r   r   r     s
   r   c                 c   s    t | }|du r| V  dS |jj|}|du r%td| V  dS t| ddro| }||_	|
|jdd |jD |j ||j |jD ]}||j ||j |dd |jD  |  qJ| V  dS | V  dS )	z3The default help functionality in plac interpretersNzUnknown command %s
_interact_Fc                 S   s   g | ]	}|j d kr|qS )helpdestr`   ar   r   r   rb     ry   z default_help.<locals>.<listcomp>c                 s   s    | ]
}|j d kr|V  qdS )r   Nr   r   r   r   r   r   !  s    
zdefault_help.<locals>.<genexpr>)r   r   r   
subparsers_name_parser_mapget_getattr_get_formatter_prog	add_usageusage_actions_mutually_exclusive_groupsadd_textdescription_action_groupsstart_sectiontitleadd_arguments_group_actionsend_section)r   r   parsersubp	formatteraction_groupr   r   r   default_help  s.   



r   PLACPATHr   :z#Ill-formed PLACPATH: got %PLACPATHsc                 C   s   t | j}|js|js|jrtdd|j}|r|d7 }d||f }t	| d}t
|| |d }d|_t| rDt| jdi |_nt| di |_d	|jd
< t ||S )zBCall a container factory with the arglist and return a plac objectzJInterpreter.call must be invoked on factories with required arguments onlyz, ,zzdef makeobj(interact, %s *args):
    obj = factory(%s)
    obj._interact_ = interact
    obj._args_ = args
    return obj
)factorymakeobjF__annotations__)zstart interactive interpreterflagiinteract)r   r   argspecdefaultsvarargsvarkwr%   rY   argsr   r"   add_helpinspectisclassr   rl   r   call)r   arglistr   required_argscodedicr   r   r   r   partial_call0  s,   



r   c           	      G   s   d| v r|  d\} }nd}tj| s1tD ]}tj|| }tj|r' n	qttd|  n| }tj	tj
|\}}t||}|rPtt|||}|S |j}|S )zs
    A utility to import the main function of a plac tool. It also
    works with command container factories.
    r   NzCannot find %s)splitosr   isabsPLACDIRSrY   existsImportErrorr   splitextbasenamer	   r   r   main)	r   r   factory_nameplacdirfullpathnameextmoduletoolr   r   r   import_mainM  s&   
r   c                   @   sn   e Zd ZdZdZdd Zdd Zddd	Zd
d Zdd Z	dd Z
dd Zedd Zedd Zdd ZdS )BaseTaskz
    A task is a wrapper over a generator object with signature
    Task(no, arglist, genobj), attributes
    .no
    .arglist
    .outlist
    .str
    .etype
    .exc
    .tb
    .status
    and methods .run and .kill.
    )	SUBMITTEDRUNNING
TOBEKILLEDKILLEDFINISHEDABORTEDc                 C   s<   || _ || _| || _d\| _| _| _| _d| _g | _	d S )N)rP   NNNr   )
nor   _wrap_genobjr/   r8   r+   r*   statusoutlistrk   r   r   genobjr   r   r   rl   |  s   
zBaseTask.__init__c                 C      dS )z2Notifies the underlying monitor. To be implementedNr   rk   msgr   r   r   notify      zBaseTask.notifyFc              
   c   s    d| _ z"|D ]}| j dkrt|dur!| j| | t| dV  qW n> tjy3   |     tt	t
fyB   d| _ Y dS  tyd   t \| _| _}|r[dt|n|| _d| _ Y dS w |   dS )z
        Wrap the genobj into a generator managing the exceptions,
        populating the .outlist, setting the .status and yielding None.
        stringify_tb must be True if the traceback must be sent to a process.
        r   r   Nr   rP   r   )r   GeneratorExitr  rX   r  r-   InterpreterExit_regular_exitrG   KeyboardInterruptr$   r   exc_infor8   r+   rY   	traceback	format_tbr*   )rk   r  stringify_tbr)   r*   r   r   r   r     s,   
zBaseTask._wrapc                 C   s<   d| _ zdtt| j| _W d S  ty   d| _Y d S w )Nr   r|   z	no result)r   rY   mapr-   r  r/   rz   rp   r   r   r   r    s   zBaseTask._regular_exitc                 C   s   | j D ]}qdS )zRun the inner generatorN)r   )rk   noner   r   r   run  s   
zBaseTask.runc                 C   s
   d| _ dS )zSet a TOBEKILLED statusr   Nr   rp   r   r   r   kill  s   
zBaseTask.killc                 C   r  )z-Wait for the task to finish: to be overriddenNr   rp   r   r   r   rB     r  zBaseTask.waitc                 C   s6   | j du rdS t| j ttfr| j S dt| j S )z1Return the traceback as a (possibly empty) stringNrP   )r*   r#   r/   bytesrY   r  r  rp   r   r   r   r    s
   
zBaseTask.tracebackc                 C   sT   |    | jr t| jttfr| | jt| j| j| jpd  | js%d S | jd S )NrU   )	rB   r+   r#   r*   r/   r  r8   r,   r  rp   r   r   r   result  s   
zBaseTask.resultc                 C   s    d| j j| jd| j| jf S )zDString representation containing class name, number, arglist, statusz<%s %d [%s] %s>rV   )r   rI   r   rY   r   r   rp   r   r   r   __repr__  s   
zBaseTask.__repr__NF)rI   rJ   rK   r   STATESrl   r  r   r  r  r  rB   propertyr  r  r  r   r   r   r   r   k  s    

	
r   c                 c   s    | ]}d V  qdS )skipNr   )r`   dummyr   r   r   r     s    r   )r   c                   @   s   e Zd ZdZdd ZdS )SynTaskzn
    Synchronous task running in the interpreter loop and displaying its
    output as soon as available.
    c                 C   s*   | j rd| j j| jf S dtt| jS )z-Return the output string or the error messagez%s: %sr|   )r8   rI   r+   rY   r  r/   r  rp   r   r   r   r     s   zSynTask.__str__N)rI   rJ   rK   r   r   r   r   r   r   r    s    r  c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )ThreadedTaskz/
    A task running in a separated thread.
    c                    s*   t | ||| tjtt| jd| _d S )Ntarget)r   rl   	threadingThreadr   r   r  threadr  r   r   r   rl     s   zThreadedTask.__init__c                 C      | j   dS )zRun the task into a threadN)r%  startrp   r   r   r   r       zThreadedTask.runc                 C   r&  )zBlock until the thread endsN)r%  rY   rp   r   r   r   rB     r(  zThreadedTask.wait)rI   rJ   rK   r   rl   r  rB   r   r   r   r   r   r     s
    r   c                    s$    fdd} fdd}t ||S )z-Return a property to be attached to an MPTaskc                    s   zt | j W S     Y S r
   )r   nsrp   r   on_errorr   r   r     s   zsharedattr.<locals>.getc                    s"   z
t | j | W d S    Y d S r
   )setattrr)  )rk   r)   )r   r   r   set  s   zsharedattr.<locals>.set)r  )r   r+  r   r-  r   r*  r   
sharedattr  s   
r.  c                       s~   e Zd ZdZeddZeddZeddZeddZedd	Z	e
d
d Zdd Z fddZdd Zdd Zdd Z  ZS )MPTaskz
    A task running as an external process. The current implementation
    only works on Unix-like systems, where multiprocessing use forks.
    r/   rP   r8   Nr+   r*   r   r   c                 C   s   z| j W S    g  Y S r
   )_outlistrp   r   r   r   r    s   zMPTask.outlistc                 C   s   | j | j| d S r
   )mannotify_listenerr   r  r   r   r   r    s   zMPTask.notifyc                    st   || _ || _| j|dd| _|| _|j | _|j | _	d| _
d\| _| _| _t| | _tjtt| jd| _dS )zS
        The monitor has a .send method and a .man multiprocessing.Manager
        T)r  r   NNNr!  N)r   r   r   r   r1  mplistr0  	Namespacer)  r   r8   r+   r*   reprr/   multiprocessingProcessr   r/  r  proc)rk   r   r   r  managerr   r   r   rl     s   
zMPTask.__init__c                 C   r&  )z%Run the task into an external processN)r:  r'  rp   r   r   r   r  +  r(  z
MPTask.runc                 C   r&  )z2Block until the external process ends or is killedN)r:  rY   rp   r   r   r   rB   /  r(  zMPTask.waitc                 C   r&  )z^Kill the process with a SIGTERM inducing a TerminatedProcess
        exception in the childrenN)r:  	terminaterp   r   r   r   r  3  s   zMPTask.kill)rI   rJ   rK   r   r.  r/   r8   r+   r*   r   r  r  r  rl   r  rB   r  r   r   r   r   r   r/    s    





r/  c                   @   s   e Zd ZdZdZedgZdd Zdd Zdd
dZ	e
jddd	efddddZe
jddd	eejfddddZe
jddd	efddddZe
jddd	efddddZd	S )TaskManagerzl
    Store the given commands into a task registry. Provides methods to
    manage the submitted tasks.
    r   z.last_tbc                 C   s   || _ i | _|js|jr| jg d t|dd}tj||r!dnd t	d| _
t|| j |jr4t nd | _ttjt d S )N)z.killz.listz.outputr   FrP   )progformatter_class)r   registryr   r   r   updater   r   r   r   r   r   r   Managerr1  signalSIGTERMrN   )rk   r   r   r   r   r   rl   C  s   zTaskManager.__init__c                 C   sP   | j  D ]}z|jdkr|  |  W q   Y q| jr&| j  dS dS )zKill all the running tasksr   N)r@  valuesr   r  rB   r1  stop)rk   taskr   r   r   rA   O  s   
zTaskManager.closerU   Nc                    sn   |dk sJ d r fdd| j  D }n
dd | j  D }|jtdd t|t|kr5|| S dS )	z/Get the latest submitted task from the registryr   zYou must pass a negative numberc                    s   g | ]	}|j  kr|qS r   r  r`   tr  r   r   rb   _  s    
z+TaskManager._get_latest.<locals>.<listcomp>c                 S   s   g | ]}|qS r   r   rH  r   r   r   rb   b  s    r   )keyN)r@  rE  sortr   lenabs)rk   tasknor   tasksr   r  r   _get_latest[  s   zTaskManager._get_latestztask to kill
positional)rN  c                 c   sx    |dk r| j |dd}|du rdV  dS n|| jvr"d| V  dS | j| }|jdv r3d| V  dS |  |V  dS )	z8kill the given task (-1 to kill the latest running task)r   r   r  NzNothing to killUnknown task %d)r   r   r   zAlready finished %s)rP  r@  r   r  rk   rN  rG  r   r   r   r  i  s    





zTaskManager.killrP   r  r   c                 c   s&    | j  D ]
}|j|kr|V  qdS )zlist tasks with a given statusN)r@  rE  r   )rk   r   rG  r   r   r   r5  }  s   
zTaskManager.listztask numberc                 c   s    |dk r|  |}|du rdV  dS n|| jvr d| V  dS | j| }dtt|j}|rAt|d| d||f V  dS |V  t|jdkrSt	rSt
| dS |V  dS )	zBshow the output of a given task (and optionally save it to a file)r   NNothing to showrR  r|   wzsaved output of %d into %s   )rP  r@  rY   r  r/   r  openr4   rL  use_lessr:   )rk   rN  fnamerG  outstrr   r   r   output  s(   




zTaskManager.outputc                 c   s&    |  |}|r|jV  dS dV  dS )z*show the traceback of a given task, if anyrT  N)rP  r  rS  r   r   r   last_tb  s
   

zTaskManager.last_tb)rU   N)rU   )r   )rI   rJ   rK   r   	cmdprefixr-  r   rl   rA   rP  r   annotationsintr  r/   r   r  r5  r[  r\  r   r   r   r   r=  ;  s.    




r=  c                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )r9  z=Start the interpreter specified by the params in a subprocessc                 C   sP   t  t jt j d|d |f }tjj| tjdd|gtjtjd t	
 | _d S )Nzfimport plac, sys
sys.argv[0] = '<%s>'
plac.Interpreter(plac.import_main(*%s)).interact(prompt='i>\n')
r   z-ur;   )r<   r1   )rC  SIGPIPESIG_DFLr=   r>   rl   r   
executabler?   r8  rB  r1  )rk   paramsr   r   r   r   rl     s   
zProcess.__init__c                 C   s"   | j   | j  | j  dS )zClose stdin and stdoutN)r<   rA   r1   r1  shutdownrp   r   r   r   rA     s   

zProcess.closec                 C   s>   g }	 | | j  |d dkrd|}|dd d S q)zBReturn the output of the subprocess, line-by-line until the promptTrU   zi>
rP   NrV   )rX   r1   rR   rY   )rk   r[   outr   r   r   recv  s   
zProcess.recvc                 C   s   | j |tj  |  S )z[Send a line (adding a newline) to the underlying subprocess
        and wait for the answer)r<   r4   r   lineseprf  )rk   r\   r   r   r   send  s   zProcess.sendN)rI   rJ   rK   r   rl   rA   rf  rh  r   r   r   r   r9    s    	r9  c                   @       e Zd ZdZdd Zdd ZdS )StartStopObjectFc                 C      d S r
   r   rp   r   r   r   r'    rO   zStartStopObject.startc                 C   rk  r
   r   rp   r   r   r   rF    rO   zStartStopObject.stopN)rI   rJ   rK   startedr'  rF  r   r   r   r   rj    s    rj  c                   @   sJ   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dS )Monitorzv
    Base monitor class with methods add_listener/del_listener/notify_listener
    read_queue and and start/stop.
    Nc                 C   s   || _ |pt | _d S r
   )r   r8  Queuequeue)rk   r   ro  r   r   r   rl     s   zMonitor.__init__c                 C   rk  r
   r   rk   rN  r   r   r   add_listener  rO   zMonitor.add_listenerc                 C   rk  r
   r   rp  r   r   r   del_listener  rO   zMonitor.del_listenerc                 C   rk  r
   r   )rk   rN  r  r   r   r   r2    rO   zMonitor.notify_listenerc                 C   rk  r
   r   rp   r   r   r   r'    rO   zMonitor.startc                 C   rk  r
   r   rp   r   r   r   rF    rO   zMonitor.stopc                 C   rk  r
   r   rp   r   r   r   
read_queue  rO   zMonitor.read_queuer
   )rI   rJ   rK   r   rl   rq  rr  r2  r'  rF  rs  r   r   r   r   rm    s    
rm  c                   @   sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dS )rB  z
    The plac Manager contains a multiprocessing.Manager and a set
    of slave monitor processes to which we can send commands. There
    is a manager for each interpreter with mpcommands.
    c                 C   s   i | _ d| _d | _d S NF)r@  rl  r4  rp   r   r   r   rl     s   
zManager.__init__c                 C   s*   t d|j|j}|j|_|| j|j< dS )z(Add or replace a monitor in the registryN)r8  r9  r'  r   ro  r@  )rk   monitorr:  r   r   r   r     s   zManager.addc                 C   s   | j |= dS )z(Remove a named monitor from the registryN)r@  rk   r   r   r   r   delete     zManager.deletec                 C   s6   | j d u r
t | _ | j D ]}|  qd| _d S )NT)r4  r8  rB  r@  rE  r'  rl  rk   ru  r   r   r   r'    s
   



zManager.startc                 C   sB   | j  D ]}|j  |  q| jr| j  d | _d| _d S rt  )r@  rE  ro  rA   r<  r4  rd  rl  ry  r   r   r   rF    s   



zManager.stopc                 C   s&   | j  D ]}|jd||f qd S )Nr2  r@  rE  ro  put)rk   rN  r  ru  r   r   r   r2    s   zManager.notify_listenerc                 C   s$   | j  D ]
}|jd|f qd S )Nrq  rz  )rk   r   ru  r   r   r   rq     s   zManager.add_listenerN)rI   rJ   rK   r   rl   r   rw  r'  rF  r2  rq  r   r   r   r   rB    s    	rB  c                   @   s  e Zd ZdZG dd deZdejfddZdd Z	d	d
 Z
dd Zdd Zdd Zdd Zd3ddZdd Zdd Zdd Zd4ddZd4dd Zejd!dfd"d#Zejd$dfd%d&Zd'd( Zd5d*d+Zd,d- Zd.d/ Zeejd0d dejejd$dfd1d2ZdS )6r
  zi
    A context manager with a .send method and a few utility methods:
    execute, test and doctest.
    c                   @   rF   )zInterpreter.ExitNrH   r   r   r   r   r  x  rL   r  #c                 C   s   || _ z|j| _W n ty   d| _Y nw || _|| _| | t|| _| jj	| _	| jj
| _
| jr?| j
j| jj| jdd |jrL| j
j|j|dd |jrY| j
j|j|dd dd | j
_d | _d S )Nplacr   )r   r   r   c                 S   s
   t | S r
   )r   exit)r  r   r   r   <lambda>  s   
 z&Interpreter.__init__.<locals>.<lambda>)r   rJ   r   r.   commentcharr   _set_commandsr=  tmr1  r   r   addsubcommandsr   r   r   error_interpreter)rk   r   r  r   r   r   r   rl   {  s6   





zInterpreter.__init__c              	   C   s   dD ]}t | |tt| j|g  t ||tt||g  q|j| _| j|j | j|j |js9|js9|jrPt|dsNt	
||j|_| jd dS dS dS )z=Make sure obj has the right command attributes as Python sets)r   r   r   r   N)r,  r-  r   r   r   r   rA  r   hasattrr   __get__r   r   )rk   r   attrnamer   r   r   r    s   zInterpreter._set_commandsc                 C   s   |   | _| jd | S )z Start the inner interpreter loopN)_make_interpreterr  rh  rp   r   r   r   rq     s   
zInterpreter.__enter__c                 C   s   |  ||| dS )z0Close the inner interpreter and the task managerN)rA   rk   exctyper+   r*   r   r   r   rs     s   zInterpreter.__exit__c                 C   s   | j du rttd|  t|ttfr| || j}n|}|s"tS | j	j
}|r/|js/|  | j |}t|d | j	jsN|| j	j|j< |rN||j |S )zBSend a line to the underlying interpreter and return a task objectNzA%r not initialized: probably you forgot to use the with statementr   )r  RuntimeErrorr   r#   r/   r  r   r  nulltaskr  r1  rl  r'  rh  r   
_match_cmdr   r@  r   rq  )rk   r\   r   mrG  r   r   r   submit  s$   

zInterpreter.submitc                 C   s   |  |}t| |S )zNSend a line to the underlying interpreter and return
        the finished task)r  r   r  rk   r\   rG  r   r   r   rh    s   

zInterpreter.sendc                 C   s   | j j S )z%The full lists of the submitted tasks)r  r@  rE  rp   r   r   r   rO    rx  zInterpreter.tasksNc                 C   s4   | j   |dur| j||| dS | j  dS )z2Can be called to close the interpreter prematurelyN)r  rA   r  throwr  r   r   r   rA     s   
zInterpreter.closec           
      c   sb   t | jddd }t | jddd }|  d}ztdD ]v}|V }z
| j|\}}W n5 tyT } z|jdkr=g }	nt|g}	t	||t
|	}W Y d}~qd}~w   t	||tt  }Y qt|sqt	||t|}q|| jjv rt|||| jj}q|| jjv rt|||}qt	|||}qW dS  ty   |ddd Y dS    |t    )	zBThe interpreter main loop, from lists of arguments to task objectsrq   c                   S   rk  r
   r   r   r   r   r   r    r  z/Interpreter._make_interpreter.<locals>.<lambda>rs   c                 S   rk  r
   r   )etexr*   r   r   r   r    r  Nr   )r   )r   r   	itertoolscountr   consume
SystemExitr   r/   r  r   r9   r   r  r   iterabler7   r   r/  r  r1  r   r   r	  )
rk   enterr~  rG  r   r   r   r  eerrlistr   r   r   r    sB   


zInterpreter._make_interpreterc                 C   s2   |  |j}||k}|sd|||f }t|dS )z:Make sure you get the expected_output from the given_inputz!input: %s
output: %s
expected: %sN)rh  r/   AssertionError)rk   given_inputexpected_outputr[  okr  r   r   r   check  s   zInterpreter.checkc           
      C   s   dd |D }g }g }t |D ]\}}|dr&||dd  || q|t|d  g }t |dd D ]\}}||d  }	|d||d |	  q:t|||S )	zDReturns the lines of input, the lines of output, and the line numberc                 S   r^   r   )rW   )r`   r\   r   r   r   rb     rc   z.Interpreter._parse_doctest.<locals>.<listcomp>i> r   Nr   rU   r|   )	enumerateru   rX   rL  rY   zip)
rk   lineiterr[   inputs	positionsr   r\   outputsr'  endr   r   r   _parse_doctest   s   

zInterpreter._parse_doctestFc              	   C   s   | \ z@|  |D ]8\}}}|rtd|  td|  | |}t||ksAd|d |||f }t| |jrAt|j|j|j q	W n
 | jyM   Y n	w W d   dS W d   dS 1 saw   Y  dS )z
        Parse a text containing doctests in a context and tests of all them.
        Raise an error even if a single doctest if broken. Use this for
        sequential tests which are logically grouped.
        zi> %s
z-> %s
z+line %d: input: %s
output: %s
expected: %s
r   N)	r  r4   rh  r/   r+   r,   r8   r*   r  )rk   r  verboseinputr[  r   rG  r  r   r   r   doctest  s.   
"zInterpreter.doctestc              	   C   s   | C z'|D ]"}|rt d|  | |}|jr!t|j|j|j t d|j  qW n
 | jy4   Y n	w W d   dS W d   dS 1 sHw   Y  dS )z@Execute a lineiter of commands in a context and print the outputr  %s
N)r4   rh  r8   r,   r+   r*   r/   r  )rk   r  r  r\   rG  r   r   r   execute&  s"   

"zInterpreter.execute;c              	   C   s   | @ z$t ||D ]}| |}|  td|j  |r%|jr%t|j q	W n
 | jy1   Y n	w W d   dS W d   dS 1 sEw   Y  dS )z<The multiline mode is especially suited for usage with emacsr  N)r]   r  r  r4   r/   r  r  )rk   r<   rZ   r  r\   rG  r   r   r   	multiline4  s"   


	"zInterpreter.multiliner  c           	   	   C   sB  zddl }d}W n ty   d}Y nw |tju rA|rAtjd| j }t| j	t| j
 t| j t| jj }t||d| _n|| _|| _|| _| jjpOd}t|d  | ? d| j_| jtju rh|   n| j |   W d   n1 szw   Y  W d   dS W d   dS W d   dS 1 sw   Y  dS )	zDStarts an interactive command loop reading commands from the consoler   NTFz~/.%s.history)rf   rP   r|   )rR   r   r   r<   r   r   
expanduserr   r5  r   r   r   r  r   rQ   rS   r  r   r   r4   r   _manage_input)	rk   r<   rS   r  rR   readline_presentrf   rd   intror   r   r   r   A  s>   


"zInterpreter.interactc                    s|   z2t  fdddD ]%}| }|sq
 |}|  tt|d   jr/|jr/t|j q
W dS   j	y=   Y dS w )z5Convert input lines into task which are then executedc                      s   t  j jS r
   )rT   r<   rS   r   rp   r   r   r  ^  s    z+Interpreter._manage_input.<locals>.<lambda>rP   r|   N)
r   rW   r  r  r4   r/   r  r8   r  r  r  r   rp   r   r  [  s   

	zInterpreter._manage_input  c              	   K   s`   t | t| z$z
tjdi | W n ttfy   Y nw W t  dS W t  dS t  w )zqStarts an asyncore server reading commands for clients and opening
        a new interpreter for each connection.Nr   )_AsynServer_AsynHandlerasyncoreloopr  rG   	close_all)rk   portrx   r   r   r   start_serverj  s   zInterpreter.start_serverc                 C   r   r
   )r1  r   )rk   monr   r   r   add_monitoru  r   zInterpreter.add_monitorc                 C   r   r
   )r1  rw  rv  r   r   r   del_monitorx  r   zInterpreter.del_monitorr   c                 C   s   t ||}| |||}	|	jjrI|	. |	|	jj}
|
jr%t|
j|
j|
j t|
}|r7t	| W d   dS W d   dS 1 sBw   Y  dS |	jj
rV|	||| dS |	j  dS )z
        Call a container factory with the arglist and instantiate an
        interpreter object. If there are remaining arguments, send them to the
        interpreter, else start an interactive session.
        N)r   r   _args_rh  r+   r,   r8   r*   r/   printr   r   r   print_usage)r   r   r   r  r   r<   rS   r  r   r   rG  re  r   r   r   r   {  s    
	
"zInterpreter.callr3  r  )r  ) rI   rJ   rK   r   r$   r  shlexr   rl   r  rq   rs   r  rh  rO  rA   r  r  r  r  r  r   r<   r  r   r  r  r  r  r   argvr   r   r   r   r   r
  s  s6    
#



r
  c                   @   ri  )_TaskLauncherzHelper for runpc                 C   s(   |dkr	dg| _ ndg| _t|| _d S )Nr   rungen)r   r   r5  genlist)rk   genseqmoder   r   r   rl     s   
z_TaskLauncher.__init__c                 c   s$    | j t|d  D ]}|V  q
d S )Nr   )r  r_  )rk   r   re  r   r   r   r    s   z_TaskLauncher.rungenN)rI   rJ   rK   r   rl   r  r   r   r   r   r    s    r  r   c                 C   s   |dv sJ |t | |}g }t|D}tt|jD ]}|d|d    q| D ]!}z||j	 W q- t
yN } z|| W Y d}~q-d}~ww W d   |S 1 sZw   Y  |S )zRun a sequence of generators in parallel. Mode can be 'p' (use processes)
    or 't' (use threads). After all of them are finished, return a list of
    task objects.
    ptz	rungen %dr   N)r  r
  rangerL  r  r  r  rO  rX   r  r$   )r  r  launcherresinterr   rG  r  r   r   r   runp  s$   


r  )NNr   r
   )r   )M
__future__r   
contextlibr   operatorr   r   r   r   r   r   r   r  r=   argparser  r  r8  rC  r#  r   version_infoversionimpr	   importlib.utilr   r"   r   evalr,   r}   	NameErrorr  r-   r1   r4   r7   r9   r:   platformrX  r$   rG   rN   rT   r]   objectrQ   r   RawDescriptionHelpFormatterr   r   r   r   environr   r   r   
ValueErrorr   r   r   r  r  r   r.  r/  r=  r>   r9  rj  rm  rB  r
  r  r  r   r   r   r   <module>   s   







	2

g4p%
3J  %