
    Mhcm                       U 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
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 ddlmZ ddlmZ dd	lmZ 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* ddl+m!Z!m,Z,m-Z-m.Z.m/Z/m0Z0m1Z1mZm2Z2m3Z3m4Z4m5Z5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;Z<ddl=m>Z>m?Z?m@Z@mAZAmBZB ddlCmDZDmEZE ddlFmGZG ddlHmIZI ddlJmKZK ddlLmMZM ddlNmOZO ddlPmQZQ ddlRmSZS ddlTmUZUmVZV ddlWmXZXmYZY ddlZm[Z[ ddl\m]Z] ddl^m_Z_m`Z` ddlambZbmcZc dd ldmeZe dd!lfmgZg dd"lhmiZi dd#ljmkZk dd$llmmZm dd%lnmoZo dd&lpmqZq dd'lrmsZs dd(ltmuZu dd)lvmwZw dd*lxmyZymZmzZzm{Z{ dd+l|m}Z} dd,l~mZ dd-lmZ dd.lmZmZmZ dd/lmZmZ dd0lmZ dd1lmZ dd2lmZmZmZmZ dd3lmZ e$e         ed4<   	 ddlmZ d5 Zn# e$ r dZY nw xY w G d6 d7e          Zdd8lmZ ej        ej        ej        fZej        ej        fZd9d:lmZmZmZmZmZ  e
j        d;          Zd<efd=Ze}d>             Ze}d?             Z G d@ dAe          Z G dB dCe3          Z G dD dEej                  ZdFeee!f         dGee         fdHZ G dI dJ          Z G dK dL          Z ej        e          dM             Z G dN dOe8          Z G dP dQej        R          Ze                    e           dS )SzMain IPython class.    N)stmt)contextmanager)open)error)Path)Callable)ListAny)LiteralOptionalSequenceTuple)warn)PickleShareDB)TemporaryDirectory)r
   BoolCaselessStrEnumDictEnumInstanceIntegerr	   TypeUnicodedefaultobservevalidate)SingletonConfigurableimport_item)magicoinspectpage	prefilterultratb)AliasAliasManagerExitAutocall)BuiltinTrap)CachingCompiler)InterruptiblePdb)DisplayTrap)DisplayHook)DisplayPublisher)InputRejected
UsageError)EventManageravailable_events)ExtensionManager)DisplayFormatter)HistoryManagerHistoryOutput)	ESC_MAGIC
ESC_MAGIC2)Logger)Macro)PayloadManager)PrefilterManager)
ProfileDir)pick_tip)default_banner)display)get_ipython_dir)skip_doctest)
PyColorizeioopenpy	py3compat)undoc)
ask_yes_no)Struct)ensure_dir_existsget_home_dirget_py_filename)	getoutputsystem)StrDispatch)prepended_to_syspath)DollarFormatterLSStringSListformat_screen)OInfo	sphinxifyc                 :    t          j        |           fd}|S )Nc                     t                      5 }t          j        |          | dcd d d            S # 1 swxY w Y   d S )N)z	text/html
text/plain)r   sphxrV   )	docstringdirnamewrapped_docstrings     ]/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/IPython/core/interactiveshell.pysphinxify_docstringz&sphinxify.<locals>.sphinxify_docstringk   s    #%% !%0A7!K!K"+                  s   599)rZ   wrap_main_docstring)oinfor_   r]   s     @r^   rV   rV   h   s5     4U;;	 	 	 	 	 #"    c                       e Zd ZdZdS )ProvisionalWarningz-
    Warning class for unstable features
    N__name__
__module____qualname____doc__ rb   r^   rd   rd   w   s          	Drb   rd   )Module   )_asyncio_runner_curio_runner_pseudo_sync_runner_should_be_async_trio_runnerz^\s+raise|^\s+return|^\s+passsc                 H    	 t          |            dS # t          $ r Y dS w xY w)zQ
    Variant of "str.isnumeric()" that allow negative values and other ints.
    TF)int
ValueError)rr   s    r^   is_integer_stringrv      s9    At   uus    
!!c                 |    d}	 | j         }n# t          $ r Y nw xY w	 || _         n# t          t          f$ r Y nw xY w|S )z-Copied from code.py, to remove the dependencyr   )	softspaceAttributeError	TypeError)filenewvalueoldvalues      r^   rx   rx      sq     H>   !I&    Os    
% 99c                      d S Nrj   )akws     r^   no_opr      s    Drb   c                       e Zd ZdS )SpaceInInputN)rf   rg   rh   rj   rb   r^   r   r      s          rb   r   c                   "     e Zd ZdZ fdZ xZS )SeparateUnicodezA Unicode subclass to validate separate_in, separate_out, etc.

    This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
    c                     |dk    rd}|                     dd          }t          t          |                               ||          S )N0 z\n
)replacesuperr   r   )selfobjvalue	__class__s      r^   r   zSeparateUnicode.validate   sC    C<<eD))_d++44S%@@@rb   )rf   rg   rh   ri   r   __classcell__r   s   @r^   r   r      sK         
A A A A A A A A Arb   r   c                         e Zd Zd fdZ xZS )_IPythonMainModuleBasereturnNc                 N    t                                          dd           d S )N__main__zDAutomatically created module for the IPython interactive environmentdoc)r   __init__)r   r   s    r^   r   z_IPythonMainModuleBase.__init__   s4    V 	 	
 	
 	
 	
 	
rb   r   N)rf   rg   rh   r   r   r   s   @r^   r   r      s=        
 
 
 
 
 
 
 
 
 
rb   r   user_nsr   c                 L     t            G  fddt                                }|S )Nc                       e Zd ZdZedeeef         f fd            Zdededdf fdZ	dedef fdZ
deddf fd	ZdS )
0make_main_module_type.<locals>.IPythonMainModulea  
        ModuleType that supports passing in a custom user namespace dictionary,
        to be used for the module's __dict__. This is enabled by shadowing the
        underlying __dict__ attribute of the module, and overriding getters and
        setters to point to the custom user namespace dictionary.
        The reason to do this is to allow the __main__ module to be an instance
        of ModuleType, while still allowing the user namespace to be custom.
        r   c                     S r   rj   )r   r   s    r^   __dict__z9make_main_module_type.<locals>.IPythonMainModule.__dict__   s    Nrb   itemr   Nc                 "    |dk    rd S ||<   d S )Nr   rj   )r   r   r   r   s      r^   __setattr__z<make_main_module_type.<locals>.IPythonMainModule.__setattr__   s     z!!!GDMMMrb   c                 f    	 |         S # t           $ r t          d| j         d|           w xY wNzmodule z has no attribute KeyErrorry   rf   r   r   r   s     r^   __getattr__z<make_main_module_type.<locals>.IPythonMainModule.__getattr__   sT    Xt}$ X X X$%Vt}%V%VPT%V%VWWWXs    %0c                 `    	 |= d S # t           $ r t          d| j         d|           w xY wr   r   r   s     r^   __delattr__z<make_main_module_type.<locals>.IPythonMainModule.__delattr__   sU    XDMMM X X X$%Vt}%V%VPT%V%VWWWXs    %-)rf   rg   rh   ri   propertydictstrr
   r   r   r   r   r   s   r^   IPythonMainModuler      s        	 	 
	d38n 	 	 	 	 	 
		"C 	" 	" 	" 	" 	" 	" 	" 	"	XC 	XC 	X 	X 	X 	X 	X 	X	XC 	XD 	X 	X 	X 	X 	X 	X 	X 	Xrb   r   )rG   r   )r   r   s   ` r^   make_main_module_typer      sU    
X X X X X X X2 X X UX@ rb   c                   2    e Zd ZdZdZdZdZdZdZd Z	d Z
dS )ExecutionInfoz~The arguments used for a call to :meth:`InteractiveShell.run_cell`

    Stores information about what is going to happen.
    NFTc                 L    || _         || _        || _        || _        || _        d S r   )raw_cellstore_historysilentshell_futurescell_id)r   r   r   r   r   r   s         r^   r   zExecutionInfo.__init__  s+     **rb   c                     | j         j        }t          | j                  dk    r| j        d d         dz   n| j        }d|t	          |           || j        | j        | j        | j        fz  S )N2   z..zW<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s cell_id=%s>)	r   rh   lenr   idr   r   r   r   )r   namer   s      r^   __repr__zExecutionInfo.__repr__  sy    ~*+.t}+=+=+B+BT]3B3$&& 	 f4""		
rb   )rf   rg   rh   ri   r   r   r   r   r   r   r   rj   rb   r^   r   r      sW          HMFMG  
 
 
 
 
rb   r   c                       e Zd ZU dZdZee         ed<   dZee	         ed<   dZ
ee	         ed<   dZdZd Zed             Zd Zd	 ZdS )
ExecutionResultzmThe result of a call to :meth:`InteractiveShell.run_cell`

    Stores information about what took place.
    Nexecution_counterror_before_execerror_in_execc                     || _         d S r   )info)r   r   s     r^   r   zExecutionResult.__init__*  s    			rb   c                 &    | j         d u o| j        d u S r   r   r   r   s    r^   successzExecutionResult.success-  s    &$.PT5G45OPrb   c                 >    | j         | j         | j        | j        dS )z>Reraises error if `success` is `False`, otherwise does nothingNr   r   s    r^   raise_errorzExecutionResult.raise_error1  s.    !-(()$$ *)rb   c           
          | j         j        }d|t          |           | j        | j        | j        t          | j                  t          | j                  fz  S )Nz]<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>)	r   rh   r   r   r   r   reprr   resultr   r   s     r^   r   zExecutionResult.__repr__8  se    ~*nr$xx!5t7MtOacghlhqcrcrtxy}  zE  uF  uF  GG 	Grb   )rf   rg   rh   ri   r   r   rt   __annotations__r   BaseExceptionr   r   r   r   r   r   r   r   rj   rb   r^   r   r     s          
 &*OXc])))15x.555-1M8M*111DF   Q Q XQ% % %G G G G Grb   r   c                 P    | dv rt          d|  d          t          | g|R i |S )N>   r   rl      zIPython won't let you open fd=zi by default as it is likely to crash IPython. If you know what you are doing, you can use builtins' open.)ru   io_open)r{   argskwargss      r^   _modified_openr   >  sU    y*T * * *
 
 	
 4)$)))&)))rb   c                       e Zd ZU dZdZeed<   ee         ed<   e	j
        ed<    eg d                              d	          Zeej                 ed
<    eddd                              d	          Z edd                              d	          Z edd                              d	          ZedfedfedfedfdZ eddd                              d	          Z ed          d             Z ed          d             Z edd                              d	          Z  edd                              d	          Z! e"e#d                              d	          Z$ e"dd                              d	          Z% e&dd                              d	          Z' ed                              d	          Z( e)e*d           Z+ e,e-          Z. e,e/          Z0 e,e1          Z2 e,e	j
        d!                              d	          Z3 edd"                              d	          Z4 e5d#          d$             Z6 edd%                              d	          Z7 e5d&          d'             Z8dZ9 ed          Z: e)e;          Z< ed(          d)             Z= e&d*          Z> e"d+          Z? e"d                              d	          Z@ e)d,d-          ZAeBd.             ZC eg d/          ZDeed0<    edd1                              d	          ZE e"dd2                              d	          ZF e"dd3                              d	          ZG edd4                              d	          ZH edd5                              d	          ZI edd6                              d	          ZJ edd7                              d	          ZK ed                              d	          ZL e&d8d9                              d	          ZM e&dd:                              d	          ZN eg d;d<d=                              d	          ZO edd>                              d	          ZP eQd?                              d	          ZR eQd                              d	          ZS eQd                              d	          ZT ed                              d	          ZU eVd@dAdB                              d	          ZW e)dCd           ZX e)dDd           ZY e)dE          ZZ e)dF          Z[ e)dGd           Z\ e)dHd           Z] e)dId           Z^ e)dJ          Z_ e)dKd           Z`eBdL             Za eb            ZcdZd eddM          Ze e)dNdOdP          Zf	 	 	 d fdR	ZgeBdS             Zhehji        dTefdU            ZhdV Zj e5dW          dX             ZkddYZldZ Zmd[ Znd\ Zod] Zpd^ Zqd_ Zr e"d`da                              d	          Zs edb          dc             Zt e5db          ddd            Zude Zvdf ZwddhZxddiZydj Zzdk Z{dl Z|dm Z}dn Z~do Zdp Zedqefdr            Zds Zdt Zdu ZeBdv             ZddwZdx ZddzZd{ Zd| Zd} Zd~ Zd Zd Zd Z eBeedd          ZddZdZddZeBd             ZddZd Zd ZeBd             ZddZddZddZddZd Zededgeeee         f         fd            Z	 ddedeeeeef                           dgefdZed             ZddgefdZddefdZddZddZddZd ZeZddZd Zd ZddZd ZddZ	 	 ddZdee         fdZddZd Zedd            Zd Zedd            ZdddZddZd Z ej        ej        j                  dd            ZdefdZddedefdZd Zd Zd Zd ZddZd Zd Zd ZeZddZd Zd Zd Zd Zd Zd Zd Zd Zd Zd ZddddÜdĄZd dńZdƄ Zeded         fdɄ            Z	 	 	 	 ddʄZdedededededgefdЄZdddќdedgefd҄Z	 	 	 dddddӜdedee         dee         dgefdքZ	 ddׄZd؄ Zdل Zd<edfdee         defd܄ZdddݜdބZeZdedgeeef         fdZdZee         ed<   ddZddZddZd e            fdZddZddZd ZddZddZd Zd Z d Zd Z xZS (  InteractiveShellz*An enhanced, interactive shell for Python.N_user_ns_sys_modules_keys	inspectorz
        A list of ast.NodeTransformer subclass instances, which will be applied
        to user input before code is run.
        )helpT)configast_transformers)r   rl   r   r   a  
        Make IPython automatically call any callable object even if you didn't
        type explicit parentheses. For example, 'str 43' becomes 'str(43)'
        automatically. The value can be '0' to disable the feature, '1' for
        'smart' autocall, where it is not applied if there are no more
        arguments on the line, and '2' for 'full' autocall, where all callable
        objects are automatically called (even if no arguments are present).
        )default_valuer   z@
        Autoindent IPython code entered interactively.
        zJ
        Automatically run await statement in the top level repl.
        F)asynciocuriotriosync-IPython.core.interactiveshell._asyncio_runnerzOSelect the loop runner that will be used to execute top-level asynchronous code)r   
allow_noner   loop_runnerc                      t          d          S )Nr   r   r   s    r^   _default_loop_runnerz%InteractiveShell._default_loop_runner~  s    JKKKrb   c                 J   t          |j        t                    r`|j        | j        v r| j        |j                 \  }}|| _        |S t          |j                  }t          |          st          d          |S t          |j                  st          d          |j        S )Nzloop_runner must be callable)
isinstancer   r   loop_runner_map	autoawaitr   callableru   )r   proposalrunnerr   s       r^   _import_runnerzInteractiveShell._import_runner  s    hnc** 	~!555$($8$H!	!* 00FF## A !?@@@M'' 	=;<<<~rb   zK
        Enable magic commands to be called without the leading %.
        z/
        Set to show a tip when IPython starts.z7The part of the banner to be printed before the profiler   z6The part of the banner to be printed after the profilei  a  
        Set the size of the output cache.  The default is 1000, you can
        change it permanently in your config file.  Setting it to 0 completely
        disables the caching system, and the minimum value accepted is 3 (if
        you provide a value less than 3, it is reset to 0 and a warning is
        issued).  This limit is defined because otherwise you'll spend more
        time re-flushing a too small cache than working
        )r   z/Class to use to instantiate the shell inspectorzm
        Enables rich html representation of docstrings. (This requires the
        docrepr module).
        r_   c                 D    |d         rt          dt                     d S d S )Nnewz[`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions.r   rd   r   changes     r^   _sphinxify_docstring_changedz-InteractiveShell._sphinxify_docstring_changed  sF    %= 	En  rD  E  E  E  E  E	E 	Erb   zg
        (Provisional API) enables html representation in mime bundles sent
        to pagers.
        enable_html_pagerc                 D    |d         rt          dt                     d S d S )Nr   zY`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.r   r   s     r^   _enable_html_pager_changedz+InteractiveShell._enable_html_pager_changed  sF    %= 	Bl  oA  B  B  B  B  B	B 	Brb   exiterc                      t          |           S r   r'   r   s    r^   _exiter_defaultz InteractiveShell._exiter_default  s    D!!!rb   rl   z<ipython console>z1IPython.core.inputtransformer2.TransformerManagerrj   c                     | j         j        S r   )input_transformer_managercleanup_transformsr   s    r^   input_transformers_cleanupz+InteractiveShell.input_transformers_cleanup  s    -@@rb   z]A list of string input transformers, to be applied after IPython's own input transformations.input_transformers_postz
        Start logging to the default log file in overwrite mode.
        Use `logappend` to specify a log file to **append** logs to.
        z1
        The name of the logfile to use.
        z
        Start logging to the given file in append mode.
        Use `logfile` to specify a log file to **overwrite** logs to.
        )r   zL
        Automatically call the pdb debugger after every exception.
        zhIf True, anything that would be passed to the pager
        will be displayed as regular output instead.z(Show rewritten input, e.g. for autocall.i'  zTotal length of command historyzn
        The number of saved history entries to be loaded
        into the history buffer at startup.
        )alllast	last_exprnonelast_expr_or_assignr  z
        'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
        which nodes should be run interactively (displaying output from expressions).
        ztWarn if running in a virtual environment with no IPython installed (so IPython from the global environment is used).r   )ContextPlainVerboseMinimalDocsr
  z0Switch modes for the IPython exception handlers.zIPython.core.alias.AliasManagerz'IPython.core.prefilter.PrefilterManagerz%IPython.core.builtin_trap.BuiltinTrapz%IPython.core.display_trap.DisplayTrapz(IPython.core.extensions.ExtensionManagerz#IPython.core.payload.PayloadManagerz(IPython.core.history.HistoryAccessorBasez IPython.core.magic.MagicsManagerz#IPython.core.application.ProfileDirc                     | j         ?t          j                            | j         j                  }|                    dd          S d S )Nprofile_r   )profile_dirospathbasenamelocationr   r   s     r^   profilezInteractiveShell.profileA  sB    '7##D$4$=>>D<<
2... ('rb   z#Did last executed command succeededz-IPython.core.interactiveshell.ExecutionResultz$Result of executing the last command)r   r   rj   Nc                 v    t          t          |           j        di | | g| _        |                     |           |                     |           |                                  |                                  |                                  | 	                    ||           | 
                                 |                                  t          t          j                            | j        j        d                    | _        |                                  |                                  |                                  |                                  |                                  |                                  |                                  |                                  |                                  |                                  t:          | _        |                                  |                                   | !                    |           | "                                 | #                                 | $                                 | %                                 | &                                 | '                                 | (                                 | )                                 | *                                 | +                                 | ,                                 | j-        .                    d|            t_          j0        | j1                   d | _2        d| _3        d S )Ndbshell_initializedFrj   )4r   r   r   configurablesinit_ipython_dirinit_profile_dirinit_instance_attrsinit_environmentinit_virtualenvinit_create_namespacessave_sys_module_stateinit_sys_modulesr   r  r  joinr  r  r  init_historyinit_encodinginit_prefilterinit_syntax_highlighting
init_hooksinit_eventsinit_pushd_popd_magicinit_user_nsinit_loggerinit_builtinsinputraw_input_originalinit_completerinit_ioinit_traceback_handlersinit_promptsinit_display_formatterinit_display_pubinit_data_pubinit_displayhookinit_magics
init_aliasinit_logstartinit_pdbinit_extension_managerinit_payloadeventstriggeratexitregisteratexit_operationstrio_runnershowing_traceback)r   ipython_dirr  user_moduler   custom_exceptionsr   r   s          r^   r   zInteractiveShell.__init__R  s   
 	/%%.88888"V 	k***k***  """ 	 	##K999 	""$$$
  T-=-F M MNN%%'''""$$$ #( 	$$%6777##%%%##%%%/666.///  !&rb   c                     | j         S r   )r   r   s    r^   r   zInteractiveShell.user_ns  s
    }rb   nsc                 f    t          |d          sJ t          |t                    sJ || _        d S )Nclear)hasattrr   r   r   r   rJ  s     r^   r   zInteractiveShell.user_ns  s9    r7#####"d#####rb   c                     | S )z.Return the currently running IPython instance.rj   r   s    r^   get_ipythonzInteractiveShell.get_ipython  s    rb   rF  c                 0    t          |d                    d S )Nr   )rJ   r   s     r^   _ipython_dir_changedz%InteractiveShell._ipython_dir_changed  s    &-(((((rb   c                 6    || j          | _         dS || _         dS )zSSet the autoindent flag.

        If called with no arguments, it acts as a toggle.N)
autoindent)r   r   s     r^   set_autoindentzInteractiveShell.set_autoindent  s$     ="&/1DOOO#DOOOrb   c                     || _         d S r   )rD  )r   trs     r^   set_trio_runnerz InteractiveShell.set_trio_runner  s    rb   c                 B    |	|| _         d S t                      | _         d S r   )rF  rA   )r   rF  s     r^   r  z!InteractiveShell.init_ipython_dir  s)    "*DF*,,rb   c                 Z    |	|| _         d S t          j        | j        d          | _         d S )Nr   )r  r=   create_profile_dir_by_namerF  )r   r  s     r^   r  z!InteractiveShell.init_profile_dir  s8    "*DF%@i
 
rb   c                     d| _         |                                 | _        t                      | _        g | _        g | _        t          j                    | _	        d| _
        i | _        d S )NFr   )morecompiler_classcompilerI   meta	tempfilestempdirsr  getcwdstarting_dirindent_current_nsp_post_executer   s    r^   r  z$InteractiveShell.init_instance_attrs  se    	 **,, HH	  IKK #$  rb   c                     dS )z6Any changes we need to make to the user's environment.Nrj   r   s    r^   r  z!InteractiveShell.init_environment      rb   c                 h    	 t           j        j        pd| _        d S # t          $ r d| _        Y d S w xY w)Nascii)sysstdinencodingstdin_encodingry   r   s    r^   r&  zInteractiveShell.init_encoding  sK    	*"%)"4"?D 	* 	* 	*")D	*s    11neutralz8Set the color scheme (nocolor, neutral, linux, lightbg).colorsc                     |d         }||                                 k    s-t          d|                                  dt          d           |                                 S )Nr   z5`TerminalInteractiveShell.colors` is now lowercase: `z/`, non lowercase, may be invalid in the future.r   
stacklevel)lowerr   DeprecationWarning)r   r   r   s      r^   _check_colorszInteractiveShell._check_colors  sn    wciikk!!@		 @ @ @"	    yy{{rb   c                    t          j        | j                  j        fd| _        t          | d          s'|                     | j        | j        |           | _        	 | j        	                    | j        
                                           n;# t          $ r. t          dt          j                    d         z  d           Y nw xY wt          | d	          r| j        	                    | j                   t          | d
          r| j        	                    | j                   |                                  d S )N
theme_namec                      | d          S )Nr   rj   )srcpyformats    r^   <lambda>z;InteractiveShell.init_syntax_highlighting.<locals>.<lambda>  s    hhsE&:&: rb   r   )ry  str_detail_levelparentz1Error changing object inspector color schemes.
%srl   r   rr  InteractiveTBSyntaxTB)rC   Parserrp  format
pycolorizerM  inspector_classobject_info_string_levelr   set_theme_namert  	Exceptionr   rk  exc_infor  r  refresh_style)r   changesr|  s     @r^   r(  z)InteractiveShell.init_syntax_highlighting
  sY    $<<<C::::t[)) 	!11;!%!> 2  DN	N))$+*;*;*=*=>>>> 	 	 	D<>>!$&     	 4)) 	;--dk:::4$$ 	6M((555s   #1B 5CCc                     d S r   rj   r   s    r^   r  zInteractiveShell.refresh_style%  rh  rb   c                 :    t                      | _        g | _        d S r   )rK   home_dir	dir_stackr   s    r^   r+  z&InteractiveShell.init_pushd_popd_magic)  s    $rb   r   c                 >    t          | j        dd          | _        d S )Nzipython_log.pyrotate)logfnamelogmode)r9   r  loggerr   s    r^   r-  zInteractiveShell.init_logger/  s&    T]5E%-/ / /rb   c                     | j         r |                     d| j          d           dS | j        r|                     d| j                   dS | j        r|                     dd           dS dS )zIInitialize logging in case it was requested at the command line.
        logstartz appendr   N)	logappendrun_line_magiclogfiler  r   s    r^   r;  zInteractiveShell.init_logstart3  s     > 	0
t~,F,F,FGGGGG\ 	0
DL99999] 	0
B/////	0 	0rb   c                 v    dt           j        d<   t          t           j        d<   t          |           | _        d S )NT__IPYTHON__r@   )shell)builtin_modr   r@   r)   builtin_trapr   s    r^   r.  zInteractiveShell.init_builtins=  s7    
 /3]+*1Y''d333rb   c                     d S r   rj   r   s    r^   r2  zInteractiveShell.init_ioH  s	     	rb   c                 N    dt           _        dt           _        dt           _        d S )NzIn : z...: zOut: )rk  ps1ps2ps3r   s    r^   r4  zInteractiveShell.init_promptsM  s     rb   c                 n    t          |           | _        | j                            | j                   d S N)r  )r4   display_formatterr  appendr   s    r^   r5  z'InteractiveShell.init_display_formatterT  s5    !1!>!>!>!!$"899999rb   c                 |    |                      | |           | _        | j                            | j                   d S )N)r  r  )display_pub_classdisplay_pubr  r  r   s    r^   r6  z!InteractiveShell.init_display_pubX  s=    11T1JJ!!$"233333rb   c                     | j         s	d | _        d S |                      |           | _        | j                            | j                   d S r  )data_pub_classdata_pubr  r  r   s    r^   r7  zInteractiveShell.init_data_pub\  sP    " 	 DMF++4+88!!$-00000rb   c                     |                      | | | j                  | _        | j                            | j                   t          | j                  | _        d S )N)r  r  
cache_size)hook)displayhook_classr  displayhookr  r  r,   display_trapr   s    r^   r8  z!InteractiveShell.init_displayhookc  sd    11 2 
 

 	!!$"2333 (T-=>>>rb   pc                    | g}|                                  rjt          t          j        |                     }|                                s
| j        |z  }|} |                    |            |                                  j|S )a  Gets path links including all symlinks

        Examples
        --------
        In [1]: from IPython.core.interactiveshell import InteractiveShell

        In [2]: import sys, pathlib

        In [3]: paths = InteractiveShell.get_path_links(pathlib.Path(sys.executable))

        In [4]: len(paths) == len(set(paths))
        Out[4]: True

        In [5]: bool(paths)
        Out[5]: True
        )
is_symlinkr   r  readlinkis_absoluter  r  )r  pathsnew_paths      r^   get_path_linkszInteractiveShell.get_path_linkso  s}    $ llnn 	BKNN++H'')) /8h.ALLOOO llnn 	 rb   c                   
 dt           j        vrdS t           j        d         dk    rt          d           dS t          t          j                  }t          t           j        d                                                   
|                     |          }t          
j	                  dk    r:
j	        d         dk    r)
j	        d         }|dz   t          
j	        d	d          z  
t          
fd
|D                       rdS t          j        dk    r/t          t          t           j        d         dd                    }nt          t           j        d         ddd          }t          j        dd         }t          j        dt           j        d                   }|r^t           t          |          j        |                                           }|                                r|                                } t          |          j        | }| j        rt          d           ddl}	t          j                            d|           |	                    |           dS )a  Add the current virtualenv to sys.path so the user can import modules from it.
        This isn't perfect: it doesn't use the Python interpreter with which the
        virtualenv was built, and it ignores the --no-site-packages option. A
        warning will appear suggesting the user installs IPython in the
        virtualenv, but for many cases, it probably works well enough.

        Adapted from code snippets online.

        http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
        VIRTUAL_ENVNr   z=Virtual env path set to '', please check if this is intended.r   rl   cygdrivez:/   c              3   ^   K   | ]'}|j         d                                          k    V  (dS )rl   N)parentsresolve).0r  p_venvs     r^   	<genexpr>z3InteractiveShell.init_virtualenv.<locals>.<genexpr>  s:      ??Av1--///??????rb   win32Libzsite-packageslibzpython{}.{}z\bpy(?:thon)?([23])\.(\d+)\bzlAttempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.r   )r  environr   r   rk  
executabler  r  r   partsanyplatformr   version_inforesearchr  groupsexists	warn_venvsiter  insert
addsitedir)r   r  r  
drive_namevirtual_envvirtual_env_pathp_verre_mpredicted_pathr  r  s             @r^   r   z InteractiveShell.init_virtualenv  s>    
**FZ&",,PQQQF  bj/0088:: ##A&& v|q  V\!_
%B%BaJ 4'4abb1A+BBF????????? 	F<7""d2:m#<e_UUVVKK#
=)5-    $RaR(E 9<bj>WXXD *!%&Bc*:&;&;&BDKKMM&R!S!S!((** * KKMME6#.//6>K> 	@   	;'''$$$$$rb   c                     t           j        t           j        t           j        t           j        d| _        | j        j        | _        t           j	        
                    | j        j                  | _        dS )zuSave the state of hooks in the sys module.

        This has to be called after self.user_module is created.
        )rl  stdoutstderr
excepthookN)rk  rl  r  r  r  _orig_sys_module_staterG  rf   _orig_sys_modules_main_namemodulesget_orig_sys_modules_main_modr   s    r^   r"  z&InteractiveShell.save_sys_module_state  s[    
 14	141458^'E 'E# ,0+;+D(*-+//$:J:S*T*T'''rb   c                     	 | j                                         D ]\  }}t          t          ||           n# t          $ r Y nw xY w| j        | j        t          j        | j        <   dS dS )z$Restore the state of the sys module.N)r  itemssetattrrk  ry   r  r  r  )r   kvs      r^   restore_sys_module_statez)InteractiveShell.restore_sys_module_state  s    	399;; # #1Q""""# 	 	 	D	 *6<@<[CK8999 76s   58 
AAc                     | j         }| j        r| j        dk    r|d| j        z  z  }| j        r|d| j        z   z  }n,| j        r%|d                    t                                z  }|S )Nr   z
IPython profile: %s
r   zTip: {tip}
)tip)banner1r  banner2
enable_tipr  r>   r   banners     r^   r  zInteractiveShell.banner  s|    < 	?DLI55/$,>>F< 	<dT\))FF_ 	<n++

+;;;Frb   c                 :    || j         }t          |d           d S )Nr   )end)r  printr  s     r^   show_bannerzInteractiveShell.show_banner  s'    >[Ff"rb   c                 2   t                      | _        i | _        t          j        j        }|j        D ]'}|                     |t          ||          d           (| j        r5|                     dt          j
        t          j                  d           d S d S )Nd   show_in_pagerZ   )rI   hooksstrdispatchersIPythoncore__all__set_hookgetattrdisplay_pager"   as_hook)r   r  	hook_names      r^   r)  zInteractiveShell.init_hooks  s    XX
  " 	E 	EI MM)WUI%>%>DDDD 	PMM/4<8I+J+JBOOOOO	P 	Prb   r   c                    t          j        ||           }|J| j                            |t	                                }|                    |||           || j        |<   dS |\| j                            |t	                                }|                    t          j        |          ||           || j        |<   dS t          | j
        |d          }|t          j        j
        j        vr)t          d|dt          j        j
        j                   |s#t          j        j
                                        }	 |                    ||           n# t"          $ r |}Y nw xY wt%          | j
        ||           dS )a	  set_hook(name,hook) -> sets an internal IPython hook.

        IPython exposes some of its internal API as user-modifiable hooks.  By
        adding your function to one of these hooks, you can modify IPython's
        behavior to call at runtime your own routines.NzWarning! Hook 'z' is not one of )types
MethodTyper  r  rO   add_sadd_rer  r_  r  r  r  r  r  r  CommandChainDispatcheraddry   r  )	r   r   r  prioritystr_keyre_keyfsdpdps	            r^   r   zInteractiveShell.set_hook
  s    T$'' %))$>>CIIgq(,,,(+D%F%))$>>CJJrz&))1h888(+D%FTZt,,w|)111E44+336 7 7 7  	=#::<<B	FF1X 	 	 	BBB	 	
4$$$$$s   =E E#"E#c                 z    t          | t                    | _        | j                            d| j                   d S )Npre_execute)r1   r2   r?  rB  _clear_warning_registryr   s    r^   r*  zInteractiveShell.init_events7  s5    "4)9::]D,HIIIIIrb   c                 ,    d| j         v r
| j         d= d S d S )N__warningregistry__)user_global_nsr   s    r^   r  z(InteractiveShell._clear_warning_registry<  s,     !D$777#$9::: 87rb   c                     t           j                            |          }	 | j        |         }|j                                         ||_        n0# t          $ r# t          j	        |d          x}| j        |<   Y nw xY w||_
        d |_        |S )a  Return a new 'main' module object for user code execution.

        ``filename`` should be the path of the script which will be run in the
        module. Requests with the same filename will get the same module, with
        its namespace cleared.

        ``modname`` should be the module name - normally either '__main__' or
        the basename of the file without the extension.

        When scripts are executed via %run, we must keep a reference to their
        __main__ module around so that Python doesn't
        clear it, rendering references to module globals useless.

        This method keeps said reference in a private dict, keyed by the
        absolute path of the script. This way, for multiple executions of the
        same script we only keep one copy of the namespace (the last one),
        thus preventing memory leaks from old references while allowing the
        objects from the last execution to be accessible.
        z(Module created for script run in IPythonr   c                      dS NTrj   rj   rb   r^   r}  z/InteractiveShell.new_main_mod.<locals>.<lambda>i  s     rb   )r  r  abspath_main_mod_cacher   rL  rf   r   r  
ModuleType__file____nonzero__)r   filenamemodnamemain_mods       r^   new_main_modzInteractiveShell.new_main_modG  s    ( 7??8,,	(+H5H ##%%% 'H  	H 	H 	H8=8HF9H 9H 9H HHt+H555	H %  -}s   A *A<;A<c                 8    | j                                          dS )a  Clear the cache of main modules.

        Mainly for use by utilities like %reset.

        Examples
        --------
        In [15]: import IPython

        In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')

        In [17]: len(_ip._main_mod_cache) > 0
        Out[17]: True

        In [18]: _ip.clear_main_mod_cache()

        In [19]: len(_ip._main_mod_cache) == 0
        Out[19]: True
        N)r  rL  r   s    r^   clear_main_mod_cachez%InteractiveShell.clear_main_mod_cachem  s    & 	""$$$$$rb   c                     | j         | _        d S r   )pdbcall_pdbr   s    r^   r<  zInteractiveShell.init_pdb  s     rb   c                     | j         S r   )	_call_pdbr   s    r^   _get_call_pdbzInteractiveShell._get_call_pdb  s
    ~rb   c                 R    |dvrt          d          || _        || j        _        d S )N)r   rl   FTz"new call_pdb value must be boolean)ru   r*  r  r(  )r   vals     r^   _set_call_pdbzInteractiveShell._set_call_pdb  s9    &&&ABBB  '*###rb   z,Control auto-activation of pdb at exceptionsc                     |s	| j         sdS t          t          d          st          d           dS | j                            d           dS )a:  Call the pdb debugger.

        Keywords:

          - force(False): by default, this routine checks the instance call_pdb
            flag and does not actually invoke the debugger if the flag is false.
            The 'force' option forces the debugger to activate even if the flag
            is false.
        Nlast_tracebackz1No traceback has been produced, nothing to debug.Tforce)r(  rM  rk  r   r  debugger)r   r2  s     r^   r3  zInteractiveShell.debugger  sa      	 	Fs+,, 	EFFFF##$#/////rb   c                     ||d| _         |                     ||          \  | _        | _        i | _        i | _        | j        j        | j        t          j        d| _        d S )NF)user_global
user_localbuiltin)	default_user_namespacesprepare_user_modulerG  r   user_ns_hiddenr  r   r  ns_tabler   rG  r   s      r^   r!  z'InteractiveShell.init_create_namespaces  ss    J [%<+0D()-)A)A+w)W)W&$, !4  " (,'7'@&*l#.#7 rb   c                     | j         j        S r   )rG  r   r   s    r^   r  zInteractiveShell.user_global_ns  s    ((rb   c                 .   |/|-|                     dd            t          |                      }|t          j        dd          }|j                             dt
                     |j                             dt
                     ||j        }||fS )a  Prepare the module and namespace in which user code will be run.

        When IPython is started normally, both parameters are None: a new module
        is created automatically, and its __dict__ used as the namespace.

        If only user_module is provided, its __dict__ is used as the namespace.
        If only user_ns is provided, a dummy module is created, and user_ns
        becomes the global namespace. If both are provided (as they may be
        when embedding), user_ns is the local namespace, and user_module
        provides the global namespace.

        Parameters
        ----------
        user_module : module, optional
            The current user module in which IPython is being run. If None,
            a clean module will be created.
        user_ns : dict, optional
            A namespace in which to run interactive commands.

        Returns
        -------
        A tuple of user_module and user_ns, each properly initialised.
        Nrf   r   z@Automatically created module for IPython interactive environmentr   __builtin____builtins__)
setdefaultr   r  r  r   r  r<  s      r^   r9  z$InteractiveShell.prepare_user_module  s    0 7#6z:6668/88::K*:VX X XK 	''{CCC''DDD?!*GG##rb   c                 F    | j         j        }| j         t          j        |<   d S r   )rG  rf   rk  r  )r   	main_names     r^   r#  z!InteractiveShell.init_sys_modules1  s$    " $-	!%!1Irb   c                 f   i }| j         K| j         j        |d<   | j         j        |d<   | j         j        |d<   | j         j        |d<   | j         j        |d<   | j        |d<   | j        |d<   | j        |d	<   t          |d
<   | j                            |           | j	                            |           dS )a  Initialize all user-visible namespaces to their minimum defaults.

        Certain history lists are also initialized here, as they effectively
        act as user namespaces.

        Notes
        -----
        All data structures here are only filled in, they are NOT reset by this
        method.  If they were not empty before, data will simply be added to
        them.
        N_ih_oh_dhInOutrP  exitquitr   )
history_managerinput_hist_parsedoutput_histdir_histrP  r   r   r:  updater   rN  s     r^   r,  zInteractiveShell.init_user_nsE  s    :  +,>BuI,8BuI,5BuI +=BtH,8BuI !,=[6
[6
#6
 	""2&&& 	Brb   c                 r    | j         | j        | j        gd | j                                        D             z   S )zGet a list of references to all the namespace dictionaries in which
        IPython might store a user-created object.

        Note that this does not include the displayhook, which also caches
        objects from the output.c                     g | ]	}|j         
S rj   )r   )r  ms     r^   
<listcomp>z0InteractiveShell.all_ns_refs.<locals>.<listcomp>  s    BBBq
BBBrb   )r   r  r:  r  valuesr   s    r^   all_ns_refszInteractiveShell.all_ns_refs  sB     d143FGBBD$8$?$?$A$ABBBC 	Crb   c                 v   | j         | j                             |           |rd| _        d| _        d| _        | j        j        r| j                                         | j        | j	        ur| j        
                                 | j	        }t          |                                          }|                    d           |                    d           |                    d           |D ]}||= | j        
                                 |                                  |r t!          | d          st#          d           nl|rjt#          d	           t          t$          j                                                  }|| j        z
  D ]%}|                    d
          rt$          j        |= &| j                                         | j                                         t2          j        dk    r4dD ]1}|| j        j        d         vr| j                            ||           2|                                  dS )zClear all internal namespaces, and attempt to release references to
        user objects.

        If new_session is True, a new history session will be opened.
        Nrl   Tr?  r@  rf   r   z&Cannot restore sys.module, no snapshotzculling sys module...multiprocessingposix)rL  r]  lessmanline)rL  resetr   last_execution_succeededlast_execution_resultr  do_full_cacheflushr   r  rL  setkeysdiscardr:  r,  rM  r  rk  r  r   
startswithalias_managerclear_aliasesinit_aliasesr  r   magics_managermagicssoft_define_aliasr%  )r   new_session
aggressiverJ  	drop_keysr  current_keyscmds           r^   r]  zInteractiveShell.reset  sW    + &&{333 	%#$D  )-%%)" ) 	%""$$$
 <t222L    		NN	-(((.)))*%%% 	 	A1!!### 	 	#gd,?@@ 	#:;;;; 	#)***s{//1122L!D$:: # #<< 122 KNN 	((***'')))
 7g7 C Cd18@@@&88cBBB 	!!#####rb   c                    |dv rt          d|z            | j        }|r|D ]}	 ||= # t          $ r Y w xY wdS 	 | j        |         n%# t          $ r}t	          d|z            |d}~ww xY w| j        J |                    | j        j                   |D ]*}fd|                                D             }|D ]}||= +| j	        j
        u rd| _	        dD ]/}t          | j        |          u rt          | j        |d           0dS )a  Delete a variable from the various namespaces, so that, as
        far as possible, we're not keeping any hidden references to it.

        Parameters
        ----------
        varname : str
            The name of the variable to delete.
        by_name : bool
            If True, delete variables with the given name in each
            namespace. If False (default), find the variable in the user
            namespace, and delete references to it.
        )r?  r@  zRefusing to delete %szname '%s' is not definedNc                 "    g | ]\  }}|u 	|S rj   rj   )r  nor   s      r^   rT  z,InteractiveShell.del_var.<locals>.<listcomp>  s"    BBB41acQrb   )______)ru   rV  r   r   	NameErrorrL  r  rN  r  r_  r   r  r  r  )	r   varnameby_namens_refsrJ  e	to_deleter   r   s	           @r^   del_varzInteractiveShell.del_var  s    5554w>???" 	:  7   D Ml7+ M M M :W DEE1LM '333NN4/;<<< ! !BBBB288::BBB	% ! !D4! )0C77-1* + : :4+T22c99D,dD999: :s#   *
77A 
A-A((A-c                     |_	 t          j        |          }n"# t          $ r}t          d          |d}~ww xY w| j        D ]!}|D ]}|                    |          r||=  dS dS )aD  Clear selective variables from internal namespaces based on a
        specified regular expression.

        Parameters
        ----------
        regex : string or compiled pattern, optional
            A regular expression pattern that will be used in searching
            variable names in the users namespaces.
        Nz*regex must be a string or compiled pattern)r  r_  rz   rV  r  )r   regexrS  r|  rJ  vars         r^   reset_selectivez InteractiveShell.reset_selective  s     UJu%% U U U LMMSTTU & $ $ $ $Cxx}} $sG$ $ $s    
838c                 z   d}t          |t                    r|}nt          |t          t          t          f          rt          |t                    r|                                }nt          |          }i }t          j        d          }|D ]G}	 t          ||j	        |j
                  ||<   "#  t          d|d|j        j                   Y ExY wnt          d          | j                            |           | j        }|r|D ]}|                    |d           dS |                    |           dS )a  Inject a group of variables into the IPython user namespace.

        Parameters
        ----------
        variables : dict, str or list/tuple of str
            The variables to inject into the user's namespace.  If a dict, a
            simple update is done.  If a str, the string is assumed to have
            variable names separated by spaces.  A list/tuple of str can also
            be used to give the variable names.  If just the variable names are
            give (list/tuple/str) then the variable values looked up in the
            callers frame.
        interactive : bool
            If True (default), the variables will be listed with the ``who``
            magic.
        Nrl   zCould not get variable z from z'variables must be a dict/str/list/tuple)r   r   r   listtuplesplitrk  	_getframeeval	f_globalsf_localsr  f_codeco_nameru   r   rP  r:  pop)r   	variablesinteractivevdictvlistcfr   r:  s           r^   pushzInteractiveShell.push  s{      i&& 	HEE	Cu#566 	H)S)) (!))YEq!!B 5 55"&tR\2;"G"GE$KK5E DD!2!24 5 5 5 5 5	5 FGGG 	E""" , 	) / /""4..../ / !!%(((((s   B00!Cc                     |                                 D ]@\  }}|| j        v r2| j        |         |u r#| j        |= | j                            |d           AdS )a  Remove a dict of variables from the user namespace, if they are the
        same as the values in the dictionary.

        This is intended for use by extensions: variables that they've added can
        be taken back out if they are unloaded, without removing any that the
        user has overwritten.

        Parameters
        ----------
        variables : dict
            A dictionary mapping object names (as strings) to the objects.
        N)r  r   r:  r  )r   r  r   r   s       r^   
drop_by_idzInteractiveShell.drop_by_id?  sm     #** 	4 	4ID#t|##T(:c(A(AL&#''d333	4 	4rb   onamec                    |                      d          }g }d}|D ]}|                    d          r|                     d          ^}}|                                sd} n|                    |           |D ]F}|d         dk    rt	          |dd                   sd} n|                    |dd                    G|                                sd}|                    |           ||fS )a  
        Given an object name, return a list of parts of this object name.

        Basically split on docs when using attribute access,
        and extract the value when using square bracket.


        For example foo.bar[3].baz[x] -> foo, bar, 3, baz, x


        Returns
        -------
        parts_ok: bool
            whether we were properly able to parse parts.
        parts: list of str
            extracted parts



        .T][FN)r  endswithisidentifierr  rv   )r  	raw_partsr  parts_okr  r  indicesinds           r^   _find_partszInteractiveShell._find_partsT  s   , KK$$	 	 	Azz#  !g'')) $HES!!!" + +C2w#~~.?CRC.I.I~#(LLSbS****>>## ! LLOOOOrb   
namespacesc                    |                                 }|                     |          \  }}|                    t                    s1|                    t                    s|st          dddddd          S |d| j        fd| j        fdt          j	        fg}d}d}d}d}d}	d}
|}|d         |dd         }}|D ]\  }}	 ||         }
t          |          D ]r\  }}	 |
}	|t          |          dz
  k    r|                     |
|          }
n5t          |          r|
t          |                   }
nt          |
|          }
k#  Y  n	xY wd	}|} n# t           $ r Y w xY w|sd}
|                    t                    r0|                    t                    }|                     |          }
nv|                    t                    r0|                    t                    }|                     |          }
n,|                     |          }
|
|                     |          }
|
d	}d
}d	}t)          |
t*                    }|s|dv rt-          |          }
d	}d}t          |
||	|||          S )a  Find an object in the available namespaces.


        Returns
        -------
        OInfo with fields:
          - ismagic
          - isalias
          - found
          - obj
          - namespac
          - parent

        Has special code to detect magic functions.
        FN)ismagicisaliasfoundr   	namespacer  InteractivezInteractive (global)zPython builtinr   rl   TzIPython internal)z''z""z[]z{}z())r   r  r  r  r  r  )stripr  re  r7   r8   rU   r   r  r  r   	enumerater   _getattr_propertyrv   rt   r  r   lstripfind_cell_magicfind_line_magicr   r%   r  )r   r  r  r  r  r  r  r  ospacer  r   oname_parts
oname_head
oname_restnsnamerJ  idxparts                     r^   _ofindzInteractiveShell._ofind  s   $ **511%   ++	$$Z00	 	
      *4<82D4GH,k.BCJ
  !,QABBJ
# 	 	IF2n "+:!6!6  IC!$ #j//A"555"&"8"8d"C"CCC066 9&)#d))n&-c4&8&8  !E#FE )    8  	1C
++ 
6Z00**511!!),, 6Y//**511 **511;..u55C+$S%00  	#'AAAz""CE"F
 
 
 	
s   EA$EE
EEc                 "   t          | t                    sk	 t          |          r| t          |                   S t	          t          |           |          }	 t          |t
                    r|S n# t          $ r Y nw xY wt	          | |          S )zProperty-aware getattr to use in object finding.

        If attrname represents a property, return it unevaluated (in case it has
        side effects or raises an error.

        )r   typerv   rt   r  r   ry   )r   attrnameattrs      r^   r  z"InteractiveShell._getattr_property  s     #t$$ 	   %X.. 8s8}}--"499h77DD  dH--  K  "   & sH%%%s   #A1 A1 1
A>=A>c                 .    |                      ||          S )z6Find an object and return a struct with info about it.)r  )r   r  r  s      r^   _object_findzInteractiveShell._object_find%  s    {{5*---rb   c                 
   |                      ||          }| j        r9t          t          d          t          |                     |                    }nd}|j        st          |j        t          j	                  rrt          | j        |          }|j        rt          n|}|dk    r ||j        ||           dS |dk    r ||j        |||fd| j        i| dS  ||j        |           dS t!          d|z             dS )zyGeneric interface to the inspector system.

        This function is meant to be called by pdef, pdoc & friends.
        N'Module ``docrepr`` required but missingpdocpinfor   zObject `%s` not found.z	not found)r  r_   rV   ImportErrorobject_inspectr  rM  r  r!   	HOOK_NAMEr  r   r  rT   r   r   r  )	r   methr  r  r   r   	docformatpmethod	formatters	            r^   _inspectzInteractiveShell._inspect)  sI   
 ''z::# 	 !"KLLL!$"5"5e"<"<==III: 	h.@AA 	dnd33G *.D9Iv~~%33333H	 
 '+&<      %(((((*U2333;rb   c                    | j         5  |                     |          }|j        r/| j                            |j        |||          cddd           S t          j        |d          cddd           S # 1 swxY w Y   dS )zGet object info about oname)r   detail_levelNF)r   r  )r  r  r  r   r   r   r!   object_info)r   r  r  r   s       r^   r  zInteractiveShell.object_inspectK  s    	E 	E$$U++Dz E~**48U)5 +  	E 	E 	E 	E 	E 	E 	E 	E  +eDDD	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	Es   ?A6A66A:=A:c                 :    |                      ||          d         S )z!Get object info as formatted textrY   )object_inspect_mime)r   r  r  s      r^   object_inspect_textz$InteractiveShell.object_inspect_textV  s    ''|<<\JJrb   c           	      h   | j         5  |                     |          }|j        rs| j        r9t          t          d          t	          |                     |                    }nd}| j                            |j	        |||||          cddd           S t          |          # 1 swxY w Y   dS )zGet object info as a mimebundle of formatted representations.

        A mimebundle is a dictionary, keyed by mime-type.
        It must always have the key `'text/plain'`.
        Nr  )r   r  r  omit_sections)r  r  r  r_   rV   r  r  r   	_get_infor   r   )r   r  r  r  r   r  s         r^   r  z$InteractiveShell.object_inspect_mimeZ  s     	& 	&$$U++Dz &+ % ()*STTT )$*=*=e*D*D E EII $I~//H!-'"/ 0  	& 	& 	& 	& 	& 	& 	& 	&$ uoo%%	& 	& 	& 	& 	& 	& 	& 	& 	& 	&s   BB'B''B+.B+c                 p    t          | |           | _        | j                            | j                   dS )z:Sets up the command history, and starts regular autosaves.r  r  N)r5   rL  r  r  r   s    r^   r%  zInteractiveShell.init_historyx  s7    -DFFF!!$"677777rb   c                    t          j        | j                  | _        t          j        | j        | j        d| j                  | _        t          j        | _	         | j
        |  | j                            | j                   d S )Nrx  rl   )modery  	tb_offsetdebugger_cls)r  )r$   r  rp  AutoFormattedTBxmoder  r  rk  r  sys_excepthookset_custom_excset_mode)r   rH  s     r^   r3  z(InteractiveShell.init_traceback_handlers  s    (DK@@@
 %4{*	
 
 
 "n 	.// 	###44444rb   c                     t          |t                    st          d          dd}d |}ndfd	}t          j        ||           | _        || _        dS )a  set_custom_exc(exc_tuple, handler)

        Set a custom exception handler, which will be called if any of the
        exceptions in exc_tuple occur in the mainloop (specifically, in the
        run_code() method).

        Parameters
        ----------
        exc_tuple : tuple of exception classes
            A *tuple* of exception classes, for which to call the defined
            handler.  It is very important that you use a tuple, and NOT A
            LIST here, because of the way Python's except statement works.  If
            you only want to trap a single exception, use a singleton tuple::

                exc_tuple == (MyCustomException,)

        handler : callable
            handler must have the following signature::

                def my_handler(self, etype, value, tb, tb_offset=None):
                    ...
                    return structured_traceback

            Your handler must return a structured traceback (a list of strings),
            or None.

            This will be made into an instance method (via types.MethodType)
            of IPython itself, and it will be called if any of the exceptions
            listed in the exc_tuple are caught. If the handler is None, an
            internal basic one is used, which just prints basic info.

            To protect IPython from crashes, if your handler ever raises an
            exception or returns an invalid result, it will be immediately
            disabled.

        Notes
        -----
        WARNING: by putting in your own exception handler into IPython's main
        execution loop, you run a very good chance of nasty crashes.  This
        facility should only be used if you really know what you are doing.
        z/The custom exceptions must be given as a tuple.Nc                     t          d           t          d|           t          d|           t          d|           d S )Nz'*** Simple custom exception handler ***zException type :zException value:zTraceback      :)r  )r   etyper   tbr  s        r^   dummy_handlerz6InteractiveShell.set_custom_exc.<locals>.dummy_handler  sJ    ;<<<$e,,,$e,,,$b)))))rb   c                     d| z  }| g S t          | t                    r| gS t          | t                    st          |          | D ]&}t          |t                    st          |          '| S )a?  validate structured traceback return type

            return type of CustomTB *should* be a list of strings, but allow
            single strings or None, which are harmless.

            This function will *always* return a list of strings,
            and will raise a TypeError if stb is inappropriate.
            z,CustomTB must return list of strings, not %r)r   r   r  rz   )stbmsgr\  s      r^   validate_stbz5InteractiveShell.set_custom_exc.<locals>.validate_stb  s     A3FC{	C%% %uT** %nn$ ) )!$,, )#C..()Jrb   c                    	  | ||||          } |          S #  |                      dd           t          dt          j                    | j        j        t          j                     }t          | j                            |                     t          d           | j                            ||||          }Y nxY w|S )zwrap CustomTB handler, to protect IPython from user code

                This makes it harder (but not impossible) for custom exception
                handlers to crash IPython.
                r  rj   Nz'Custom TB Handler failed, unregisteringr{   zThe original exception:)r  r  rk  r  r  structured_tracebackr  stb2text)r   r  r   r  r  r  handlerr  s         r^   wrappedz0InteractiveShell.set_custom_exc.<locals>.wrapped  s    !'$uU2	JJJC'<,,,
''D111C#*UUUUA$,A3<>>RC$,55c::;;;3444,AAubI B  CCC 
s
    B'Cr   )r   r  rz   r  r  CustomTBrH  )r   	exc_tupler  r  r  r  s     `  @r^   r  zInteractiveShell.set_custom_exc  s    V )U++ 	OMNNN	* 	* 	* 	*	 	 	. ?#GG      , (66!*rb   c                 :    |                      |||fd           dS )aT  One more defense for GUI apps that call sys.excepthook.

        GUI frameworks like wxPython trap exceptions and call
        sys.excepthook themselves.  I guess this is a feature that
        enables them to keep running after exceptions that would
        otherwise kill their mainloop. This is a bother for IPython
        which expects to catch all of the program exceptions with a try:
        except: statement.

        Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
        any app directly invokes sys.excepthook, it will look to the user like
        IPython crashed.  In order to work around this, we can disable the
        CrashHandler and replace it with this excepthook instead, which prints a
        regular traceback using our InteractiveTB.  In this fashion, apps which
        call sys.excepthook will generate a regular-looking exception from
        IPython, and the CrashHandler will only be triggered by real IPython
        crashes.

        This hook should be used sparingly, only in places which are not likely
        to be true IPython errors.
        r   r  N)showtraceback)r   r  r   r  s       r^   r  zInteractiveShell.excepthook  s*    , 	E5"-;;;;;rb   c                 d   |t          j                    \  }}}n|\  }}}|9t          t           d          r$t           j        t           j        t           j        }}}|t          d          |t           _        |t           _        |t           _        t           j        dk    r|t           _        |||fS )zget exc_info from a given tuple, sys.exc_info() or sys.last_type etc.

        Ensures sys.last_type,value,traceback hold the exc_info we found,
        from whichever source.

        raises ValueError if none of these contain any information
        N	last_typezNo exception to find)r     )	rk  r  rM  r  
last_valuer0  ru   r  last_exc)r   r  r  r   r  s        r^   _get_exc_infozInteractiveShell._get_exc_info  s     "|~~E5""(E5"=sK(( 6#&=#.#&#5 !u =3444 w&& CLeRrb   c                 B    t          d|z  t          j                   dS )ztShow a short message for UsageErrors

        These are special exceptions that shouldn't show a traceback.
        zUsageError: %sr  N)r  rk  r  )r   excs     r^   show_usage_errorz!InteractiveShell.show_usage_error=  s%    
 	$3:666666rb   c                     |                      |          \  }}}t          j        ||          }d                    |          S )z}
        Return as a string (ending with a newline) the exception that
        just occurred, without any traceback.
        r   )r  	tracebackformat_exception_onlyr$  )r   r  r  r   r  r  s         r^   get_exception_onlyz#InteractiveShell.get_exception_onlyD  s@    
  --i88ub-eU;;wws||rb   c                   
 	 	 |                      |          \  }}}n,# t          $ r t          dt          j                   Y dS w xY wt          |t                    r|                     ||           dS |t          u r| 	                    |           dS |r2dg}	|	
                    | j                            ||                     n҈
fd
 
|          rt          j                     n	 t          |d          r|                                }	n| j                            ||||          }	n3# t$          $ r& t          d           t          j                     Y dS w xY w|                     |||	           | j        r|                     d	
           dS |                     |||	           dS # t,          $ r4 t          d|                                 z   t          j                   Y dS w xY w)a  Display the exception that just occurred.

        If nothing is known about the exception, this is the method which
        should be used throughout the code for presenting user tracebacks,
        rather than directly invoking the InteractiveTB object.

        A specific showsyntaxerror() also exists, but this method can take
        care of calling it if needed, so unless you are explicitly catching a
        SyntaxError exception, don't try to analyze the stack manually and
        simply call this method.zNo traceback available to show.r  Nz>An exception has occurred, use %tb to see the full traceback.
c                 V    | dS t          | t                    p | j                  S NFr   BaseExceptionGroup__context__r-  contains_exceptiongroups    r^   r  z?InteractiveShell.showtraceback.<locals>.contains_exceptiongroupo  s<    ;#(5)!3     F44S_EEFrb   _render_traceback_r  zMUnexpected exception formatting exception. Falling back to standard exceptionTr1  r   )r  ru   r  rk  r  
issubclassSyntaxErrorshowsyntaxerrorr0   r  extendr  r  r  	print_excrM  r  r  r  _showtracebackr(  r3  KeyboardInterrupt)r   r  r   r  exception_onlyrunning_compiled_coder  r   r  r  r  s             @r^   r  zInteractiveShell.showtracebackM  s   =	E#'#5#5i#@#@ ubb   7cjIIII %-- 37 $$X/DEEEEE*$$%%e,,,,,! )3 4CJJt1DDUEJ L  L M M M MF F F F F /.u55 ? "+----(  'u.BCC "&+&>&>&@&@&*&8&M&M$)5"	 'N '" '"  ) ( ( (! o   &/111#'44( ++E5#>>>} 2D111F ##E5#66666  	E 	E 	E$00222DDDDDDD	Esd    F6 %AF6 A.F6 7F6 AF6 0AD4 3F6 4,E$ F6 #E$$7F6 F6 6:G43G4r  c                    | j                             |          }d| _        	 t          |           nE# t          $ r8 t          |                    dd                                                     Y nw xY wd| _        dS )zActually show a traceback.

        Subclasses may override this method to put the traceback on a different
        place, like a side channel.
        Tutf-8backslashreplaceFN)r  r  rE  r  UnicodeEncodeErrorencodedecode)r   r  evaluer  r-  s        r^   r  zInteractiveShell._showtraceback  s      ))#..!%	D#JJJJ! 	D 	D 	D#**W&899@@BBCCCCC	D!&s   3 ?A54A5c                    |                                  \  }}}|r%t          |t                    r	 ||_        n#  Y nxY w|rt	          j        |          ng }| j                            |||          }|                     |||           dS )a  Display the syntax error that just occurred.

        This doesn't display a stack trace because there isn't one.

        If a filename is given, it is stuffed in the exception instead
        of what was there before (because Python's parser always uses
        "<string>" when reading from a string).

        If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
        longer stack trace will be displayed.
        N)	r  r  r	  r   r  
extract_tbr  r  r  )r   r   r  r  r   r0  elistr  s           r^   r
  z InteractiveShell.showsyntaxerror  s     (,'9'9';';$un 	
5+66 	!) 9NU	$^444SUm00uEEE5#.....s   9 =c                 .    |                                   dS )zCalled by _run_cell when there's an IndentationError in code entered
        at the prompt.

        This is overridden in TerminalInteractiveShell to show a message about
        the %paste magic.N)r
  r   s    r^   showindentationerrorz%InteractiveShell.showindentationerror  s     	rb   c                     || _         dS )z Sets the 'default' input string for the next command line.

        Example::

            In [1]: _ip.set_next_input("Hello Word")
            In [2]: Hello Word_  # cursor is here
        N)rl_next_input)r   rr   r   s      r^   set_next_inputzInteractiveShell.set_next_input  s     rb   c                 >   ddl m} ddlm}m}m}m}  || | j        | j        |           | _	        | j
                            | j	                   | j                            dt                                }|| j        d<   || j	        _        |                     d|d           |                     d|d           |                     d|d	           |                     d|d
           |                     d|d           |                     d|d           dS )aN  Initialize the completion machinery.

        This creates completion machinery that can be used by client code,
        either interactively in-process (typically triggered by the readline
        library), programmatically (such as in test suites) or out-of-process
        (typically over the network by remote frontends).
        r   )IPCompleter)cd_completermagic_run_completermodule_completerreset_completer)r  r  global_namespacer  complete_commandimport)r  fromz%aimportz%runz%cdz%resetN)IPython.core.completerr!  IPython.core.completerlibr"  r#  r$  r%  r   r  	Completerr  r  r  r  rO   custom_completersr   )r   r!  r"  r#  r$  r%  sdisps          r^   r1  zInteractiveShell.init_completer  sn    	766666	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 	
 %4/3|6:6I,0' ' '
 	!!$.111 #''(:KMMJJ27./+0((*:hOOO(*:fMMM(*:jQQQ(*=PPP(,%HHH(/XNNNNNrb   c                 |    | j         5  | j                            |||          cddd           S # 1 swxY w Y   dS )a  Return the completed text and a list of completions.

        Parameters
        ----------
        text : string
            A string of text to be completed on.  It can be given as empty and
            instead a line/position pair are given.  In this case, the
            completer itself will split the line like readline does.
        line : string, optional
            The complete line that text is part of.
        cursor_pos : int, optional
            The position of the cursor on the input line.

        Returns
        -------
        text : string
            The actual text that was completed.
        matches : list
            A sorted list with all possible completions.

        Notes
        -----
        The optional arguments allow the completion to take more context into
        account, and are part of the low-level completion API.

        This is a wrapper around the completion mechanism, similar to what
        readline does at the command line when the TAB key is hit.  By
        exposing it as a method, it can be used by other non-readline
        environments (such as GUIs) for text completion.

        Examples
        --------
        In [1]: x = 'hello'

        In [2]: _ip.complete('x.l')
        Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
        N)r  r,  complete)r   textr\  
cursor_poss       r^   r0  zInteractiveShell.complete  s    R  	C 	C>**4zBB	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C 	C   155c                 z    t          j        || j                  }| j        j                            ||           dS )a  Adds a new custom completer function.

        The position argument (defaults to 0) is the index in the completers
        list where you want the completer to be inserted.

        `completer` should have the following signature::

            def completion(self: Completer, text: string) -> List[str]:
                raise NotImplementedError

        It will be bound to the current Completer instance and pass some text
        and return a list with current completions to suggest to the user.
        N)r  r  r,  custom_matchersr  )r   	completerposnewcomps       r^   set_custom_completerz%InteractiveShell.set_custom_completer)	  s9     "9dn==&--c':::::rb   c                     |r$|j         | j        _        |j        | j        _        dS | j        | j        _        | j        | j        _        dS )zSet the frame of the completer.N)r  r,  r  r  r&  r   r  )r   frames     r^   set_completer_framez$InteractiveShell.set_completer_frame;	  sH     	B',~DN$.3oDN+++'+|DN$.2.ADN+++rb   c                 &   ddl m} t          j        | | |                    |                     | _        | j                            | j                   | j        j        | _	        | 	                    |j
        |j        |j        |j        |j        |j        |j        |j        |j        |j        |j        |j        |j        |j                   | 	                    |j                   | j        }|                    dd           |                    dd           |                    dd	           |                    d
dd           |                    ddd           |                    ddd           |                     d| j                   d S )Nr   )rj  )r  r  user_magicsededithisthistoryreprecallSVGsvgcellHTMLhtmlr{   	writefilerp  )IPython.corerj  r    MagicsManager
UserMagicsri  r  r  rB  register_magics
AutoMagicsBasicMagics
CodeMagicsConfigMagicsDisplayMagicsExecutionMagicsExtensionMagicsHistoryMagicsLoggingMagicsNamespaceMagicsOSMagicsPackagingMagicsPylabMagicsScriptMagicsAsyncMagicsregister_aliasr  rp  )r   rS  mmans      r^   r9  zInteractiveShell.init_magicsH	  s   ,,,,,,#1*./0||D/A/AC C C 	!!$"5666  $2;Q\1=!,NAOQ->qqz1+<M1>		
 	
 	
 	Q]+++ " 	D&)))FI...E8,,,E5&111FFF333FK888
 	Hdk22222rb   r\  c                 @    | j                             |||           d S )N)
magic_kind
magic_name)ri  register_function)r   funcra  rb  s       r^   register_magic_functionz(InteractiveShell.register_magic_functionk	  s3    --ZJ 	. 	
 	
 	
 	
 	
rb   rb  c                    | j         | j        d|         } ||          }||S | j        j                            |          }|dS |                     d|            ||          }|S )aT  
        Try to find a magic potentially lazy-loading it.

        Parameters
        ----------

        type_: "line"|"cell"
            the type of magics we are trying to find/lazy load.
        magic_name: str
            The name of the magic we are trying to find/lazy load


        Note that this may have any side effects
        )r\  rG  Nload_ext)r  r  ri  lazy_magicsr  r  )r   type_rb  finderfnlazyress          r^   _find_with_lazy_loadz%InteractiveShell._find_with_lazy_loadq	  s     .8LMMeTVJ>I".22:>><4J---fZ  
rb   c                    |                      d|          }|L| j        j                            |          }|r+|                     d|           |                     |          }|4|                     |          }d}|dnd|z  }t          |||fz            |}	t          |t          j
        d          r|}
n|                     ||	          }
|
g}i }t          |dd          r|                     |	          |d	<   | j        5   ||i |}ddd           n# 1 swxY w Y   t          |t          j        d          rt          j        |
          rdS |S )
a  Execute the given line magic.

        Parameters
        ----------
        magic_name : str
            Name of the desired magic function, without '%' prefix.
        line : str
            The rest of the input line as a single string.
        _stack_depth : int
            If run_line_magic() is called from magic() then _stack_depth=2.
            This is added to ensure backward compatibility for use of 'get_ipython().magic()'
        r\  Nrg  z'Line magic function `%%%s` not found%s.r   z= (But cell magic `%%%%%s` exists, did you mean that instead?)Fneeds_local_scopelocal_ns)rn  ri  rh  r  r  r  r  r0   r  r    MAGIC_NO_VAR_EXPAND_ATTR
var_expandget_local_scoper  MAGIC_OUTPUT_CAN_BE_SILENCEDr-   semicolon_at_end_of_expression)r   rb  r\  _stack_depthrk  rl  cmetplextrastack_depthmagic_arg_sr   r   r   s                 r^   r  zInteractiveShell.run_line_magic	  s    &&vz:::&266zBBD 6##J555))*55:%%j11B<D*BB ,BDN,OETZ$77888 'Kr595AA A""oodK@@=DFr.66 G%)%9%9+%F%Fz"" - -T,V,,- - - - - - - - - - - - - - - r5=uEE  =kJJ  4Ms   	DD"Dc                 :    t          j        |dz             j        S )zGet local scope at given stack depth.

        Parameters
        ----------
        stack_depth : int
            Depth relative to calling frame
        rl   )rk  r  r  )r   r{  s     r^   rt  z InteractiveShell.get_local_scope	  s     }[1_--66rb   c                    |                      d|          }|S|                     |          }d}|dnd                    |          }t          |                    ||                    |dk    rQd                    |          }|                     |          |d                    |          z  }t          |          d}	t	          |t
          j        d	          r|}
n|                     ||	          }
i }t	          |d
d	          r
| j        |d<   | j	        5  |
|f} ||i |}ddd           n# 1 swxY w Y   t	          |t
          j
        d	          rt          j        |          rdS |S )aT  Execute the given cell magic.

        Parameters
        ----------
        magic_name : str
            Name of the desired magic function, without '%' prefix.
        line : str
            The rest of the first input line as a single string.
        cell : str
            The body of the cell as a (possibly multiline) string.
        rG  Nz Cell magic `%%{0}` not found{1}.r   z; (But line magic `%{0}` exists, did you mean that instead?)z2%%{0} is a cell magic, but the cell body is empty.z- Did you mean the line magic %{0} (single %)?r   Frp  rq  )rn  r  r  r0   r  r    rr  rs  r   r  ru  r-   rv  )r   rb  r\  rG  rk  lmry  rz  messager{  r|  r   r   r   s                 r^   run_cell_magiczInteractiveShell.run_cell_magic	  s    &&vz:::%%j11B5D*BB ,::@&:L:L T[[U;;<<<RZZJQQR\]]G##J//;JQQR\]]]W%%%
 Kr595AA A""oodK@@Fr.66 2%)\z"" - -#T*T,V,,- - - - - - - - - - - - - - - r5=uEE  =dCC  4Ms   D66D:=D:c                 L    | j         j        d                             |          S )zUFind and return a line magic by name.

        Returns None if the magic isn't found.r\  ri  rj  r  r   rb  s     r^   r  z InteractiveShell.find_line_magic 
  #     ")&155jAAArb   c                 L    | j         j        d                             |          S )zUFind and return a cell magic by name.

        Returns None if the magic isn't found.rG  r  r  s     r^   r  z InteractiveShell.find_cell_magic
  r  rb   c                 L    | j         j        |                             |          S )zbFind and return a magic of the given type by name.

        Returns None if the magic isn't found.r  )r   rb  ra  s      r^   
find_magiczInteractiveShell.find_magic
  s#     ")*599*EEErb   c                     ddl m} t          |t                    r|                    |          }t          ||j                  st          d          || j        |<   dS )a#  Define a new macro

        Parameters
        ----------
        name : str
            The name of the macro.
        themacro : str or Macro
            The action to do upon invoking the macro.  If a string, a new
            Macro object is created by passing the string to it.
        r   )macroz-A macro must be a string or a Macro instance.N)rK  r  r   r   r:   ru   r   )r   r   themacror  s       r^   define_macrozInteractiveShell.define_macro
  so     	'&&&&&h$$ 	-{{8,,H(EK00 	NLMMM%Trb   c                     |                                                     d          rt          d          t          |                     |d                    | j        d<   dS )a2  Call the given cmd in a subprocess, piping stdout/err

        Parameters
        ----------
        cmd : str
            Command to execute (can not end in '&', as background processes are
            not supported.  Should not be a command that expects input
            other than simple text.
        &#Background processes not supported.rl   depth
_exit_codeN)rstripr  OSErrorrN   rs  r   r   rp  s     r^   system_pipedzInteractiveShell.system_piped.
  s`     ::<<  %% 	A ?@@@
 &,DOOCqO,I,I%J%J\"""rb   c                 ,   |                      |d          }|dk    rd}n|                                d         }d}||v r't          j        d                    |                     t
          j        dk    rddlm}  |            5 }|d
|d|}	 t          j
        |          }nB# t          $ r5 t          d|                                 z   t
          j                   d}Y nw xY wd	d	d	           n# 1 swxY w Y   nt          j                            dd	          }	 t#          j        |d|          }nB# t          $ r5 t          d|                                 z   t
          j                   d}Y nw xY w|dk    r|dz
   }|| j        d<   d	S )zCall the given cmd in a subprocess using os.system on Windows or
        subprocess.call using the system shell on other platforms.

        Parameters
        ----------
        cmd : str
            Command to execute.
        rl   r  r   r   )pipcondacdzhYou executed the system command !{0} which may not work as expected. Try the IPython magic %{0} instead.r  )AvoidUNCPathNz"pushd z &&"r   r  SHELLT)r  r        r  )rs  r  warningsr   r  rk  r  IPython.utils._process_win32r  r  rN   r  r  r  r  r  r  
subprocesscallr   )r   rp  main_cmdhas_magic_alternativesr  r  ecr  s           r^   
system_rawzInteractiveShell.system_rawE
  s    ooco++"99HHyy{{1~H!7---MG&""	   <7""AAAAAA 4##/3ttSS9C3BB(   $!8!8!:!::LLLLBBB              $ 66J_SLLL$   dT44666SZHHHH CxxCx[ &(\"""sH   C7B)(C7)<C(%C7'C((C77C;>C;$D< <<E;:E;c                 &   |                                                     d          rt          d          t          |                     ||dz                       }|r"t          |                                          }nt          |          }|S )a[  Get output (possibly including stderr) from a subprocess.

        Parameters
        ----------
        cmd : str
            Command to execute (can not end in '&', as background processes are
            not supported.
        split : bool, optional
            If True, split the output into an IPython SList.  Otherwise, an
            IPython LSString is returned.  These are objects similar to normal
            lists and strings, with a few convenience attributes for easier
            manipulation of line-based output.  You can use '?' on them for
            details.
        depth : int, optional
            How many frames above the caller are the local variables which should
            be expanded in the command string? The default (0) assumes that the
            expansion variables are in the stack frame calling this function.
        r  r  rl   r  )r  r  r  rM   rs  rS   
splitlinesrR   )r   rp  r  r  outs        r^   rM   zInteractiveShell.getoutput
  s    & ::<<  %% 	A?@@@57;;<< 	 (())CC3--C
rb   c                 p    t          | |           | _        | j                            | j                   d S Nr  )r&   rf  r  r  r   s    r^   r:  zInteractiveShell.init_alias
  s7    )TBBB!!$"455555rb   c                 p    t          | |           | _        | j                            | j                   d S r  )r3   extension_managerr  r  r   s    r^   r=  z'InteractiveShell.init_extension_manager
  s7    !1T!J!J!J!!$"899999rb   c                 n    t          |           | _        | j                            | j                   d S r  )r;   payload_managerr  r  r   s    r^   r>  zInteractiveShell.init_payload
  s5    -T:::!!$"677777rb   c                     t          | |           | _        | j                            | j                   | j        j        | _        d S r  )r<   prefilter_managerr  r  prefilter_linesr#   r   s    r^   r'  zInteractiveShell.init_prefilter
  sD    !1T!J!J!J!!$"8999 /?rb   c                 <    | j         sdS t          d|z              dS )a  Print to the screen the rewritten form of the user's command.

        This shows visual feedback by rewriting input lines that cause
        automatic calling to kick in, like::

          /f x

        into::

          ------> f(x)

        after the user's input prompt.  This helps the user understand that the
        input line was transformed automatically by IPython.
        Nz------> )show_rewritten_inputr  r  s     r^   auto_rewrite_inputz#InteractiveShell.auto_rewrite_input
  s/     ( 	F 	j3rb   c                     |                                  \  }}}| j                            ||          }d||j        t	          j        |          d}|S )zJreturn simple exception dict

        for use in user_expressions
        r   )statusr  enamer  )r  r  r  rf   rF   safe_unicode)r   r  r  r  r  r  s         r^   _user_obj_errorz InteractiveShell._user_obj_error
  sb     !..00vr 33E6BB ^,V44	
 
 rb   c                 L    | j                             |          \  }}d||d}|S )zRformat a user object to display dict

        for use in user_expressions
        ok)r  datametadata)r  r  )r   r   r  mdr   s        r^   _format_user_objz!InteractiveShell._format_user_obj
  s:     )0055b
 

 rb   c                     i }| j         }| j        }|                                D ]K\  }}	 |                     t	          |||                    }n#  |                                 }Y nxY w|||<   L|S )a  Evaluate a dict of expressions in the user's namespace.

        Parameters
        ----------
        expressions : dict
            A dict with string keys and string values.  The expression values
            should be valid Python expressions, each of which will be evaluated
            in the user namespace.

        Returns
        -------
        A dict, keyed like the input expressions dict, with the rich mime-typed
        display_data of each value.
        )r   r  r  r  r  r  )r   expressionsr  r   	global_nskeyexprr   s           r^   user_expressionsz!InteractiveShell.user_expressions  s     ,'	$**,, 	 	IC/--d4G.L.LMM/,,..CHH
s   $AA(c                 |    | j         5  t          || j        | j                   ddd           dS # 1 swxY w Y   dS )z4Execute a normal python statement in user namespace.N)r  execr  r   r  s     r^   exzInteractiveShell.ex!  s     	9 	9d)4<888	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9 	9r3  c                 z    | j         5  t          || j        | j                  cddd           S # 1 swxY w Y   dS )zeEvaluate python expression expr in user namespace.

        Returns the result of evaluation
        N)r  r  r  r   )r   r  s     r^   evzInteractiveShell.ev&  s    
  	A 	Ad14<@@	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	As   044)exit_ignoreraise_exceptionsr   c                   t          |                                                                          }	 |                    d          5  	 ddd           n# 1 swxY w Y   n#  t	          d|z             Y dS xY wt          |j                  }t          |          5  | j        5  	 |dz   dd         \  }}t          j
        ||||r| j        nd           nT# t          $ r,}	|	j        r|r |s|                     d           Y d}	~	n#d}	~	w |r |                     d           Y nxY wddd           n# 1 swxY w Y   ddd           dS # 1 swxY w Y   dS )	aj  A safe version of the builtin execfile().

        This version will never throw an exception, but instead print
        helpful error messages to the screen.  This only works on pure
        Python files with the .py extension.

        Parameters
        ----------
        fname : string
            The name of the file to be executed.
        *where : tuple
            One or two namespaces, passed to execfile() as (globals,locals).
            If only one is given, it is passed as both.
        exit_ignore : bool (False)
            If True, then silence SystemExit for non-zero status (it is always
            silenced for zero status, as it is so common).
        raise_exceptions : bool (False)
            If True raise exceptions everywhere. Meant for testing.
        shell_futures : bool (False)
            If True, the code will share future statements with the interactive
            shell. It will both be affected by previous __future__ imports, and
            any __future__ imports in the code will affect the shell. If False,
            __future__ imports are not shared in either direction.

        rbN,Could not open file <%s> for safe execution.r   r   Tr  r  )r   
expanduserr  r   r   r   r  rP   r  rF   execfiler_  
SystemExitcoder  )
r   fnamer  r  r   wherednamegloblocr  s
             r^   safe_execfilezInteractiveShell.safe_execfile.  so   4 U&&((0022	D!!                	?%GHHHFF
 EL!!!%(( 	0 	0$*; 	0 	00"X-rr2	c"4$1;DLLt= = = =  @ @ @ ; @' & @**$*???0# ""Q"/////3	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0 	0s   A$ 
AA$ AA$ A A$ $A;!E)D<+0CD<
D-&"DD<D-+D<0E<E 	 EE 	EEEc                 r   t                                                                                    	                     d          5  	 ddd           n# 1 swxY w Y   n#  t	          dz             Y dS xY wt          j                  }fd}t          |          5  	  |            D ]:}|                     |d|          }|r|	                                 1|j
        s n;n0#  |r |                                  t	          dz             Y nxY wddd           dS # 1 swxY w Y   dS )a  Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.

        Parameters
        ----------
        fname : str
            The name of the file to execute.  The filename must have a
            .ipy or .ipynb extension.
        shell_futures : bool (False)
            If True, the code will share future statements with the interactive
            shell. It will both be affected by previous __future__ imports, and
            any __future__ imports in the code will affect the shell. If False,
            __future__ imports are not shared in either direction.
        raise_exceptions : bool (False)
            If True raise exceptions everywhere.  Meant for testing.
        r  Nr  c               3      K   j         dk    r<ddlm}   | d          }|j        sdS |j        D ]}|j        dk    r	|j        V  dS                     d	          V  dS )
z,generator for sequence of code blocks to runz.ipynbr   )read   )
as_versionNr  r  rm  )suffixnbformatr  cells	cell_typesource	read_text)r  nbrG  r  s      r^   	get_cellsz5InteractiveShell.safe_execfile_ipy.<locals>.get_cells  s      |x''))))))T%A...x FH * *D~//"k)))* * oowo7777777rb   T)r   r   z$Unknown failure executing file: <%s>)r   r  r  r   r   r   r  rP   run_cellr   r   r  )r   r  r   r  r  r  rG  r   s    `      r^   safe_execfile_ipyz"InteractiveShell.safe_execfile_ipyr  s     U&&((0022	D!!                	?%GHHHFF
 EL!!	8 	8 	8 	8 	8 "%(( 	E 	EE%IKK  D!]]4M]ZZF' **,,,,#^ E# ""$$$;eCDDDDD	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	E 	EsZ   A% AA% AA%  A!A% %A<'D,)AC/.D,/+DD,,D03D0c                    	 	 |                     t          j        t          |          dd                     dS # t          $ r}|j        r Y d}~dS d}~ww xY w#  |                                  t          d|z             Y dS xY w)a  A safe version of runpy.run_module().

        This version will never throw an exception, but instead print
        helpful error messages to the screen.

        `SystemExit` exceptions with status code 0 or None are ignored.

        Parameters
        ----------
        mod_name : string
            The name of the module to be executed.
        where : dict
            The globals namespace.
        r   T)run_name	alter_sysNz&Unknown failure executing module: <%s>)rP  runpy
run_moduler   r  r  r  r   )r   mod_namer  r  s       r^   safe_run_modulez InteractiveShell.safe_run_module  s    	F$S]]Z/35 5 5        ;      	F   9HDEEEEEEs'   7< 
AAA AA (Bchannel)r  r  c              #   z    K   t          t                    }|j         fd}||_        dV  |_        dS )a  Capture output of a given standard stream and store it in history.

        Uses patching of write method for maximal compatibility,
        because ipykernel checks for instances of the stream class,
        and stream classes in ipykernel implement more complex logic.
        c                     
| g|R i |}t          j        j        j        j        j        g          r|S | s|S j        }d}j        j        }	dk    rdnd}||v r!||         }|d         j	        |k    r|d         }|.t          |ddi          }||                             |           |j        dxx         | z  cc<   |S )	zGWrite data to both the original destination and the capture dictionary.Nr  
out_stream
err_streamr  streamr   )output_typebundle)r  r  is_publishingr  	is_activerE  r   rL  outputsr  r6   r  r  )r  r   r   r   r   output_streamoutputs_by_counterr  r  r  original_writer   s            r^   writez$InteractiveShell._tee.<locals>.write  s$   #^D:4:::6::F$2$.*    "2O M!%!5!=*1X*=*=,,<K"444,_=2;*k99$+BKM$ - +XrN! ! ! #?3::=III ***d2***Mrb   N)r  rk  r  )r   r  r  r  r  s   ``  @r^   _teezInteractiveShell._tee  sa       g&&	 	 	 	 	 	 	< %rb   c           	         d}|                      d          5  |                      d          5  	 |                     |||||          }| j                            d           |s| j                            d|           n=# | j                            d           |s| j                            d|           w w xY wddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   |S )a  Run a complete IPython cell.

        Parameters
        ----------
        raw_cell : str
            The code (including IPython code such as %magic functions) to run.
        store_history : bool
            If True, the raw and translated cell will be stored in IPython's
            history. For user code calling back into IPython's machinery, this
            should be set to False.
        silent : bool
            If True, avoid side-effects, such as implicit displayhooks and
            and logging.  silent=True forces store_history=False.
        shell_futures : bool
            If True, the code will share future statements with the interactive
            shell. It will both be affected by previous __future__ imports, and
            any __future__ imports in the code will affect the shell. If False,
            __future__ imports are not shared in either direction.
        cell_id : str, optional
            A unique identifier for the cell. This is used in the messaging system
            to match output with execution requests and for tracking cell execution
            history across kernel restarts. In notebook contexts, this is typically
            a UUID generated by the frontend. If None, the kernel may generate an
            internal identifier or proceed without cell tracking capabilities.
        Returns
        -------
        result : :class:`ExecutionResult`
        Nr  )r  r  post_executepost_run_cell)r  	_run_cellr?  r@  )r   r   r   r   r   r   r   s          r^   r  zInteractiveShell.run_cell  s   H YYxY(( 	A 	A$))H)*E*E 	A 	AAmV]G  ##N333 AK''@@@ ##N333 AK''@@@@A	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A 	A sK   C#CB8C:B==C C#C	C#C	C##C'*C'r   r   r   r   r   c           	         d}	 |                      |          }n%# t          $ r |}t          j                    }Y nw xY w|J |                     |||||||          }| j        r| j        }	n'|                     |||          r| j        }	nt          }		  |	|          }
n_# t          $ rR}	 t          |||||          }t          |          }
||
_        |                     d           n#  Y nxY wY d}~nd}~ww xY w|
S )z/Internal method to run a complete IPython cell.N)r   r   r   transformed_cellpreprocessing_exc_tupler   r	  r
  Tr  )transform_cellr  rk  r  run_cell_asyncrD  should_run_asyncr   ro   r   r   r   r   r  )r   r   r   r   r   r   r
  r	  coror   r   r|  r   s                r^   r  zInteractiveShell._run_cell%  s    #'	5#228<< 	5 	5 	5'&)lnn###	5  +++""''-$; # 
 
  		)%FF""-$; # 
 
 	)
 %FF(F	VD\\FF 		 		 		$mV]G  )..'($""">>>>		 s6    <<B" "
C>-?C-,C9-C1/C99C>r  c                    | j         sdS |dS |J |Dt          j        dt          d           	 |                     |          }n# t
          $ r Y dS w xY w|}t          |          S )aT  Return whether a cell should be run asynchronously via a coroutine runner

        Parameters
        ----------
        raw_cell : str
            The code to be executed

        Returns
        -------
        result: bool
            Whether the code needs to be run with a coroutine runner or not
        .. versionadded:: 7.0
        FNz`should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.r   rr  )r   r  r   ru  r  r  rp   )r   r   r	  r
  rG  s        r^   r  z!InteractiveShell.should_run_asynca  s      ~ 	5".5&...#M+ #	 	 	 	**844    uu
 $D%%%s   A 
AA)r	  r
  r   r	  r
  c          	         K   t          ||||          }t          |          |r|                                rd _         _        S |rdr j        _         fd}	 j                            d           |s j                            d|           |Zt          j	        dt          d	           	                      |          }
d}n,# t          $ r t          j                    }|}
Y nw xY w||}
n|}
d
|
v rd|
v rdr* j        J  j                             j        |
|           |s j                            |
|           |8                     |           r xj        dz  c_         |	|d                   S |r j        n                                 } j        5  |                    |
 j        |          } j        5  	 |                    |
|          }n#  j        $ r[}t          j                    \  }}}                     |||            |	|          cY d}~cddd           cddd           S d}~wt8          $ rA}                                   |	|          cY d}~cddd           cddd           S d}~wt<          t>          t@          tB          tD          f$ rA} #                                  |	|          cY d}~cddd           cddd           S d}~ww xY w	  $                    |          }nN# tJ          $ rA}                                   |	|          cY d}~cddd           cddd           S d}~ww xY w j&        _'        |rdn j(        } )                    |j*        |||           d{V }|  _         _        d j&        _'        ddd           n# 1 swxY w Y   ddd           n# 1 swxY w Y   rm j        J  j        +                     j                    j        }j,        r' -                    j,                   j        j.        |<    xj        dz  c_        S )a  Run a complete IPython cell asynchronously.

        Parameters
        ----------
        raw_cell : str
          The code (including IPython code such as %magic functions) to run.
        store_history : bool
          If True, the raw and translated cell will be stored in IPython's
          history. For user code calling back into IPython's machinery, this
          should be set to False.
        silent : bool
          If True, avoid side-effects, such as implicit displayhooks and
          and logging.  silent=True forces store_history=False.
        shell_futures : bool
          If True, the code will share future statements with the interactive
          shell. It will both be affected by previous __future__ imports, and
          any __future__ imports in the code will affect the shell. If False,
          __future__ imports are not shared in either direction.
        transformed_cell: str
          cell that was passed through transformers
        preprocessing_exc_tuple:
          trace if the transformation failed.

        Returns
        -------
        result : :class:`ExecutionResult`

        .. versionadded:: 7.0
        TFc                     r>j         r'                    |           j         j        j        <   xj        dz  c_        | _        d_        _        S )Nrl   F)rL  _format_exception_for_storage
exceptionsr   r   r^  r_  )r   r   r   r   s    r^   r   z:InteractiveShell.run_cell_async.<locals>.error_before_exec  so     *'  ::5AA (3D4HI $$)$$',F$,1D))/D&Mrb   r  pre_run_cellNz`run_cell_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.r   rr  zget_ipython().run_line_magic(pasterl   )raw_code)r   r  )interactivitycompilerr   )/r   r   isspacer^  r_  r   r?  r@  r  r   ru  r  r  rk  r  rL  store_inputsr  logr  r_  r^  r  cacher  	ast_parserH  r  IndentationErrorr  OverflowErrorr	  ru   rz   MemoryErrorr
  transform_astr/   r  exec_resultast_node_interactivityrun_ast_nodesbodystore_outputr   r  r  )r   r   r   r   r   r	  r
  r   r   r   rG  r  	cell_namecode_astr|  r  r   r  r  
has_raised
exec_countr   s   ` `                  @r^   r  zInteractiveShell.run_cell_async  s     P X}fmWUU && 	X--// 	,0D))/D&M 	"!M 	:%)%9F"	 	 	 	 	 	 	 	M*** 	6K555#M+ #	 	 	 	/**844
 +/''	       *-,..'  '.' +d22w$!M  	T'333 --d.BD(SSS 	,KOOD(+++ #.6777 *$$)$$$$%<Q%?@@@
 $1K4<<d6I6I6K6K *	4 *	4 tT-AHUUI" '4 '40'11$1KKHH- 0 0 0'*|~~$E5"MM%333,,Q///////'4 '4 '4 '4 '4 '4 '4*	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4 ( 0 0 0--///,,Q///////'4 '4 '4 '4 '4 '4 '4*	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4 &{J	#% 0 0 0((***,,Q///////'4 '4 '4 '4 '4 '4 '4*	4 *	4 *	4 *	4 *	4 *	4 *	4 *	400#11(;;HH$ 0 0 0&&(((,,Q///////+'4 '4 '4 '4 '4 '4 '4*	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4,0 06 , +1 Qd6Q $(#5#5hmY%2Xf $6 $V $V V V V V V V
 5?--3* 04 ,O'4 '4 '4 '4 '4 '4 '4 '4 '4 '4 '4 '4 '4 '4 '4*	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4 *	4X  	&'333  --d.BCCC-J#  66v7KLL $/
;
   A%  s   =C C76C72%O$OG20O2
L<8I4L5O9O$LJ=L>OO$&LK=L O$O$=LOLO
M'&M"M'O	O$"M''AOO$O	O$O	O$$O(+O(c                   	 t          |          }|}|j        }t          |t          t          f          r\|r%t          |t                    r	 ||_        n#  Y nxY w|rt          j        |          ng }| j	        
                    |||          }n|t          u rd| g}n	fd	 	|          rt          j        |||          }nk	 t          |d          r|                                }n| j        
                    |||d          }n&# t           $ r t          j        |||          }Y nw xY w|j        t%          |          |dS )z
        Format an exception's traceback and details for storage, with special handling
        for different types of errors.
        zUsageError: c                 V    | dS t          | t                    p | j                  S r  r  r  s    r^   r  zOInteractiveShell._format_exception_for_storage.<locals>.contains_exceptiongroup_  s:    ; 5!#'9:: >U>UO? ? rb   r  rl   r  )r  r  r  )r  __traceback__r  r	  r   r   r   r  r  r  r  r0   format_exceptionrM  r  r  r  rf   r   )
r   	exceptionr   r  r  r  r  r  r  r  s
            @r^   r  z.InteractiveShell._format_exception_for_storageB  s    Y$ ek+;<== '	H Jv{;; &.FOOD 1FMI(,,,2E-44UFEJJCC j  *&**+CC     '&v.. H0CCHv';<< $7799 #0EE!62 F   ! H H H#4UFBGGCCCH 3v;;SQQQs   A A
AD  D10D1c                 |   | j                             |          }t          |                                          dk    r<| j        5  | j                            |          dz   }ddd           n# 1 swxY w Y   |                    d          }| j        D ]} ||          }d                    |          }|S )a  Transform an input cell before parsing it.

        Static transformations, implemented in IPython.core.inputtransformer2,
        deal with things like ``%magic`` and ``!system`` commands.
        These run on all input.
        Dynamic transformations, for things like unescaped magics and the exit
        autocall, depend on the state of the interpreter.
        These only apply to single line inputs.

        These string-based transformations are followed by AST transformations;
        see :meth:`transform_ast`.
        rl   r   NT)keependsr   )	r  r  r   r  r  r  r  r  r$  )r   r   rG  lines	transforms        r^   r  zInteractiveShell.transform_celly  s    -<<XFFt  !!Q&&" K K -==dCCdJK K K K K K K K K K K K K K K
 ..5 	% 	%IIe$$EEwwu~~s   A11A58A5c                    | j         D ]h}	 |                    |          }# t          $ r  t          $ r9}t	          d|d|           | j                             |           Y d}~ad}~ww xY w| j         rt          j        |           |S )a  Apply the AST transformations from self.ast_transformers

        Parameters
        ----------
        node : ast.Node
            The root node to be transformed. Typically called with the ast.Module
            produced by parsing user input.

        Returns
        -------
        An ast.Node corresponding to the node it was called with. Note that it
        may also modify the passed object, so don't rely on references to the
        original AST.
        zAST transformer z* threw an error. It will be unregistered. N)r   visitr/   r  r   removeastfix_missing_locations)r   nodetransformerr|  s       r^   r#  zInteractiveShell.transform_ast  s      0 	: 	:K:"((..      : : :"{{AA'   %,,[99999999:   	,%d+++s   !A./A))A.nodelistr)  c                   K   |sdS |dk    rt          |d         t                    r|d         }t          |t          j                  r&t	          |j                  dk    r|j        d         }nt          |t                    r|j        }nd}t          |t          j                  rft          j	        t          j        |j
        t          j                                        }t          j        |           |                    |           d}d}	|dk    r%t          |d         t          j	                  rd}nd	}|d	k    r|g }}
n8|dk    r|dd         |dd         }}
n|d
k    rg |}}
nt          d|z            	 d }g }|
D ]}|                    |df           |D ]}|                    |df           |D ]\  }}|dk    rt          |gg           }n|dk    rt          j        |g          }|                    | j        rt'          t          dd          nd          5   ||||          } ||          }ddd           n# 1 swxY w Y   |                     |||           d{V r dS t+          t,          j        d          rt1                       n<#  |rt-          j                    d         |_        |                                  Y dS xY wdS )a%  Run a sequence of AST nodes. The execution mode depends on the
        interactivity parameter.

        Parameters
        ----------
        nodelist : list
          A sequence of AST nodes to run.
        cell_name : str
          Will be passed to the compiler as the filename of the cell. Typically
          the value returned by ip.compile.cache(cell).
        interactivity : str
          'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
          specifying which nodes should be run interactively (displaying output
          from expressions). 'last_expr' will run the last node interactively
          only if it is an expression (i.e. expressions in loops or other blocks
          are not displayed) 'last_expr_or_assign' will run the last expression
          or the last assignment. Other values for this parameter will raise a
          ValueError.

        compiler : callable
          A function with the same interface as the built-in compile(), to turn
          the AST nodes into code objects. Default is the built-in compile().
        result : ExecutionResult, optional
          An object to store exceptions that occur during execution.

        Returns
        -------
        True if an exception occurred while running code, False if it finished
        running.
        Nr	  r  rl   r   r  Fr  r  r  zInteractivity was %rc                 J    t           j        | j        z  t           j        k    }|S r   )inspectCO_COROUTINEco_flags)r  is_asyncs     r^   comparez/InteractiveShell.run_ast_nodes.<locals>.compare  s    "/$-?7CWWrb   r  singlePyCF_ALLOW_TOP_LEVEL_AWAITasync_T)r   _assign_nodesr9  Assignr   targets_single_targets_nodestargetNameExprr   Loadr:  r  ru   rk   r  extra_flagsr   r  run_coderx   rk  r  r  r  r   r  )r   r=  r)  r  r  r   asgrM  nnode_asyncto_run_execto_run_interactiverD  to_runr;  r  modr  asys                      r^   r&  zInteractiveShell.run_ast_nodes  s     L  	F 111(2,66 +rlc3:.. "3s{3C3Cq3H3H [^FF%:;; " ZFF!Ffch// +HSXfi%D%DEEE-e444OOE***'MK''(2,11 ' & &F"".6+KKf$$.6ssmXbcc]+KKe##.0(+KK3mCDDD.	     
 F# . .tVn----* 0 0tX.////$    
d6>> $,,CCX%%/4&11C))~GC!=sCCC  ( (
 $8CD99D!'$--C( ( ( ( ( ( ( ( ( ( ( ( ( ( ( tVC@@@@@@@@  44  Q'' 	  =+.<>>!+<(   44us7   B)J' ,IJ' I	J' I	"J' =)J' '6K rG  c                  K   d}t           j        | j        c}t           _        || _        d}	 	 |r"t          || j        | j                   d{V  nt          || j        | j                   |t           _        n# |t           _        w xY w	 d}n# t          $ r:}|||_        | 	                    d           t          dd           Y d}~nd}~wt          j        $ r# t          j                    \  }}	}
||	|_        Y n~| j        $ r: t          j                    \  }}	}
||	|_        |                     ||	|
           Y n< |t          j                    d         |_        | 	                    d	           Y nxY w|S )
a?  Execute a code object.

        When an exception occurs, self.showtraceback() is called to display a
        traceback.

        Parameters
        ----------
        code_obj : code object
          A compiled code object, to be executed
        result : ExecutionResult, optional
          An object to store exceptions that occur during execution.
        async_ :  Bool (Experimental)
          Attempt to run top-level asynchronous code in a default loop.

        Returns
        -------
        False : successful execution.
        True : an error occurred.
        __ipython_bottom__TNFr  z'To exit: use 'exit', 'quit', or Ctrl-D.rl   rr  r  )rk  r  r  r  r  r   r  r  r   r  r   bdbBdbQuitr  rH  r  )r   code_objr   rH  __tracebackhide__old_excepthookoutflagr|  r  r   r  s              r^   rR  zInteractiveShell.run_code4  s     , 1 *-& -	0 Fx)<dlKKKKKKKKKK4#6EEE "0////* GG)  	J 	J 	J!'($d333:qIIIIIIIII{ 	- 	- 	-"|~~E5"!',$% 	, 	, 	,"|~~E5"!',$MM%+++++	;!'*|~~a'8$T::::: s6   ?A: -B :BB 
E=0C2E=A E=7E=r  c                 N    | j                             |          \  }}|d|pdz  fS )a  Return whether a block of code is ready to execute, or should be continued

        Parameters
        ----------
        code : string
            Python input code, which can be multiline.

        Returns
        -------
        status : str
            One of 'complete', 'incomplete', or 'invalid' if source is not a
            prefix of valid code.
        indent : str
            When status is 'incomplete', this is some whitespace to insert on
            the next line of the prompt.
         r   )r  check_complete)r   r  r  nspacess       r^   re  zInteractiveShell.check_completev  s2    " 8GGMMsgl+++rb   active_eventloopc                      t          d          )Nz"Implement enable_gui in a subclass)NotImplementedError)r   guis     r^   
enable_guizInteractiveShell.enable_gui  s    !"FGGGrb   c                    ddl m}  |            s|dv rddl}ddlm } |                    || j                  \  }}|dk    rR| j        || _        nC|| j        k    r8t          d|d| j        d	           |                    | j                  \  }}|                    |           dd
lm}  || |           | 	                    |           |
                    | j                  | j        j        d         _        ||fS )a  Enable interactive matplotlib and inline figure support.

        This takes the following steps:

        1. select the appropriate eventloop and matplotlib backend
        2. set up matplotlib for interactive use with that backend
        3. configure formatters for inline figure display
        4. enable the selected gui eventloop

        Parameters
        ----------
        gui : optional, string
            If given, dictates the choice of matplotlib GUI backend to use
            (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
            'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
            matplotlib (as dictated by the matplotlib build-time options plus the
            user's matplotlibrc configuration file).  Note that not all backends
            make sense in all contexts, for example a terminal ipython can't
            display figures inline.
        rl   )_matplotlib_manages_backends)Nautor   N)
pylabtoolsz3Warning: Cannot change to a different GUI toolkit: z. Using z	 instead.)configure_inline_supportrT  )ro  rm   matplotlib_inline.backend_inlinerK  find_gui_and_backendpylab_gui_selectr  activate_matplotlibrp  rk  
mpl_runnerr  ri  registrydefault_runner)r   rj  rm  matplotlib_inlineptbackendrp  s          r^   enable_matplotlibz"InteractiveShell.enable_matplotlib  s`   * 	=<<<<<++-- 	4#2G2G 4333111111..sD4IJJW$;;$,(+%%---03T5J5J5JL M M M!66t7LMMW
w'''MMMMMM  w/// 	MM$,-- 	$%67F G|rb   c                 h    ddl m}                      |          \  }}i  ||           dh}t                                         j                                      |          } fd|D             } j                                        j                                       |||fS )a  Activate pylab support at runtime.

        This turns on support for matplotlib, preloads into the interactive
        namespace all of numpy and pylab, and configures IPython to correctly
        interact with the GUI event loop.  The GUI backend to be used can be
        optionally selected with the optional ``gui`` argument.

        This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.

        Parameters
        ----------
        gui : optional, string
            If given, dictates the choice of matplotlib GUI backend to use
            (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
            'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
            matplotlib (as dictated by the matplotlib build-time options plus the
            user's matplotlibrc configuration file).  Note that not all backends
            make sense in all contexts, for example a terminal ipython can't
            display figures inline.
        import_all : optional, bool, default: True
            Whether to do `from numpy import *` and `from pylab import *`
            in addition to module imports.
        r   )import_pylabr@  c                 >    g | ]}j         |         |         u|S rj   r   )r  r   rJ  r   s     r^   rT  z1InteractiveShell.enable_pylab.<locals>.<listcomp>  s.    SSStt|D/AD/Q/Qd/Q/Q/Qrb   )	IPython.core.pylabtoolsr}  r{  rb  intersectionr   
differencerP  r:  )	r   rj  
import_allr}  rz  ignoredboth	clobberedrJ  s	   `       @r^   enable_pylabzInteractiveShell.enable_pylab  s    0 	988888--c22W R$$$!"2ww##DL11<<WEESSSSStSSS	B""2&&&GY&&rb   c                    | j                                         }	 t          j        |dz             }|                    |j                   n# t          $ r Y nw xY w	 |                    |g |          }n# t          $ r Y nw xY w|S )a(  Expand python variables in a string.

        The depth argument indicates how many frames above the caller should
        be walked to look for the local namespace where to expand variables.

        The global namespace for expansion is always the user's interactive
        namespace.
        rl   )r   r   )	r   copyrk  r  rP  r  ru   vformatr  )r   rp  r  r  rJ  r;  s         r^   rs  zInteractiveShell.var_expand  s     \  	&M%'**E IIen%%%%  	 	 	 D		 ##Cb#<<CC 	 	 	D	 
s#   A 
AAA7 7
BBipython_edit_c                 x   t          t          j        |                    }| j                            |           t          j        d|t          |                    \  }}t          j        |           t          |          }| j	                            |           |r|
                    |d           |S )a  Make a new tempfile and return its filename.

        This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
        but it registers the created filename internally so ipython cleans it up
        at exit time.

        Optional inputs:

          - data(None): if data is given, it gets written out to the temp file
            immediately, and the file is closed again.)prefixz.py)dirr  r  )r   tempfilemkdtemprb  r  mkstempr   r  closera  
write_text)r   r  r  dir_pathhandler   	file_paths          r^   
mktempfilezInteractiveShell.mktempfile  s     (77788X&&&#+E6s8}}MMM
NN	i((( 	9   888rb   c                 6    | j         rdS t          |||          S r  )quietrH   )r   promptr   	interrupts       r^   rH   zInteractiveShell.ask_yes_no.  s#    : 	4&333rb   c                 V    t          j         t          j        j        j                   dS )zShow a usage messageN)r"   r  r  usageinteractive_usager   s    r^   
show_usagezInteractiveShell.show_usage3  s     	',$677777rb   c                     | j                             ||          }d                    d |D                       }|s$d|vrd}n|d|                    d                   }|S )ax  Return as a string a set of input history slices.

        Parameters
        ----------
        range_str : str
            The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
            since this function is for use by magic functions which get their
            arguments as strings. The number before the / is the session
            number: ~n goes n back from the current session.

            If empty string is given, returns history of current session
            without the last input.

        raw : bool, optional
            By default, the processed input is used.  If this is true, the raw
            input history is used instead.

        Notes
        -----
        Slices can be described with two notations:

        * ``N:M`` -> standard python form, means including items N...(M-1).
        * ``N-M`` -> include items N..M (closed endpoint).
        rawr   c              3   "   K   | ]
\  }}}|V  d S r   rj   )r  ru  xs      r^   r  z7InteractiveShell.extract_input_lines.<locals>.<genexpr>Q  s(      00wq!Q000000rb   r   N)rL  get_range_by_strr$  rfind)r   	range_strr  r4  r1  s        r^   extract_input_linesz$InteractiveShell.extract_input_lines7  s|    2 $55iS5IIyy00%00000  	04.djj.../rb   c                    |                      ||          }|r|S 	 |                    d          rt          j        ||          S nd# t          $ rW}|s=ddlm}  ||          }	|	                                                    d          cY d}~S t          d|z            |d}~ww xY w|g}
	 |

                    dt          |                     n# t          $ r Y nw xY w|
D ]}t          j                            |          r	 t          j        ||          c S # t          $ r_}|sEt#          |d	d
          5 }|                                cddd           cY d}~c S # 1 swxY w Y   t          d|z            |d}~ww xY wt          j                            t          j                            |                    rt          d|z            |r/|                     |d          }|d         r|d         r|d         S 	 t+          || j                  }n%# t.          $ r}t          d|z            |d}~ww xY wt1          |t2                    r|S t1          |t4                    r|j        S t9          d|z  |          )aV  Get a code string from history, file, url, or a string or macro.

        This is mainly used by magic functions.

        Parameters
        ----------
        target : str
            A string specifying code to retrieve. This will be tried respectively
            as: ranges of input history (see %history for syntax), url,
            corresponding .py file, filename, or an expression evaluating to a
            string or Macro in the user namespace.

            If empty string is given, returns complete history of current
            session, without the last line.

        raw : bool
            If true (default), retrieve raw history. Has no effect on the other
            retrieval mechanisms.

        py_only : bool (default False)
            Only try to fetch python code, do not try alternative methods to decode file
            if unicode fails.

        Returns
        -------
        A string of code.
        ValueError is raised if nothing is found, and TypeError if it evaluates
        to an object of another type. In each case, .args[0] is a printable
        message.
        r  )zhttp://zhttps://)skip_encoding_cookier   )urlopenlatin1Nz'%s' seem to be unreadable.rr  z('%s' is a directory, not a regular file.rl   )r  r  r  zI'%s' was not found in history, as a file, url, nor in the user namespace.z#%s is neither a string nor a macro.)r  re  rE   read_py_urlUnicodeDecodeErrorurllib.requestr  r  r  ru   r  rL   IOErrorr  r  isfileread_py_filer   isdirr  r  r  r   r  r   r   r:   r   rz   )r   rM  r  py_onlyr  	search_nsr  r|  r  responsepotential_targettgtr  r  codeobjs                  r^   find_user_codezInteractiveShell.find_user_code\  s   > ''C'88 	K		N  !899 ])&G[\\\\]! 	N 	N 	N 8222222"76??}}--h77777777;vEFFAM	N #8	##Aof&=&=>>>> 	 	 	D	 $ 
	V 
	VCw~~c"" 	VV!.sI]^^^^^^) V V V" ,$Sx@@@ ,A#$6688, , , , , , , , , , , , , , , , , , , , , , ,$&Cv%MNNTUU	V
 rw11#6677 V !Kf!TUUUV  	---f1-EEK7# -H(= -"8,,	O64<00GG 	O 	O 	O =@FG H HMNO	O gs## 	!N'' 	!= =F! ! 	!s   *A	 	
B*9B%B*B%%B*1#C 
C"!C"	D!!
F
+F?E'FF
'E++F.E+/FF
H$ $
I.IIc                     t          | dd          sFd| _        |                     d           | j        $| j                                         d| _        dS dS dS )z
        At exist operation that need to be called at most once.
        Second call to this function per instance will do nothing.
        _atexit_once_calledFT)rl  N)r  r  r]  rL  end_sessionr   s    r^   _atexit_oncezInteractiveShell._atexit_once  su     t2E:: 		,'+D$JJ5J))) #/$00222'+$$$		, 		, 0/rb   c                    |                                   | j        D ]A}	 |                                 | j                            |           2# t          $ r Y >w xY w| `| j        D ]A}	 t          j        |           | j                            |           2# t          $ r Y >w xY w| `t          | d          rJ| j	        dk    rAt          j                            d           t          j                                         dS dS dS )a  This will be executed at the time of exit.

        Cleanup operations and saving of persistent data that is done
        unconditionally by IPython should be performed here.

        For things that may depend on startup flags or platform specifics (such
        as having readline or not), register a separate atexit function in the
        code that has the appropriate information, rather than trying to
        clutter
        editing_modeviz[0 qN)r  ra  unlinkr8  FileNotFoundErrorrb  shutilrmtreerM  r  rk  r  r  ra  )r   tfiletdirs      r^   rC  z"InteractiveShell.atexit_operations  s>    	 ^ 	 	E%%e,,,,$   NM 	 	Dd###$$T****$   M 4(( 	T->$-F-FJZ(((J	 	-F-Fs#   .A
AA*.B
B&%B&c                 .    |                                   d S r   )r  r   s    r^   cleanupzInteractiveShell.cleanup  s    %%'''''rb   c                     d S r   rj   )r   r  s     r^   switch_doctest_modez$InteractiveShell.switch_doctest_mode  s    rb   )NNNNr  r   r   )r   NN)F)NN)TF)T)r   )r   rj   )NNNFFr  )r\  N)rl   )r\  )Tr   )FF)FFTN)FFTr  )Nr  )TFTF(  rf   rg   rh   ri   	_instancer   r   rb  r   r!   	Inspectorr	   tagr   r9  NodeTransformerr   autocallr   rT  r   rm   rn   rq   ro   r   r
   r   r   r   r   r   	automagicr  r   r?   r  r  r   r  debugr   r4   r  r   r-   r  r.   r  r*   r^  r  r_   r   r   r   r   r  exit_nowr(   r   r   r   r   rF  r  r   r  r  r  r  r  r  r'  r  r  r  history_lengthhistory_load_lengthr%  r  r   separate_inseparate_outseparate_out2wildcards_case_sensitiver   r  rf  r  r  r  r  r  rL  ri  r  r  r   rf  rs  r^  r_  r   r   setterrP  rR  rU  rX  r  r  r  r  r&  rp  rv  r(  r  r+  r-  r;  r.  r2  r4  r5  r6  r7  r8  staticmethodr   r  r   r"  r  r  r  r)  r   r*  r  r#  r%  r<  r+  r.  r(  r3  r8  r!  r  r9  r#  r,  rV  r]  r~  r  r  r  r   boolListTyper  r   r   AnyTyperU   r  r  r  r  r  r  r  r%  r+   r  r3  r  r  r  r  r  r  r  r  r
  r  rB   r  r1  r0  r9  r<  r9  	functoolswrapsr    rL  rc  re  rn  r  rt  r  r  r  r  r  r  r  rN   rM   r:  r=  r>  r'  r  r  r  r  r  r  r  r  r  r   r   r  r  r   r  r  r  r  r  r#  r_  r   r&  rR  runcodere  rg  rk  r{  r  rQ   rs  r  rH   r  r  r  r  rC  r  r  r   r   s   @r^   r   r   J  s        44INNN3x!!!!26$
3 3 3 
cc d3./    tG1		 	 	 
cc  d	   
cc	  T	   
cc	  #D)%d#$e,	 O #$Sb   
cc 
 W]L L L Xm   T	   
cc	  2   
cc	  gnJ  	cc  gbI  	cc  
 
 
 
cc  DKKOO4O((E !1dCCC[))-..T/**Nd!R  	cc  $u	   SS	  W"##E E $#E U	   SS	  W !!B B "!B NtE{{HXl##FWX" " " gajjOw*++H'"++///..K !))\)+!- !- A A XA %)D
*% % %T    tE	  
 
cc  gb	   
cc	 
 	  
 
cc   $tG1      	cc 
$u	   
cc	 
 48   
cc   47  	cc  DKKOO4O((EWU.  	cc  "'$	  
 
cc  "T"]"]"]0;(   
cc   D   
cc  "/$''++4+88K"?2&&**$*77L#OB''++4+88M#tDzz~~T~::O:?   
cc	 
 H>4PPPM 1d   8CDDL8CDDL 2t   hDQUVVVOh2t  O X@AAN(@TRRRK/ / X/ DFFM #tD/TUUU$H%T  \B  OS  T  T  T59+/#-I' I' I' I' I' I'V   X ^$    ^
   W]) ) )$ $ $ $  - - -
 
 
     8  * * * WR  	cc  Xh	 	 	 WX   4    / / / /0 0 0 04 4 4  
  : : :4 4 41 1 1
? 
? 
? $    \4;% ;% ;%B
U 
U 
U	\ 	\ 	\   X   P P P '% '% '% '%ZJ J J
; ; ;$ $ $L% % %2! ! !
  	* 	* 	* xmDFH HH0 0 0 0. #L L L L\ ) ) X)($ ($ ($ ($T2 2 2(:  :  : x C C XC>$ >$ >$ >$@,: ,: ,: ,:\$ $ $ $,.) .) .) .)`4 4 4* *3 *5x})<#= * * * \*Z QUx
 x
x
&.xc7l8K/L&Mx
	x
 x
 x
 x
t '& '& \'&R. .e . . . .   C        D	E 	E 	E 	EK K K K& & & &<8 8 8 $L5 5 5 52e+ e+ e+N< < <0           D7 7 7    FJBGJE JE JE JEX'c ' ' ' '/ / / /8      \!O !O !OF )C )C )C \)CV; ; ; ; ;$B B B B 3  3  3F Y_U(:;;
 
 
 <;

    65 5 5C 5 5 5 5n7 7 71 1 1fB B BB B BF F F F& & &0K K K.>( >( >(B F   B6 6 6: : :8 8 8@ @ @     2  $    >9 9 9
A A A 8=udi B0 B0 B0 B0 B0H8E 8E 8E 8EtF F F8 *&G$67 *& *& *& ^*&^ . . . .`:: : 	:
 : : 
: : : :z 26t(& (& (&(&	(& (& (& (&Z u +/59u u uu #3-u "*'!2u 
u u u up ?D5R 5R 5R 5Rn  <     L "y y4.y y y y yv=e = = = = =@ G,3 ,5c? , , , ,0 '+hsm***H H H H5 5 5 5n(' (' (' ('\ %&1B1B    :   24 4 4 4
8 8 8# # # #JQ! Q! Q! Q!f, , ,(     D( ( (
      rb   r   c                       e Zd ZdZdS )InteractiveShellABCz,An abstract base class for InteractiveShell.Nre   rj   rb   r^   r  r    s        6666rb   r  )	metaclass)ri   abcr9  rA  r]  builtinsr  r  r@  r  r  r  r  r  rk  r  r  r  r  r   
contextlibr   rD   r   r   loggingr   pathlibr   typingr   r	   r  r
   r  r   r   r   r   r   IPython.external.picklesharer   r   	traitletsr   r   r   r   r   r   r   r   r   r   r   traitlets.config.configurabler   traitlets.utils.importstringr   IPython.core.hooksr  rK  r    r!   r"   r#   r$   IPython.core.aliasr%   r&   IPython.core.autocallr(   IPython.core.builtin_trapr)   IPython.core.compileropr*   IPython.core.debuggerr+   IPython.core.display_trapr,   IPython.core.displayhookr-   IPython.core.displaypubr.   IPython.core.errorr/   r0   IPython.core.eventsr1   r2   IPython.core.extensionsr3   IPython.core.formattersr4   IPython.core.historyr5   r6   IPython.core.inputtransformer2r7   r8   IPython.core.loggerr9   IPython.core.macror:   IPython.core.payloadr;   IPython.core.prefilterr<   IPython.core.profiledirr=   IPython.core.tipsr>   IPython.core.usager?   IPython.displayr@   IPython.pathsrA   IPython.testing.skipdoctestrB   IPython.utilsrC   rE   rF   IPython.utils.decoratorsrG   IPython.utils.iorH   IPython.utils.ipstructrI   IPython.utils.pathrJ   rK   rL   IPython.utils.processrM   rN   IPython.utils.strdispatchrO   IPython.utils.syspathcontextrP   IPython.utils.textrQ   rR   rS   rT   IPython.core.oinspectrU   r   docrepr.sphinxifyrV   rZ   r  ru  rd   rk   	AugAssign	AnnAssignrJ  rI  rL  async_helpersrm   rn   ro   rp   rq   r_  	dedent_rer   rv   rx   r   r  r   r   r  r   r   r  r   r   r   r  r   r   ABCMetar  rB  rj   rb   r^   <module>r     s^      


 



  



          				 				       



              % % % % % %                         3 3 3 3 3 3 3 3 5 5 5 5 5 5 5 5 5 5 5 5       6 6 6 6 6 6 ' ' ' ' ' '                              @ ? ? ? ? ? 4 4 4 4 4 4     B B B B B B B B B B B B B B 2 2 2 2 2 2 2 2 . . . . . . 1 1 1 1 1 1 3 3 3 3 3 3 2 2 2 2 2 2 1 1 1 1 1 1 0 0 0 0 0 0 4 4 4 4 4 4 8 8 8 8 8 8 8 8 > > > > > > > > 4 4 4 4 4 4 4 4 4 4 4 4 > > > > > > > > @ @ @ @ @ @ @ @ & & & & & & $ $ $ $ $ $ / / / / / / 3 3 3 3 3 3 . . . . . . & & & & & & - - - - - - # # # # # # ) ) ) ) ) ) 4 4 4 4 4 4 ; ; ; ; ; ; ; ; ; ; ; ; * * * * * * ' ' ' ' ' ' ) ) ) ) ) ) O O O O O O O O O O 3 3 3 3 3 3 3 3 1 1 1 1 1 1 = = = = = = N N N N N N N N N N N N ' ' ' ' ' ' H   $$$$$$
# 
# 
# 
#    III	 	 	 	 	+ 	 	 	      sz:6               BJ788		) 	) 	) 	) 	)    	 	 	 $ # # # #9 # # #	A 	A 	A 	A 	Ag 	A 	A 	A
 
 
 
 
U- 
 
 
"4S> "d;Q6R " " " "J"
 "
 "
 "
 "
 "
 "
 "
JG G G G G G G G@ * * *a: a: a: a: a:, a: a: a:Hu7 7 7 7 7CK 7 7 7 7   - . . . . .s   	G GG