
    fw                        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mZ ddlm	Z	 ddlm
Z
 ddlmZ ddlmZmZ ddlmZ dd	lmZmZmZmZmZmZ dd
lmZ ddlmZ ddlmZ ddlmZ ddl m!Z! ddl"m#Z# e G d de             Z$y)zImplementation of magic functions for interaction with the OS.

Note: this module is named 'osm' instead of 'os' to avoid a collision with the
builtin.
    N)pformat)magic_arguments)oinspect)page)
AliasErrorAlias)
UsageError)Magicscompress_dhistmagics_class
line_magic
cell_magicline_cell_magic)skip_doctest)source_to_unicode)
abbrev_cwd)set_term_title)Bool)warnc                   r    e Zd ZdZ edd      j                  d      Zd% fd	Zd Zd	 Z	d
 Z
eed&d              Zed&d       Zed&d       Zeed&d              Zeed&d              Zed&d       Zed        Zed&d       Zed&d       Zed&d       Zed&d       Zeed&d              Zed'd       Z  ed      e      Z  ed      e      Zed&d       Zed&d       Z e j@                          e jB                  ddddd        e jB                  d!e"d"#      ed$                             Z# xZ$S )(OSMagicszJMagics to interact with the underlying OS (shell-type functionality).
    Fz5Force %cd magic to be quiet even if -q is not passed.)helpT)configc                    d| _         d | _        t        j                  dk(  rd| _         na	 t        j                  d   j                  dd      j                  dd      }	 t        j                  d
|z  t        j                        | _        t        | 4  dd|i| y # t        $ r d	}Y Lw xY w# t        j                  $ r< t        d       d	}t        j                  d
|z  t        j                        | _        Y qw xY w)NFposixTpathext;|. zexe|com|bat|pyz(.*)\.(%s)$zSeems like your pathext environmental variable is malformed. Please check it to enable a proper handle of file extensions managed for your systemshell )is_posixexecreosnameenvironreplaceKeyErrorrecompile
IGNORECASEerrorr   super__init__)selfr!   kwargswinext	__class__s       R/var/www/cvtools/html/venv/lib/python3.12/site-packages/IPython/core/magics/osm.pyr/   zOSMagics.__init__)   s     77g DM*I.66s3?GGBOP jj&)@O 	/u//  *)* 88 P / 0 * jj&)@OPs$   3B  ,B/ B,+B,/AC>=C>c                     t        j                  |j                  t         j                        r|j	                         S y)z7
        Test for executable on a POSIX system
        F)r%   accesspathX_OKis_filer0   files     r4   _isexec_POSIXzOSMagics._isexec_POSIXC   s)     99TYY(<<>!    c                 t    |j                         xr' | j                  j                  |j                        duS )>
        Test for executable file on non POSIX system
        N)r9   r$   matchr&   r:   s     r4   _isexec_WINzOSMagics._isexec_WINN   s-     ||~J$++"3"3DII">d"JJr=   c                 ^    | j                   r| j                  |      S | j                  |      S )r?   )r#   r<   rA   r:   s     r4   isexeczOSMagics.isexecT   s-     ==%%d++##D))r=   c                    |j                         }|s^t        | j                  j                  j                        }t        dt        |             t        j                  j                          |S 	 |j                  dd      \  }}	 | j                  j                  j                  ||       y# t        $ r+ t        t        j                  | j                               Y yw xY w# t         $ r}t        |       Y d}~yd}~ww xY w)a/
  Define an alias for a system command.

        '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'

        Then, typing 'alias_name params' will execute the system command 'cmd
        params' (from your underlying operating system).

        Aliases have lower precedence than magic functions and Python normal
        variables, so if 'foo' is both a Python variable and an alias, the
        alias can not be executed until 'del foo' removes the Python variable.

        You can use the %l specifier in an alias definition to represent the
        whole line when the alias is called.  For example::

          In [2]: alias bracket echo "Input in brackets: <%l>"
          In [3]: bracket hello world
          Input in brackets: <hello world>

        You can also define aliases with parameters using %s specifiers (one
        per parameter)::

          In [1]: alias parts echo first %s second %s
          In [2]: %parts A B
          first A second B
          In [3]: %parts A
          Incorrect number of arguments: 2 expected.
          parts is an alias to: 'echo first %s second %s'

        Note that %l and %s are mutually exclusive.  You can only use one or
        the other in your aliases.

        Aliases expand Python variables just like system calls using ! or !!
        do: all expressions prefixed with '$' get expanded.  For details of
        the semantic rules, see PEP-215:
        https://peps.python.org/pep-0215/.  This is the library used by
        IPython for variable expansion.  If you want to access a true shell
        variable, an extra $ is necessary to prevent its expansion by
        IPython::

          In [6]: alias show echo
          In [7]: PATH='A Python string'
          In [8]: show $PATH
          A Python string
          In [9]: show $$PATH
          /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...

        You can use the alias facility to access all of $PATH.  See the %rehashx
        function, which automatically creates aliases for the contents of your
        $PATH.

        If called with no parameters, %alias prints the current alias table
        for your system.  For posix systems, the default aliases are 'cat',
        'cp', 'mv', 'rm', 'rmdir', and 'mkdir', and other platform-specific
        aliases are added.  For windows-based systems, the default aliases are
        'copy', 'ddir', 'echo', 'ls', 'ldir', 'mkdir', 'ren', and 'rmdir'.

        You can see the definition of alias by adding a question mark in the
        end::

          In [1]: cat?
          Repr: <alias cat for 'cat'>zTotal number of aliases:N   )stripsortedr!   alias_manageraliasesprintlensysstdoutflushsplit	TypeErrorr   getdocaliasdefine_aliasr   )r0   parameter_sparrI   rR   cmdes          r4   rR   zOSMagics.alias^   s    B !TZZ55==>G
 ,c'l;JJN			$*IE#
	JJ$$11%=  	(//$**-.	  	!HH	s*   2B/ &C& /1C#"C#&	D/C??Dc                 X   |j                         }	 | j                  j                  j                  |       | j                  j                  j                  di       }||v r)t        d|       ||= || j                  j                  d<   yy# t        $ r}t        |       Y d}~yd}~ww xY w)zRemove an aliasNstored_aliaseszRemoving %stored alias)rF   r!   rH   undefine_alias
ValueErrorrJ   dbget)r0   rT   anamerW   storeds        r4   unaliaszOSMagics.unalias   s     !!#	JJ$$33E:
 ""#3R9F?*51u.4DJJMM*+   	!H	s   %B 	B)B$$B)c                 2   ddl m} | j                  j                  d= t        j
                  j                  dd      j                  t        j                        D cg c]>  }t        j                  j                  t        j                  j                  |            @ }}g }t	        j                         }	 | j                  r|D ]  }	 t	        j                  |       t	        j                   |      }|D ]  }	| j#                  |	      s|	j$                  }
	 | j                  j&                  j)                  |
      s6| j                  j&                  j+                  |
j-                  dd      |
       |j/                  |
         nt0        j2                  }|D ]  }	 t	        j                  |       t	        j                   |      }|D ]  }	|	j$                  }
t        j                  j5                  |
      \  }}| j#                  |	      sC|j7                         |vsV|j7                         dk(  sj|}
	 | j                  j&                  j+                  |j7                         j-                  dd      |
       |j/                  |
         || j                  j                  d	<   t	        j                  |       y
c c}w # t        $ r Y w xY w# |$ r Y w xY w# t        $ r Y Rw xY w# |$ r Y |w xY w# t	        j                  |       w xY w)a  Update the alias table with all executable files in $PATH.

        rehashx explicitly checks that every entry in $PATH is a file
        with execute access (os.X_OK).

        Under Windows, it checks executability as a match against a
        '|'-separated string of extensions, stored in the IPython config
        variable win_exec_ext.  This defaults to 'exe|com|bat'.

        This function also resets the root module cache of module completer,
        used on slow filesystems.
        r   )InvalidAliasErrorrootmodules_cachePATHr    )r7   r   z.exe
syscmdlistN)IPython.core.aliasrb   r!   r\   r%   r'   r]   rO   pathsepr7   abspath
expandusergetcwdr#   chdirOSErrorscandirrC   r&   rH   is_aliasrS   r(   appendr   	blacklistsplitextlower)r0   rT   rb   pr7   re   savedirpdirdirlistfffnameno_aliasbaseexts                 r4   rehashxzOSMagics.rehashx   s    	9 JJMM-. JJNN6"%++BJJ791 2 21 56 9 9 
))+4	 }}  9D!
 !jjd3G% 9;;r?$&GGE	9 (,zz'?'?'H'H'O$(JJ$<$<$I$I(-c"(=u%F
 !+ 1 1% 899, !??  9D!
 !jj.G% 9 "$&GG$4$4U$;	c;;r?tzz|8/K"yy{f4(,!) %)JJ$<$<$I$I(,

(<(<S(De%M !+ 1 1% 899. +5DJJMM,'HHWw9 # ! ! $5 % $% # ! !  (9 !)$(!) HHWs   AK9K? K ,K? K? AK5,K? "K$7AK? K? $K? 8K? ;AK4?.K? 	KK? KK? K!K?  K!!K? $	K1-K? 0K11K? 4K<9K? ;K<<K? ?Lc                 f    	 t        j                         S # t        $ r}t        d      |d}~ww xY w)zReturn the current working directory path.

        Examples
        --------
        ::

          In [9]: pwd
          Out[9]: '/home/tsuser/sprint/ipython'
        z:CWD no longer exists - please use %cd to change directory.N)r%   rj   FileNotFoundErrorr	   )r0   rT   rW   s      r4   pwdzOSMagics.pwd  s5    	b99;  	bYZ`aa	bs    	0+0c                 Z	   	 t        j                         }t        j                  d|      }|r:t        |j                  d            }	 | j                  j                  d   |   }i }n|j                  d      rd}d}|dd }| j                  j                  d   }	t        |	      D ]p  }
|t         j                  j                  |
      v r#t         j                  j                  |
      r|
} n,|J||
v sOt         j                  j                  |
      so|
}r ||}|t        d       yi }n| j!                  |dd	
      \  }}|dk(  r	 | j                  j                  d   d   }nxt         j                  j                  |      rd|v rU| j                  j$                  j'                  di       }||v r||   }t        d|d|       |}nd|v rt#        d|z        |r
	 t        j(                  t         j                  j+                  |             t-        | j                  d      rM| j                  j.                  r7t1        | j                  j2                  j5                  t7                            t8        j:                  j=                         }| j                  j                  d   }||k7  r-|j?                  |       tA        |      dd | j                  j$                  d<   nt        j(                  | j                  jH                         t-        | j                  d      rE| j                  j.                  r/t1        | j                  j2                  j5                  d             t8        j:                  j=                         }| j                  j                  d   }||k7  r6|j?                  |       tA        |      dd | j                  j$                  d<   d|vrM| jJ                  s@| j                  j                  d   r&t        | j                  j                  d   d          yyyy# t        $ r d}Y -w xY w# t        $ r t        d       Y yw xY w# t        $ r}t#        d      |d}~ww xY w# tB        $ r# t        tE        jF                         d          Y w xY w)a?  Change the current working directory.

        This command automatically maintains an internal list of directories
        you visit during your IPython session, in the variable ``_dh``. The
        command :magic:`%dhist` shows this history nicely formatted. You can
        also do ``cd -<tab>`` to see directory history conveniently.
        Usage:

          - ``cd 'dir'``: changes to directory 'dir'.
          - ``cd -``: changes to the last visited directory.
          - ``cd -<n>``: changes to the n-th directory in the directory history.
          - ``cd --foo``: change to directory that matches 'foo' in history
          - ``cd -b <bookmark_name>``: jump to a bookmark set by %bookmark
          - Hitting a tab key after ``cd -b`` allows you to tab-complete
            bookmark names.

          .. note::
            ``cd <bookmark_name>`` is enough if there is no directory
            ``<bookmark_name>``, but a bookmark with the name exists.

        Options:

        -q               Be quiet. Do not print the working directory after the
                         cd command is executed. By default IPython's cd
                         command does print this directory, since the default
                         prompts do not display path information.

        .. note::
           Note that ``!cd`` doesn't work for this purpose because the shell
           where ``!command`` runs is immediately discarded after executing
           'command'.

        Examples
        --------
        ::

          In [10]: cd parent/child
          /home/tsuser/parent/child
        Nz	(-)(\d+)$   _dhz2The requested directory does not exist in history.z--z&No matching entry in directory historyqbstringmode-z*%cd -: No previous directory to change to.b	bookmarksz
(bookmark:z) -> zDBookmark '%s' not found.  Use '%%bookmark -l' to see your bookmarks.
term_title)cwdidhistrE   ~q)&r%   rj   r~   r*   r@   intgroupr!   user_ns
IndexErrorrJ   
startswithreversedr7   basenameisdirparse_optionsr	   r\   r]   rk   ri   hasattrr   r   term_title_formatformatr   pathlibPathr   ro   r   rl   rL   exc_infohome_dircd_force_quiet)r0   rT   oldcwdnumcdnnpsoptsfallbackpatdhentrW   bkmstargetr   r   s                   r4   cdzOSMagics.cd)  s   V	YY[F
 k2U[[^$BZZ''.r2
 ##D)BHab/C##E*B| #"''**3//BGGMM#4FB#s
rww}}S7I"H# zz>? ))+t()KHD"9VZZ''.r2
 77==$tzz}}((b9:!"XF2v>?Bd{( *KMO*P Q Q J++B/04::|49N9N"4::#?#?#F#F:<#F#XY ll&&(

**51S=LL%-;E-B45-IDJJMM'* HHTZZ(()tzz<0TZZ5J5Jtzz;;BBsBKL,,""$CJJ&&u-E}S!)7)>tu)E

g&d{4#6#64::;M;Me;T$**$$U+B/0 <U#6{o ! 	F	  JKH  V !MNTUUV,  )cllnQ'()sN   P5 	Q Q! $BQ> 5QQQQ!	Q;*Q66Q;>)R*)R*c                    |j                         rd|v rdnd}|j                  |      }t        |      dk(  rQ|j                         t        j                  v rt        j                     S dj                        }t        |      t        |      dkD  r| j                  |      S t        t        j                        }t        |      D ]  t        fddD              sd|<    |S )a\  Get, set, or list environment variables.

        Usage:\

          :``%env``: lists all environment variables/values
          :``%env var``: get value for var
          :``%env var val``: set value for var
          :``%env var=val``: set value for var
          :``%env var=$val``: set value for var, using python expansion if possible
        = rE   z"Environment does not have key: {0}c              3   B   K   | ]  }|j                         v   y wN)rr   ).0skeys     r4   	<genexpr>zOSMagics.env.<locals>.<genexpr>  s     H1		#Hs   )r   tokensecretz<hidden>)rF   rO   rK   r%   r'   r   r	   set_envdictlistany)r0   rT   rO   bitserrenvr   s         @r4   r   zOSMagics.env  s     +-C3E$$U+D4yA~!'')"**$::c?*>EEcJC$S/)4y1}||K002::9 	&CH-GHH%C	& 
r=   c                    d|v rdnd}|j                  |d      }|j                         rt        |      dk  rt        d      |d   j                         }|d   j                         }t	        j
                  d|      rd}|j                  |      }t        |      |t        j                  |<   t        d	j                  ||             y
)av  Set environment variables.  Assumptions are that either "val" is a
        name in the user namespace, or val is something that evaluates to a
        string.

        Usage:\
          :``%set_env var val``: set value for var
          :``%set_env var=val``: set value for var
          :``%set_env var=$val``: set value for var, using python expansion if possible
        r   r   rE   r   zusage is 'set_env var=val'r   z.*\s.*z.refusing to set env var with whitespace: '{0}'zenv: {0}={1}N)
rO   rF   rK   r	   r*   r@   r   r%   r'   rJ   )r0   rT   rO   r   varvalr   s          r4   r   zOSMagics.set_env  s     k)s  *  "c$ik9::1gmmo1gmmo88Is# CC**S/CS/!

3n##C,-r=   c                 ^   | j                   j                  }t        j                  j	                  |      }t        j
                         j                  | j                   j                  d      }|r| j                  |       |j                  d|       | j                   j                  dd      S )zkPlace the current dir on stack and change directory.

        Usage:\
          %pushd ['dirname']
        r   r   dirsr    )r!   	dir_stackr%   r7   ri   rj   r(   r   r   insertrun_line_magic)r0   rT   dir_stgtr   s        r4   pushdzOSMagics.pushd  s}     

$$gg  -iik!!$**"5"5c:GGK Qszz((44r=   c                     | j                   j                  st        d      | j                   j                  j                  d      }| j	                  |       t        d|       y)z=Change to directory popped off the top of the stack.
        z%popd on empty stackr   zpopd ->N)r!   r   r	   popr   rJ   )r0   rT   tops      r4   popdzOSMagics.popd  sL     zz##344jj""&&q)ir=   c                 .    | j                   j                  S )z#Return the current directory stack.)r!   r   )r0   rT   s     r4   r   zOSMagics.dirs  s     zz###r=   c                 (   | j                   j                  d   }|r	 t        t        |j	                               }t        |      dk(  r't        t        |      |d   z
  d      t        |      }}nRt        |      dk(  r|\  }}t        |t        |            }n)| j                  | j                         ydt        |      }}t        d       t        ||      D ]  }t        d|||   fz          y#  | j                  | j                         Y yxY w)a  Print your history of visited directories.

        %dhist       -> print full history\
        %dhist n     -> print last n entries only\
        %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\

        This history is automatically maintained by the %cd command, and
        always available as the global list variable _dh. You can use %cd -<n>
        to go to directory number <n>.

        Note that most of time, you should view directory history by entering
        cd -<TAB>.

        r   NrE   r   r   zDirectory history (kept in _dh)z%d: %s)r!   r   mapr   rO   arg_errr   rK   maxminrJ   range)r0   rT   r   argsinifinis          r4   r   zOSMagics.dhist  s    " ZZ&3{0023 4yA~c"gtAw/23r7CTaC#s2w'TZZ(BC/0sC 	)A(aAZ'(	)TZZ(s   C2 2Dc                    | j                  |d      \  }}	 |j                  dd      \  }}|j                         }|j                  dd      \  }}d|v }| j                  j                  ||      }d|v rt        |dt        |             |r(| j                  j                  j                  ||i       y	|S # t        $ r d\  }}Y zw xY w)
a  Shell capture - run shell command and capture output (DEPRECATED use !).

        DEPRECATED. Suboptimal, retained for backwards compatibility.

        You should use the form 'var = !command' instead. Example:

         "%sc -l myfiles = ls ~" should now be written as

         "myfiles = !ls ~"

        myfiles.s, myfiles.l and myfiles.n still apply as documented
        below.

        --
        %sc [options] varname=command

        IPython will run the given command using commands.getoutput(), and
        will then update the user's interactive namespace with a variable
        called varname, containing the value of the call.  Your command can
        contain shell wildcards, pipes, etc.

        The '=' sign in the syntax is mandatory, and the variable name you
        supply must follow Python's standard conventions for valid names.

        (A special format without variable name exists for internal use)

        Options:

          -l: list output.  Split the output on newlines into a list before
          assigning it to the given variable.  By default the output is stored
          as a single string.

          -v: verbose.  Print the contents of the variable.

        In most cases you should not need to split as a list, because the
        returned value is a special type of string which can automatically
        provide its contents either as a list (split on newlines) or as a
        space-separated string.  These are convenient, respectively, either
        for sequential processing or to be passed to a shell command.

        For example::

            # Capture into variable a
            In [1]: sc a=ls *py

            # a is a string with embedded newlines
            In [2]: a
            Out[2]: 'setup.py\nwin32_manual_post_install.py'

            # which can be seen as a list:
            In [3]: a.l
            Out[3]: ['setup.py', 'win32_manual_post_install.py']

            # or as a whitespace-separated string:
            In [4]: a.s
            Out[4]: 'setup.py win32_manual_post_install.py'

            # a.s is useful to pass as a single command line:
            In [5]: !wc -l $a.s
              146 setup.py
              130 win32_manual_post_install.py
              276 total

            # while the list form is useful to loop over:
            In [6]: for f in a.l:
               ...:      !wc -l $f
               ...:
            146 setup.py
            130 win32_manual_post_install.py

        Similarly, the lists returned by the -l option are also special, in
        the sense that you can equally invoke the .s attribute on them to
        automatically get a whitespace-separated string from their contents::

            In [7]: sc -l b=ls *py

            In [8]: b
            Out[8]: ['setup.py', 'win32_manual_post_install.py']

            In [9]: b.s
            Out[9]: 'setup.py win32_manual_post_install.py'

        In summary, both the lists and strings used for output capture have
        the following special attributes::

            .l (or .list) : value as list.
            .n (or .nlstr): value as newline-separated string.
            .s (or .spstr): value as space-separated string.
        lvr   rE   )r    r    l)rO   vz ==
N)
r   rO   rF   r[   r!   	getoutputrJ   r   r   update)	r0   rT   r   r   r   _rV   rO   outs	            r4   sczOSMagics.sc4  s    z &&{D9	T
	 JJsA&EC))+C  %%c1-EAc tjj""3e"4$;gcl34JJ%%s3i0J  	GC	s   :B; ;CCc                    || j                   j                  |      S | j                  |dd      \  }}| j                   j                  |      }|j                  d|j                  d            }|r|| j                   j                  |<   y|S )a'  Shell execute - run shell command and capture output (!! is short-hand).

        %sx command

        IPython will run the given command using commands.getoutput(), and
        return the result formatted as a list (split on '\n').  Since the
        output is _returned_, it will be stored in ipython's regular output
        cache Out[N] and in the '_N' automatic variables.

        Notes:

        1) If an input line begins with '!!', then %sx is automatically
        invoked.  That is, while::

          !ls

        causes ipython to simply issue system('ls'), typing::

          !!ls

        is a shorthand equivalent to::

          %sx ls

        2) %sx differs from %sc in that %sx automatically splits into a list,
        like '%sc -l'.  The reason for this is to make it as easy as possible
        to process line-oriented shell output via further python commands.
        %sc is meant to provide much finer control, but requires more
        typing.

        3) Just like %sc -l, this is a list with special attributes:
        ::

          .l (or .list) : value as list.
          .n (or .nlstr): value as newline-separated string.
          .s (or .spstr): value as whitespace-separated string.

        This is very useful when trying to use such lists as arguments to
        system commands.Nr    zout=r   o)r!   r   r   r]   r   )r0   linecellr   r   outputout_names          r4   sxzOSMagics.sx  s    T <::''--**4V<IDZZ))$/Fxxtxx}5H/5

""8,r=   system!c                    | j                  |dd      \  }}t        |      dkD  rt        d      | j                  j                  j                  di       }d|v r	 |d   }	 ||= nd|v ri }nd|v r`t        |      }|rt        t        t        |            }nd}dt        |      z   dz   }	t        d       |D ]  }
t        |	|
||
   fz          nO|st        d      t        |      dk(  rt        j                         ||d   <   nt        |      dk(  r|d   ||d   <   || j                  j                  d<   y
# t        $ r}t        d	|z        |d
}~ww xY w# t        $ r}t        d      |d
}~ww xY w)ah  Manage IPython's bookmark system.

        %bookmark <name>       - set bookmark to current dir
        %bookmark <name> <dir> - set bookmark to <dir>
        %bookmark -l           - list all bookmarks
        %bookmark -d <name>    - remove bookmark
        %bookmark -r           - remove all bookmarks

        You can later on access a bookmarked folder with::

          %cd -b <name>

        or simply '%cd <name>' if there is no directory called <name> AND
        there is such a bookmark defined.

        Your bookmarks persist through IPython sessions, but they are
        associated with each profile.drlr   r   r   z%bookmark: too many argumentsr   dr   z)%%bookmark -d: Can't delete bookmark '%s'Nz/%bookmark -d: must provide a bookmark to deleterr   z%-zs -> %szCurrent bookmarks:z-%bookmark: You must specify the bookmark namerE   )r   rK   r	   r!   r\   r]   r)   r   rG   r   r   strrJ   r%   rj   )r0   rT   r   r   r   todelrW   bkssizefmtbks              r4   bookmarkzOSMagics.bookmark  s   ( &&{5f&E	Tt9q=<==zz}}  R0$;
TQ
TU
 D[DD[,C3sC=)s4y.*C&' ,cRbN*+,  !PQQTA "		T!WTA $QT!W%)

k"/   T$CeKMRSTT  N EGLMNNs0   E "D: :	EEE	E4#E//E4c                     	 | j                   j                  |d      }t        j
                  | j                   j                  t        |                   y# t        t        f$ r t	        d       Y yw xY w)a3  Show a syntax-highlighted file through a pager.

        This magic is similar to the cat utility, but it will assume the file
        to be Python source and will show it with syntax highlighting.

        This magic command can either take a local filename, an url,
        an history range (see %history) or a macro as argument.

        If no parameter is given, prints out history of current session up to
        this point. ::

        %pycat myscript.py
        %pycat 7-27
        %pycat myMacro
        %pycat http://www.example.com/myscript.py
        F)skip_encoding_cookiez:Error: no such file, variable, URL, history range or macroN)r!   find_user_coder[   IOErrorrJ   r   
pycolorizer   )r0   rT   conts      r4   pycatzOSMagics.pycat  se    $	::,,[u,UD
 			$**''(9$(?@A	 G$ 	NO	s   A A43A4z-az--append
store_truez_Append contents of the cell to an existing file. The file will be created if it does not exist.)actiondefaultr   filenamezfile to write)typer   c                 z   t        j                  | j                  |      }t        j                  d|j
                        r-t        j                  j                  |j
                  dd       }n)t        j                  j                  |j
                        }t        j                  j                  |      r*|j                  rt        d|z         nt        d|z         nt        d|z         |j                  rdnd}t        j                  ||d	
      5 }|j                  |       ddd       y# 1 sw Y   yxY w)zWrite the contents of the cell to a file.

        The file will be overwritten unless the -a (--append) flag is specified.
        z^(\'.*\')|(".*")$rE   r   zAppending to %szOverwriting %sz
Writing %sawzutf-8)encodingN)r   parse_argstring	writefiler*   r@   r  r%   r7   ri   existsro   rJ   ioopenwrite)r0   r   r   r   r  r   fs          r4   r  zOSMagics.writefile7  s      ..t~~tD88($--8ww))$--"*=>Hww))$--8H77>>(#{{'(23&12,)*kkssWWXtg6 	!GGDM	 	 	s   D11D:r   )r    )r    N)%__name__
__module____qualname____doc__r   tagr   r/   r<   rA   rC   r   r   rR   r`   r|   r   r   r   r   r   r   r   r   r   r   r   r   r   bangr   r   r   argumentr   r  __classcell__)r3   s   @r4   r   r       s(    %D	cc 04K* T  Tn 5 5  M M^ b  b C1  C1J  > . .: 5 5   $ $
 #) #)J p  pd 3 3j '_X&r*F:c?2D9* 9*v B B2 %_$$&_ju>
 _  	 'r=   r   )%r  r
  r%   r   r*   rL   pprintr   IPython.corer   r   r   rf   r   r   IPython.core.errorr	   IPython.core.magicr
   r   r   r   r   r   IPython.testing.skipdoctestr   IPython.utils.openpyr   IPython.utils.processr   IPython.utils.terminalr   	traitletsr   warningsr   r   r"   r=   r4   <module>r      si    
 	  	 
  ( !  0 )  5 2 , 1   vv v vr=   