o
    û›hæ3  ã                   @   sà   d 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	m
Z
 ddlmZ ddlmZmZmZmZ ddlmZ ddlmZ ddlmZmZmZmZ dd	lmZ d
d„ ZG dd„ deƒZeG dd„ deƒƒZ dS )z5Magic functions for running cells in various scripts.é    N)ÚCalledProcessError)ÚThread)ÚAnyÚDictÚListÚdefault)Úmagic_arguments)Ú_AsyncIOProxy)ÚMagicsÚ
cell_magicÚ
line_magicÚmagics_class)Ú	arg_splitc              
   C   sb   t jdtdd�t jdtdd�t jdddd	�t jd
tdd�t jddddd�g}|D ]}|| ƒ} q(| S )z'single decorator for adding script argsz--outzÙThe variable in which to store stdout from the script.
            If the script is backgrounded, this will be the stdout *pipe*,
            instead of the stderr text itself and will not be auto closed.
            )ÚtypeÚhelpz--errzØThe variable in which to store stderr from the script.
            If the script is backgrounded, this will be the stderr *pipe*,
            instead of the stderr text itself and will not be autoclosed.
            z--bgÚ
store_truezœWhether to run the script in the background.
            If given, the only way to see the output of the command is
            with --out/err.
            )Úactionr   z--procztThe variable in which to store Popen instance.
            This is used only when --bg option is given.
            z--no-raise-errorÚstore_falseÚraise_errorz„Whether you should raise an error message in addition to
            a stream on stderr if you get a nonzero exit code.
            )r   Údestr   )r   ZargumentÚstr)ÚfÚargsÚarg© r   úPc:\Users\shubh\Videos\agent\nova\Lib\site-packages\IPython/core/magics/script.pyÚscript_args   s0   þþþþþä#
r   c                   @   s   e Zd ZdS )ÚRaiseAfterInterruptN)Ú__name__Ú
__module__Ú__qualname__r   r   r   r   r   F   s    r   c                       sÔ   e Zd ZU dZedd�Zedd�jdd�Zee	d< e
dƒdd	„ ƒZed
d�jdd�Zd"‡ fdd„	Zdd„ Zdd„ Zdd„ Ze ¡ eedƒdd„ ƒƒƒZejdke_dd„ Zedƒd#dd„ƒZdd„ Zd d!„ Z‡  ZS )$ÚScriptMagicszâMagics for talking to scripts
    
    This defines a base `%%script` cell magic for running a cell
    with a program in a subprocess, and registers a few top-level
    magics that call %%script with common interpreters.
    zé
        The event loop on which to run subprocesses

        Not the main event loop,
        because we want to be able to make blocking calls
        and have certain requirements we don't want to impose on the main loop.
        )r   zêExtra script cell magics to define
        
        This generates simple wrappers of `%%script foo` as `%%foo`.
        
        If you want to add script magics that aren't on your path,
        specify them in script_paths
        T)ÚconfigÚscript_magicsc                 C   s"   g d¢}t jdkr| dg¡ |S )z$default to a common list of programs)ÚshÚbashÚperlÚrubyÚpythonÚpython2Úpython3ÚpypyÚntÚcmd)ÚosÚnameÚextend)ÚselfÚdefaultsr   r   r   Ú_script_magics_defaultg   s   

ÿz#ScriptMagics._script_magics_defaultzÕDict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
        
        Only necessary for items in script_magics where the default path will not
        find the right interpreter.
        Nc                    s0   t t| ƒj|d� |  ¡  g | _t | j¡ d S )N)Úshell)Úsuperr!   Ú__init__Ú_generate_script_magicsÚbg_processesÚatexitÚregisterÚkill_bg_processes)r1   r4   ©Ú	__class__r   r   r6   „   s   zScriptMagics.__init__c                 C   s   |   ¡  d S ©N)r;   ©r1   r   r   r   Ú__del__Š   s   zScriptMagics.__del__c                 C   s(   | j d }| jD ]	}|  |¡||< qd S )NÚcell)Zmagicsr#   Ú_make_script_magic)r1   Zcell_magicsr/   r   r   r   r7   �   s   

ÿz$ScriptMagics._generate_script_magicsc                    s@   ˆj  ||¡‰ t ¡ t‡ ‡fdd„ƒƒ}djdi tƒ ¤Ž|_|S )zAmake a named magic, that calls %%script with a particular programc                    s"   | r	dˆ | f } nˆ } ˆ  | |¡S )Nz%s %s)Úshebang)ÚlinerA   ©Úscriptr1   r   r   Únamed_script_magic—   s   z;ScriptMagics._make_script_magic.<locals>.named_script_magicz”%%{name} script magic
        
        Run cells with {script} in a subprocess.
        
        This is a shortcut for `%%script {script}`
        Nr   )Úscript_pathsÚgetr   r   ÚformatÚlocalsÚ__doc__)r1   r/   rG   r   rE   r   rB   ’   s   
ûûÿzScriptMagics._make_script_magicrF   c                    s€  ˆj du r$tjdkrt ¡  ¡ ‰nt ¡ ‰ˆˆ_ tˆjdd�}| ¡  nˆj ‰‡fdd„}dd„ ‰‡‡fd	d
„‰ ‡ ‡fdd„}t	|tj 
d¡ d�}ˆjj |¡\‰}z|tj|tjjtjjtjjdœŽƒ‰W n" ty‰ } z|jtjkr„td|d  ƒ W Y d}~dS ‚ d}~ww ˆ d¡s“ˆd7 ‰ˆ dd¡‰ˆjrýˆj ˆ¡ ˆ ¡  g ‰ˆjr·tˆjˆƒˆjjˆj< nˆ ˆj¡ ˆj rÌtˆj!ˆƒˆjjˆj < nˆ ˆj!¡ ˆ "‡‡‡‡fdd„¡ ˆj#rûtˆˆƒ}	tˆjˆƒ|	_tˆj!ˆƒ|	_!|	ˆjjˆj#< dS z	||ˆˆƒƒ W n  t$�y¦   z[ˆ %t&j'¡ |tj(ˆ )¡ dd�ƒ ˆj*du�r5tdƒ ˆj+�r1t,ƒ ‚W Y dS ˆ -¡  |tj(ˆ )¡ dd�ƒ ˆj*du�rYtdƒ ˆj+�rUt,ƒ ‚W Y dS ˆ .¡  tdƒ ˆj+�rht,ƒ ‚W n. t,�ys   Y n% t�y|   Y n t/�y— } ztdˆj0|f ƒ W Y d}~nd}~ww ˆj+�r£t1ˆj*ˆƒd‚Y dS w ˆj+�r¼ˆj*dk�r¾ˆj*�p¶d}
t1|
ˆƒ‚dS dS )ah  Run a cell via a shell command

        The `%%script` line is like the #! line of script,
        specifying a program (bash, perl, ruby, etc.) with which to run.

        The rest of the cell is run by that program.

        .. versionchanged:: 9.0
          Interrupting the script executed without `--bg` will end in
          raising an exception (unless `--no-raise-error` is passed).

        Examples
        --------
        ::

            In [1]: %%script bash
               ...: for i in 1 2 3; do
               ...:   echo $i
               ...: done
            1
            2
            3
        NÚwin32T)ÚtargetÚdaemonc                    s   t  | ˆ ¡ ¡ S )z&Call a coroutine on the asyncio thread)ÚasyncioÚrun_coroutine_threadsafeÚresult)Úcoro)Ú
event_loopr   r   Ú	in_threadÙ   s   z'ScriptMagics.shebang.<locals>.in_threadc              
   Ó   s|   �z	|   d¡I d H W S  tjjy! } z	|jW  Y d }~S d }~w tjjy= } z|   |j¡I d H W  Y d }~S d }~ww )Néd   )ÚreadrP   Ú
exceptionsÚIncompleteReadErrorÚpartialÚLimitOverrunErrorÚconsumed)ÚstreamÚer   r   r   Ú
_readchunkÝ   s   €€€ÿz(ScriptMagics.shebang.<locals>._readchunkc                 “   sJ   �	 ˆ | ƒI d H j ddd�}|sd S |r|ˆjj|< n	| |¡ | ¡  q)NTÚutf8Úreplace)Úerrors)Údecoder4   Úuser_nsÚwriteÚflush)r]   Z
stream_argZfile_objectÚchunk)r_   r1   r   r   Ú_handle_streamå   s   €
øz,ScriptMagics.shebang.<locals>._handle_streamc                 “   sn   �| j  |¡ | j  ¡  t ˆ | jˆjtjƒ¡}t ˆ | jˆj	tjƒ¡}t 
||g¡I d H  |  
¡ I d H  d S r>   )Ústdinre   ÚcloserP   Úcreate_taskÚstdoutÚoutÚsysÚstderrÚerrÚwait)ÚprocessrA   Zstdout_taskZstderr_task)rh   r   r   r   Ú_stream_communicateð   s   €
ÿÿz1ScriptMagics.shebang.<locals>._stream_communicateÚwin)Úposix)rl   ro   ri   zCouldn't find program: %rr   Ú
r`   ra   c                      s   t  ˆ ˆˆ ˆ¡¡S r>   )rP   ÚTaskÚ_run_scriptr   )rA   Úpr1   Úto_closer   r   Ú<lambda>  s    z&ScriptMagics.shebang.<locals>.<lambda>çš™™™™™¹?)ÚtimeoutzProcess was interrupted.zProcess was terminated.zProcess was killed.z/Error while terminating subprocess (pid=%i): %si÷ÿÿÿ)2rT   rn   ÚplatformrP   ÚWindowsProactorEventLoopPolicyÚnew_event_loopr   Úrun_foreverÚstartr   Ú
startswithrC   ÚparserZparse_known_argsÚcreate_subprocess_execÚ
subprocessÚPIPEÚOSErrorÚerrnoÚENOENTÚprintÚendswithÚencodeÚbgr8   ÚappendÚ_gc_bg_processesrm   r	   rl   r4   rd   rp   ro   Úcall_soon_threadsafeÚprocÚKeyboardInterruptÚsend_signalÚsignalÚSIGINTÚwait_forrq   Ú
returncoder   r   Ú	terminateÚkillÚ	ExceptionÚpidr   )r1   rD   rA   Zasyncio_threadrU   rs   Úargvr-   r^   Z
proc_proxyÚrcr   )rh   r_   r   rA   rT   ry   r1   rz   r   rC   ¬   s¶   


üÿ€û
ÿ
ÿ€ÿá!
ûzScriptMagics.shebangru   c                 Ã   sj   �|j  |¡ |j  ¡ I dH  |j  ¡  |j  ¡ I dH  | ¡ I dH  |D ]	}| ¡ I dH  q%|  ¡  dS )z1callback for running the script in the backgroundN)ri   re   Údrainrj   Úwait_closedrq   rW   r�   )r1   ry   rA   rz   Úsr   r   r   rx   T  s   €
zScriptMagics._run_scriptÚkillbgscriptsÚ c                 C   s   |   ¡  tdƒ dS )z9Kill all BG processes started by %%script and its family.z%All background processes were killed.N)r;   r‹   )r1   Z_nouse_r   r   r   r¢   b  s   zScriptMagics.killbgscriptsc                 C   sÜ   | j sdS | j D ]}|jdu rz| tj¡ W q   Y qqt d¡ |  ¡  | j s,dS | j D ]}|jdu rBz| ¡  W q/   Y q/q/t d¡ |  ¡  | j sQdS | j D ]}|jdu rgz| 	¡  W qT   Y qTqT|  ¡  dS )z.Kill all BG processes which are still running.Nr|   )
r8   r˜   r”   r•   r–   ÚtimeÚsleepr�   r™   rš   )r1   ry   r   r   r   r;   h  s@   

ü


ü


üzScriptMagics.kill_bg_processesc                 C   s   dd„ | j D ƒ| _ d S )Nc                 S   s   g | ]	}|j d u r|‘qS r>   )r˜   )Ú.0ry   r   r   r   Ú
<listcomp>‰  s    z1ScriptMagics._gc_bg_processes.<locals>.<listcomp>)r8   r?   r   r   r   r�   ˆ  s   zScriptMagics._gc_bg_processesr>   )r£   )r   r   r    rL   r   rT   r   Útagr#   Ú__annotations__r   r3   r   rH   r6   r@   r7   rB   r   r   r   rC   r.   r/   Z__skip_doctest__rx   r   r¢   r;   r�   Ú__classcell__r   r   r<   r   r!   J   s@   
 ÿ
ÿø

ÿú $ r!   )!rL   rP   Zasyncio.exceptionsr9   r‰   r.   r•   rn   r¤   r†   r   Ú	threadingr   Z	traitletsr   r   r   r   ZIPython.corer   ZIPython.core.async_helpersr	   ZIPython.core.magicr
   r   r   r   ZIPython.utils.processr   r   r›   r   r!   r   r   r   r   Ú<module>   s(    *