
    f/                         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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
 Ze G d de             Zy)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           
      (   t        j                  dt        d      t        j                  dt        d      t        j                  ddd	      t        j                  d
t        d      t        j                  dddd      g}|D ]
  } ||       }  | S )z'single decorator for adding script argsz--outzThe 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--errzThe 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_truezWhether 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_errorzWhether you should raise an error message in addition to
            a stream on stderr if you get a nonzero exit code.
            )r   destr   )r	   argumentstr)fargsargs      U/var/www/cvtools/html/venv/lib/python3.12/site-packages/IPython/core/magics/script.pyscript_argsr      s     	  #	
 	  #	
 	  <	
 	  3	
 	  }=	
9"DF  FH    c                   n    e Zd ZdZ ed      Z ed      j                  d      Z e	d      d        Z
 ed	      j                  d      Zd fd
	Zd Zd Zd Z ej"                         e ed      d                      Zej,                  dk7  e_        d Z ed      dd       Zd Zd Z xZS )ScriptMagicszMagics 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   zExtra 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                 X    g d}t         j                  dk(  r|j                  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defaultss     r   _script_magics_defaultz#ScriptMagics._script_magics_defaulta   s1    	
 77d?OO  r   zDict 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.
        c                     t         t        |   |       | j                          g | _        t        j                  | j                         y )N)shell)superr!   __init___generate_script_magicsbg_processesatexitregisterkill_bg_processes)r2   r6   	__class__s     r   r8   zScriptMagics.__init__~   s;    lD**7$$&../r   c                 $    | j                          y N)r=   )r2   s    r   __del__zScriptMagics.__del__   s     r   c                 l    | j                   d   }| j                  D ]  }| j                  |      ||<    y )Ncell)magicsr#   _make_script_magic)r2   cell_magicsr0   s      r   r9   z$ScriptMagics._generate_script_magics   s:    kk&)&& 	>D $ 7 7 =K	>r   c                       j                   j                  ||      t        j                         t         fd              } dj                  di t               |_        |S )zAmake a named magic, that calls %%script with a particular programc                 @    | rd| } n} j                  | |      S )N )shebang)linerC   scriptr2   s     r   named_script_magicz;ScriptMagics._make_script_magic.<locals>.named_script_magic   s(     "($/<<d++r   z%%{name} script magic
        
        Run cells with {script} in a subprocess.
        
        This is a shortcut for `%%script {script}`
         )script_pathsgetr	   r   formatlocals__doc__)r2   r0   rM   rL   s   `  @r   rE   zScriptMagics._make_script_magic   sr     ""&&tT2		(	(	*		, 
 
+	,	 	
 F	
 X	 	" "!r   rL   c           	      p	     j                   yt        j                  dk(  r#t        j                         j                         nt        j
                          _         t        j                  d      }|j                          n j                   fd} fdfd}t        |t        j                  j                  d       	      } j                  j                  j                  |      \  }	  |t        j                  |t        j                  j                   t        j                  j                   t        j                  j                   d
      j+                  d      sdz  j-                  dd      j.                  rt j0                  j3                          j5                          g j6                  r8t9        j:                         j<                  j>                  j6                  <   nj3                  j:                         j@                  r8t9        jB                         j<                  j>                  j@                  <   nj3                  jB                         jE                   fd       jF                  ret9              }	t9        j:                        |	_        t9        jB                        |	_!        |	 j<                  j>                  jF                  <   y	  | |             j^                  r,jT                  dk7  rjT                  xs d}
ta        |
      yy# t"        $ r9}|j$                  t$        j&                  k(  rt)        d|d   z         Y d}~y d}~ww xY w# tH        $ r 	 jK                  tL        jN                          |t        jP                  jS                         d             jT                  t)        d       Y yjW                           |t        jP                  jS                         d             jT                  t)        d       Y yjY                          t)        d       Y y# t"        $ r Y Y ytZ        $ r%}t)        dj\                  |fz         Y d}~Y yd}~ww xY ww xY w)a  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.

        Examples
        --------
        ::

            In [1]: %%script bash
               ...: for i in 1 2 3; do
               ...:   echo $i
               ...: done
            1
            2
            3
        Nwin32T)targetdaemonc                 L    t        j                  |       j                         S )z&Call a coroutine on the asyncio thread)asynciorun_coroutine_threadsaferesult)coro
event_loops    r   	in_threadz'ScriptMagics.shebang.<locals>.in_thread   s    33D*ELLNNr   c                    K   	 | j                          d {   j                  dd      }|sy |r|j                  j                  |<   n!|j	                  |       |j                          j7 Vw)Nutf8replace)errors)readlinedecoder6   user_nswriteflush)stream
stream_argfile_objectrK   r2   s       r   _handle_streamz,ScriptMagics.shebang.<locals>._handle_stream   sh     $oo//77y7Q59DJJ&&z2%%d+%%' /s   A1A/AA1c                   K   | j                   j                  |       | j                   j                          t        j                   | j
                  j                  t        j
                              }t        j                   | j                  j                  t        j                              }t        j                  ||g       d {    | j                          d {    y 7 7 wr@   )stdinrf   closerY   create_taskstdoutoutsysstderrerrwait)processrC   stdout_taskstderr_taskrk   r   s       r   _stream_communicatez1ScriptMagics.shebang.<locals>._stream_communicate   s     MM%MM!!--w~~txxDK "--w~~txxDK ,,[9:::,,.   ; s$   CC3C/C3)C1*C31C3win)posix)rp   rs   rm   zCouldn't find program: %rr   
r`   ra   c                  P    t        j                  j                               S r@   )rY   Task_run_script)rC   pr2   to_closes   r   <lambda>z&ScriptMagics.shebang.<locals>.<lambda>  s    T%5%5ax%HI r   皙?)timeoutzProcess is interrupted.zProcess is terminated.zProcess is killed.z/Error while terminating subprocess (pid=%i): %si)1r]   rr   platformrY   WindowsProactorEventLoopPolicynew_event_loopr   run_foreverstartr   
startswithrJ   parserparse_known_argscreate_subprocess_exec
subprocessPIPEOSErrorerrnoENOENTprintendswithencodebgr:   append_gc_bg_processesrq   r
   rp   r6   re   rt   rs   call_soon_threadsafeprocKeyboardInterruptsend_signalsignalSIGINTwait_forru   
returncode	terminatekill	Exceptionpidr   r   )r2   rK   rC   asyncio_threadr^   ry   argvr.   e
proc_proxyrcrk   r   r]   r   r   s   ` `        @@@@@r   rJ   zScriptMagics.shebang   s   4 ??"||w& %CCETTV
$335
(DO $:+A+A$ON  "J	O		(
	! )@)@)G%GHLL''88>	c	.."--22"--22!,,11	A }}T"DLD{{69-77$$Q'!!#Hxx/<QXXz/R

""488,)xx/<QXXz/R

""488,)++I yy*1j9
$1!((J$G
!$1!((J$G
!0:

""499-	)!T23*  1 #B$R.. !2m  	ww%,,&1CF:;	D ! 	Vfmm,'**1668SAB<<+34'**1668SAB<<+23*+
 	     VG155RS*TUUV!	si   =A%M N 	N.NNN
R5$A!Q8AQ8Q88	R1R5R1R,&R5,R11R5r{   c                   K   |j                   j                  |       |j                   j                          d{    |j                   j                          |j                   j	                          d{    |j                          d{    |D ]  }|j                          d{     | j                          y7 7 N7 87 w)z1callback for running the script in the backgroundN)rm   rf   drainrn   wait_closedru   readr   )r2   r   rC   r   ss        r   r   zScriptMagics._run_script5  s      	
dggmmo	gg!!###ffh  	A&&(NN	 	# sE   9CC;C7C8CCC,C
-CCC
Ckillbgscriptsc                 :    | j                          t        d       y)z9Kill all BG processes started by %%script and its family.z%All background processes were killed.N)r=   r   )r2   _nouse_s     r   r   zScriptMagics.killbgscriptsC  s     	 56r   c                 j   | j                   sy| j                   D ]/  }|j                  	 |j                  t        j                         1 t        j                  d       | j                          | j                   sy| j                   D ]   }|j                  	 |j                          " t        j                  d       | j                          | j                   sy| j                   D ]   }|j                  	 |j                          " | j                          y#  Y 
xY w#  Y xY w#  Y GxY w)z.Kill all BG processes which are still running.Nr   )
r:   r   r   r   r   timesleepr   r   r   r2   r   s     r   r=   zScriptMagics.kill_bg_processesI  s     "" 	A||#MM&--0	 	

3  "" 	A||#KKM	 	

3  "" 	A||#FFH	 	-s#   DD'<D.D$'D+.D2c                 f    | j                   D cg c]  }|j                  | c}| _         y c c}w r@   )r:   r   r   s     r   r   zScriptMagics._gc_bg_processesi  s'    (,(9(9R1Q\\=QQRRs   ..r@   ) )__name__
__module____qualname__rS   r   r]   r   tagr#   r   r4   r   rO   r8   rA   r9   rE   r	   r   r   rJ   r/   r0   __skip_doctest__r   r   r   r=   r   __classcell__)r>   s   @r   r!   r!   E   s     J  
cc  _ (  
cc 0!>
"4 %_$$&H/   'H/T  "ww'1G   7 !7
 @Sr   r!   )rS   rY   r;   r   r/   r   rr   r   r   r   	threadingr   	traitletsr   r   r   r   IPython.corer	   IPython.core.async_helpersr
   IPython.core.magicr   r   r   r   IPython.utils.processr   r   r!   rN   r   r   <module>r      sa    ;
    	  
  )  . . ( 4 K K +'T dS6 dS dSr   