
    Xh5                         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 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 G d de       Z!e G d de             Z"y)z5Magic functions for running cells in various scripts.    N)getincrementaldecoder)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      N/var/www/html/myenv/lib/python3.12/site-packages/IPython/core/magics/script.pyscript_argsr      s     	  #	
 	  #	
 	  <	
 	  3	
 	  }=	
9"DF  FH    c                       e Zd Zy)RaiseAfterInterruptN)__name__
__module____qualname__ r    r   r"   r"   G   s    r    r"   c                   z    e Zd ZU dZ ed      Z ed      j                  d      Zee	d<    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_defaulth   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)r9   r=   	__class__s     r   r?   zScriptMagics.__init__   s;    lD**7$$&../r    c                 $    | j                          y N)rD   )r9   s    r   __del__zScriptMagics.__del__   s     r    c                 l    | j                   d   }| j                  D ]  }| j                  |      ||<    y )Ncell)magicsr*   _make_script_magic)r9   cell_magicsr7   s      r   r@   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)linerJ   scriptr9   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}`
        r&   )script_pathsgetr
   r   formatlocals__doc__)r9   r7   rT   rS   s   `  @r   rL   zScriptMagics._make_script_magic   sr     ""&&tT2		(	(	*		, 
 
+	,	 	
 F	
 X	 	" "!r    rS   c           	           j                   yt        j                  dk(  r#t        j                         j                         nt        j
                          _         t        j                  d      }|j                          n j                   fd}d  fdfd}t        |t        j                  j                  d	       
      } j                  j                  j                  |      \  }j                  r#d j                  j                   j                  <   j"                  r#d j                  j                   j"                  <   	  |t        j$                  |t        j&                  j(                  t        j&                  j(                  t        j&                  j(                  d      j3                  d      sdz  j5                  dd      j6                  rt j8                  j;                          j=                          g j                  r8t?        j@                         j                  j                   j                  <   nj;                  j@                         j"                  r8t?        jB                         j                  j                   j"                  <   nj;                  jB                         jE                   fd       jF                  ret?              }	t?        j@                        |	_         t?        jB                        |	_!        |	 j                  j                   jF                  <   y	  | |             jV                  r,jT                  dk7  rjT                  xs d}
tc        |
      yy# t*        $ r9}|j,                  t,        j.                  k(  rt1        d|d   z         Y d}~y d}~ww xY w# tH        $ r 	 jK                  tL        jN                          |t        jP                  jS                         d             jT                  #t1        d       jV                  r
tY               Y yj[                           |t        jP                  jS                         d             jT                  #t1        d       jV                  r
tY               Y yj]                          t1        d       jV                  r
tY               nD# tX        $ r Y n9t*        $ r Y n/t^        $ r$}t1        dj`                  |fz         Y d}~nd}~ww xY wjV                  rtc        jT                        dY yw xY w)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                 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       d {   S 7 # t        j                  j                  $ r}|j                  cY d }~S d }~wt        j                  j
                  $ r.}| j                  |j                         d {  7  cY d }~S d }~ww xY ww)Nd   )readr_   
exceptionsIncompleteReadErrorpartialLimitOverrunErrorconsumed)streames     r   
_readchunkz(ScriptMagics.shebang.<locals>._readchunk   ss     5#[[----%%99 !yy %%77 5#[[44445s`   B  B BABB B-BBBBBBBc                   K   d} t        d      d      }	 |j                   |        d {         }|sy |r"j                  j                  |xx   |z  cc<   n!|j	                  |       |j                          |ry k7 Tw)NFzutf-8replace)errors)r   decoder=   user_nswriteflush)rm   
stream_argfile_objectshould_breakdecoderchunkro   r9   s         r   _handle_streamz,ScriptMagics.shebang.<locals>._handle_stream   s      L4+G4IFGZ-?'?@ JJ&&z2e;2%%e,%%' '?s   ,BBAB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rG   )stdinru   closer_   create_taskstdoutoutsysstderrerrwait)processrJ   stdout_taskstderr_taskr|   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 )r   r   r~   zCouldn't find program: %rr   
utf8rq   c                  P    t        j                  j                               S rG   )r_   Task_run_script)rJ   pr9   to_closes   r   <lambda>z&ScriptMagics.shebang.<locals>.<lambda>+  s    T%5%5ax%HI r    皙?)timeoutzProcess was interrupted.zProcess was terminated.zProcess was killed.z/Error while terminating subprocess (pid=%i): %si)2rc   r   platformr_   WindowsProactorEventLoopPolicynew_event_loopr   run_foreverstartr   
startswithrQ   parserparse_known_argsr   r=   rt   r   create_subprocess_exec
subprocessPIPEOSErrorerrnoENOENTprintendswithencodebgrA   append_gc_bg_processesr   r   r   call_soon_threadsafeprocKeyboardInterruptsend_signalsignalSIGINTwait_forr   
returncoder   r"   	terminatekill	Exceptionpidr   )r9   rR   rJ   asyncio_threadrd   r   argvr5   rn   
proc_proxyrcr|   ro   r   rc   r   r   s   ` `        @@@@@@r   rQ   zScriptMagics.shebang   sJ   < ??"||w& %CCETTV
$335
(DO $:+A+A$ON  "J	O	5	"
	! )@)@)G%GHLL''88>	c88+-DJJtxx(88+-DJJtxx(	.."--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3D  1 #B$R.. !2G  	ww%,,&1CF:;	D ! 	Vfmm,'**1668SAB<<+45''133'**1668SAB<<+34''133+,##-// $&   VG155RS*TUUV(t<$F?	s    A%N7 /O< 7	O9 .O43O44O9<
VA7T A(T*1TV	U%V'U/V1U9UVU&VV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)r~   ru   drainr   wait_closedr   rg   r   )r9   r   rJ   r   ss        r   r   zScriptMagics._run_script`  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)rD   r   )r9   _nouse_s     r   r   zScriptMagics.killbgscriptsn  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   )
rA   r   r   r   r   timesleepr   r   r   r9   r   s     r   rD   zScriptMagics.kill_bg_processest  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 rG   )rA   r   r   s     r   r   zScriptMagics._gc_bg_processes  s'    (,(9(9R1Q\\=QQRRs   ..rG   )r   )r#   r$   r%   rY   r   rc   r   tagr*   __annotations__r	   r;   r   rU   r?   rH   r@   rL   r
   r   r   rQ   r6   r7   __skip_doctest__r   r   r   rD   r   __classcell__)rE   s   @r   r(   r(   K   s    J  
cc 4  _ (  
cc 0!>
"4 %_$$&l/   'l/\  "ww'1G   7 !7
 @Sr    r(   )#rY   r_   asyncio.exceptionsrB   r   r6   r   r   r   codecsr   r   r   	threadingr   	traitletsr   r   r   r	   IPython.corer
   IPython.core.async_helpersr   IPython.core.magicr   r   r   r   IPython.utils.processr   r   r   r"   r(   r&   r    r   <module>r      ss    ;
     	  
  ( )  . . ( 4 K K +'T	) 	 IS6 IS ISr    