Format: application/x-python-code
⬇ Download File (20.2 KB)
   1  o
   2  
   3  ��h�Z�@s�dZddlmZddlZddlZddlmZddlZddlm	Z	ddl
   4  mZddlm
   5  Z
   6  mZddlmZdd	lmZmZmZmZdd
   7  lmZmZmZddlmZddlmZGd
   8  d�de�ZeGdd�de��Z eGdd�de ��Z!dS)z(Implementation of basic magic functions.�)�errorN)�pformat)�warn)�import_item)�magic_arguments�page)�
   9  UsageError)�Magics�magics_class�
  10  line_magic�
  11  magic_escapes)�
  12  format_screen�dedent�indent)�skip_doctest)�Structc@sFeZdZddd�Zdd�Zdd�Zdd	�Zd
  13  d�Zdd
  14  �Zdd�Z	dS)�
  15  MagicsDisplayNcCs|r|ng|_||_dS�N)�ignore�magics_manager)�selfrr�r�Oc:\Users\shubh\Videos\agent\nova\Lib\site-packages\IPython/core/magics/basic.py�__init__s
  16  zMagicsDisplay.__init__cs�td}td}�j}|��}d|d|�t�fdd�|d��D���dd|d|�t�fd	d�|d��D���d|��g}d
  17  �|�S)z'The main implementation of the %lsmagic�line�cellzAvailable line magics:z  c�g|]\}}|�jvr|�qSr�r��.0�m�v�rrr�
  18  <listcomp> �z*MagicsDisplay._lsmagic.<locals>.<listcomp>�zAvailable cell magics:crrrrr"rrr##r$�
  19  )rr�lsmagic�join�sorted�itemsZauto_status)rZmescZcesc�mman�magics�outrr"r�_lsmagics**�
  20  zMagicsDisplay._lsmagiccCs|�|���dSr)�textr.)r�p�cyclerrr�
  21  _repr_pretty_(szMagicsDisplay._repr_pretty_cC�|��Sr)�__str__r"rrr�__repr__+�zMagicsDisplay.__repr__cCr3r)r.r"rrrr4.r6zMagicsDisplay.__str__c
  22  
  23  Csti}|j}|��}|��D]*\}}i}|||<|��D]\}}z|jjj}	Wnty1d}	Ynw|	||<qq
  24  |S)z�turn magics dict into jsonable dict of the same structure
  25  
  26          replaces object instances with their class names as strings
  27          �Other)rr'r*�__self__�	__class__�__name__�AttributeError)
  28  rZ
  29  magic_dictr+r,�keyZsubdict�d�name�obj�	classnamerrr�	_jsonable1s�
  30  �zMagicsDisplay._jsonablecCr3r)rAr"rrr�_repr_json_Er6zMagicsDisplay._repr_json_r)
  31  r:�
  32  __module__�__qualname__rr.r2r5r4rArBrrrrrs
  33  rc@s8eZdZdZee��ejddddd�ejdddd	d�ejd
  34  dd�ejd
  35  dd�ejddddd�ed3dd���������Zed3dd��Z	d4dd�Z
  36  ed3dd��Zed3dd��Zed3d d!��Z
  37  ed3d"d#��Zed3d$d%��Zed&d'��Zed3d(d)��Zed3d*d+��Zeed3d,d-���Ze��ejd.ed/d0�ed1d2����ZdS)5�BasicMagicsz�Magics that provide central IPython functionality.
  38  
  39      These are various magics that don't fit into specific categories but that
  40      are all part of the base 'IPython experience'.z-lz--line�
  41  store_truezCreate a line magic alias.)�action�helpz-cz--cellzCreate a cell magic alias.r>z Name of the magic to be created.)rH�targetz(Name of the existing line or cell magic.z-pz--paramsNz(Parameters passed to the magic function.)�defaultrHr%cCs�t�|j|�}|j}|jj}d�t���}|j�	|�}|j
  42  �	|�}|j}|r@|�d�r0|�
  43  d�s:|�d�r@|�
  44  d�r@|dd�}|�|d�}	|�|d�}
  45  |jr]|	dur]td	td|f��|jrn|
  46  durntd
  47  td|f��|js�|js�|	s~|
  48  s~td|��t|	�|_t|
  49  �|_|dur�dnd|}|jr�|�||d|�td
  50  td|td||f�|jr�|�||d|�td
  51  td|td||f�dSdS)u�Create an alias for an existing line or cell magic.
  52  
  53          Examples
  54          --------
  55          ::
  56  
  57            In [1]: %alias_magic t timeit
  58            Created `%t` as an alias for `%timeit`.
  59            Created `%%t` as an alias for `%%timeit`.
  60  
  61            In [2]: %t -n1 pass
  62            107 ns ± 43.6 ns per loop (mean ± std. dev. of 7 runs, 1 loop each)
  63  
  64            In [3]: %%t -n1
  65               ...: pass
  66               ...:
  67            107 ns ± 58.3 ns per loop (mean ± std. dev. of 7 runs, 1 loop each)
  68  
  69            In [4]: %alias_magic --cell whereami pwd
  70            UsageError: Cell magic function `%%pwd` not found.
  71            In [5]: %alias_magic --line whereami pwd
  72            Created `%whereami` as an alias for `%pwd`.
  73  
  74            In [6]: %whereami
  75            Out[6]: '/home/testuser'
  76  
  77            In [7]: %alias_magic h history -p "-l 30" --line
  78            Created `%h` as an alias for `%history -l 30`.
  79          r%�"�'������rrNz%Line magic function `%s%s` not found.z%Cell magic function `%s%s` not found.z+No line or cell magic with name `%s` found.� z(Created `%s%s` as an alias for `%s%s%s`.)r�parse_argstring�alias_magic�shellrr(r�valuesrI�lstripr>�params�
  80  startswith�endswithZ
  81  find_magicrrr�boolZregister_alias�print)rr�argsrRr+ZescsrIr>rUZm_lineZm_cell�
  82  params_strrrrrQPs`6����
  83  �
  84  ��
  85  
  86  
  87  �
  88  ��zBasicMagics.alias_magiccCst|jjgd�S)z)List currently available magic functions.r)rrRr)r�parameter_srrrr'�szBasicMagics.lsmagicFcsf|jj}|j|dd�}|rd�nd�d��fdd�t|d���D��fd	d�t|d
  89  ���D��S)z'Return docstrings from magic functions.zNo documentation)�missingz**%s%s**::
  90  
  91  %s
  92  
  93  z	%s%s:
  94  %s
  95  r%c�*g|]\}}�td|tt|��f�qS)r�rrr�r�fnameZfndoc��
  96  format_stringrrr#��
  97  
  98  �
  99  
 100  �z+BasicMagics._magic_docs.<locals>.<listcomp>rcr^)rr_r`rbrrr#�rdr)rRrZlsmagic_docsr(r)r*)r�brief�restr+�docsrrbr�_magic_docs�s
 101  �
 102  ���zBasicMagics._magic_docscCs�d}z|��ddd�}Wn	tyYnw|dk}|dk}|�||�}|dkr3t|�|��dSt|�}d|d	td
 103  t|���g}t	�	d�
 104  |��dS)zmPrint information about the magic function system.
 105  
 106          Supported formats: -latex, -brief, -rest
 107          r%rrMNrerf�latexa�
 108  IPython's 'magic' functions
 109  ===========================
 110  
 111  The magic function system provides a series of functions which allow you to
 112  control the behavior of IPython itself, plus a lot of system-type
 113  features. There are two kinds of magics, line-oriented and cell-oriented.
 114  
 115  Line magics are prefixed with the % character and work much like OS
 116  command-line calls: they get as an argument the rest of the line, where
 117  arguments are passed without parentheses or quotes.  For example, this will
 118  time the given statement::
 119  
 120          %timeit range(1000)
 121  
 122  Cell magics are prefixed with a double %%, and they are functions that get as
 123  an argument not only the rest of the line, but also the lines below it in a
 124  separate argument.  These magics are called with two arguments: the rest of the
 125  call line and the body of the cell, consisting of the lines below the first.
 126  For example::
 127  
 128          %%timeit x = numpy.random.randn((100, 100))
 129          numpy.linalg.svd(x)
 130  
 131  will time the execution of the numpy svd routine, running the assignment of x
 132  as part of the setup phase, which is not timed.
 133  
 134  In a line-oriented client (the terminal or Qt console IPython), starting a new
 135  input with %% will automatically enter cell mode, and IPython will continue
 136  reading input until a blank line is given.  In the notebook, simply type the
 137  whole cell as one entity, but keep in mind that the %% escape can only be at
 138  the very start of the cell.
 139  
 140  NOTE: If you have 'automagic' enabled (via the command line option or with the
 141  %automagic function), you don't need to type in the % explicitly for line
 142  magics; cell magics always require an explicit '%%' escape.  By default,
 143  IPython ships with automagic on, so you should only rarely need the % escape.
 144  
 145  Example: typing '%cd mydir' (without the quotes) changes your working directory
 146  to 'mydir', if it exists.
 147  
 148  For a list of the available magic functions, use %lsmagic. For a description
 149  of any of them, type %magic_name?, e.g. '%cd?'.
 150  
 151  Currently the magic system has the following functions:z,Summary of magic functions (from %slsmagic):rr&)�split�
 152  IndexErrorrhrYZformat_latexr
 153  r�strr'rr()rr\�modererfZ
 154  magic_docsr-rrr�magic�s&�-
 155  
 156  �1zBasicMagics.magiccCsn|�|d�\}}d|v}|r|pd}|j�|�}|jr/|r#t|j�}nt|j�}t�|�dStd|�dS)z�Pretty print the object and display it through a pager.
 157  
 158          %page [options] OBJECT
 159  
 160          If no object is given, use _ (last output).
 161  
 162          Options:
 163  
 164            -r: page str(object), don't pretty-print it.�r�_zObject `%s` not foundN)	�
 165  parse_optionsrRZ_ofind�foundrlr?rrrY)rr\�optsrZ�rawZoname�info�txtrrrrs
 166  zBasicMagics.pagecCs6|jjjd}td|j�|_tdddg|j�dS)zToggle pretty printing on/off.�
 167  text/plainrMzPretty printing has been turned�OFF�ONN)rR�display_formatter�
 168  formattersrX�pprintrY)rr\�ptformatterrrrr|7s
 169  �zBasicMagics.pprintcCs�dd�}|��}|std��|j}z	||_|��Wn|d�Yz|jj|d�|jj|d�Wn|d�Y|jrSz	|j	�
 170  |�Wd	S|d�Yd	S|j	�
 171  d�d	S)
 172  a2Switch color scheme for prompts, info system and exception handlers.
 173  
 174          Currently implemented schemes: NoColor, Linux, LightBG.
 175  
 176          Color scheme names are not case-sensitive.
 177  
 178          Examples
 179          --------
 180          To get a plain black and white terminal::
 181  
 182            %colors nocolor
 183          cSs td|t��dfdd�dS)Nz#Error changing %s color schemes.
 184  %srM�)�
 185  stacklevel�r�sys�exc_info�r>rrr�color_switch_errMs
 186  �
 187  �z,BasicMagics.colors.<locals>.color_switch_errz8%colors: you must specify a color scheme. See '%colors?'rR)�scheme�	exceptionzobject inspectorZNoColorN)�striprrR�colorsZ
 188  refresh_style�
 189  InteractiveTBZ
 190  set_colorsZSyntaxTBZ
 191  color_infoZ	inspectorZset_active_scheme)rr\r��
 192  new_schemerRrrrr�?s.�
 193  
 194  zBasicMagics.colorscCs�dd�}|j}|��dkrd|j_dS|��dkrd|j_dS|����}z|jj|d�td	|jj�WdS|d
 195  �YdS)aJSwitch modes for the exception handlers.
 196  
 197          Valid modes: Plain, Context, Verbose, and Minimal.
 198  
 199          If called without arguments, acts as a toggle.
 200  
 201          When in verbose mode the value `--show` (and `--hide`)
 202          will respectively show (or hide) frames with ``__tracebackhide__ =
 203          True`` value set.
 204          cSstd|t��df�dS)Nz%Error changing %s exception modes.
 205  %srMr�r�rrr�xmode_switch_err}s
 206  �z+BasicMagics.xmode.<locals>.xmode_switch_errz--showFNz--hideT)rmzException reporting mode:�user)rRr�r�Zskip_hidden�
 207  capitalize�set_moderYrm)rr\r�rRZnew_moderrr�xmodeps
 208  zBasicMagics.xmodecCs*ddlm}||jdd�}t�|�dS)z Show a quick reference sheet r)�quick_referenceT)reN)ZIPython.core.usager�rhr)r�argr�Zqrrrr�quickref�szBasicMagics.quickrefc
 209  Cs"|j}|j}|jj}|jd}|�dt��}|j}|dd�}|d|j�|d|jj�|d|j	�|d|j
 210  �|d	|j�|d
 211  |j�|s\d|_d|_	d|_
 212  d|_dg|_|�
 213  dd�n|j|_|j|_	|j|_
 214  |j|_|j|_|�
 215  d|j�|�|�t|�|_d
 216  dg|j}	td|	�dS)a�Toggle doctest mode on and off.
 217  
 218          This mode is intended to make IPython behave as much as possible like a
 219          plain Python shell, from the perspective of how its prompts, exceptions
 220          and output look.  This makes it easy to copy and paste parts of a
 221          session into doctests.  It does so by:
 222  
 223          - Changing the prompts to the classic ``>>>`` ones.
 224          - Changing the exception reporting mode to 'Plain'.
 225          - Disabling pretty-printing of output.
 226  
 227          Note that IPython also supports the pasting of code snippets that have
 228          leading '>>>' and '...' prompts in them.  This means that you can paste
 229          doctests from files or docstrings (even if they have leading
 230          whitespace), and the code will execute correctly.  You can then use
 231          '%history -t' to see the translated history; this will give you the
 232          input after removal of all the leading prompts and whitespace, which
 233          can be pasted back into an editor.
 234  
 235          With these features, you can switch into this mode easily whenever you
 236          need to do testing and changes to doctests, without having to leave
 237          your existing IPython session.
 238          rw�doctest_modermF�	rc_pprintr��rc_separate_out�rc_separate_out2�rc_separate_in�rc_active_typesr%ZPlainrxryzDoctest mode is:N)rR�metarzr{�
 239  setdefaultrr|r�rmZseparate_outZ
 240  separate_out2Zseparate_inZactive_typesZrun_line_magicr�r�r�r�r�r�Zswitch_doctest_moderXrY)
 241  rr\rRr�Zdisp_formatterr}ZdstoreZsave_dstorermZ
 242  mode_labelrrrr��s<
 243  
 244  zBasicMagics.doctest_modec
 245  Cs^|�|d�\}}|dkrd}z|j�|�WSty.}z
 246  tt|��WYd}~dSd}~ww)akEnable or disable IPython GUI event loop integration.
 247  
 248          %gui [GUINAME]
 249  
 250          This magic replaces IPython's threaded shells that were activated
 251          using the (pylab/wthread/etc.) command line flags.  GUI toolkits
 252          can now be enabled at runtime and keyboard
 253          interrupts should work without any problems.  The following toolkits
 254          are supported:  wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
 255  
 256              %gui wx      # enable wxPython event loop integration
 257              %gui qt      # enable PyQt/PySide event loop integration
 258                           # with the latest version available.
 259              %gui qt6     # enable PyQt6/PySide6 event loop integration
 260              %gui qt5     # enable PyQt5/PySide2 event loop integration
 261              %gui gtk     # enable PyGTK event loop integration
 262              %gui gtk3    # enable Gtk3 event loop integration
 263              %gui gtk4    # enable Gtk4 event loop integration
 264              %gui tk      # enable Tk event loop integration
 265              %gui osx     # enable Cocoa event loop integration
 266                           # (requires %matplotlib 1.1)
 267              %gui         # disable all event loop integration
 268  
 269          WARNING:  after any of these has been called you can simply create
 270          an application object, but DO NOT start the event loop yourself, as
 271          we have already handled that.
 272          r%N)rqrRZ
 273  enable_gui�	Exceptionrrl)rr\rsr��errr�gui�s��zBasicMagics.guicCs|jjjd}||_|jS)aiSet floating point precision for pretty printing.
 274  
 275          Can set either integer precision or a format string.
 276  
 277          If numpy has been imported and precision is an int,
 278          numpy display precision will also be set, via ``numpy.set_printoptions``.
 279  
 280          If no argument is given, defaults will be restored.
 281  
 282          Examples
 283          --------
 284          ::
 285  
 286              In [1]: from math import pi
 287  
 288              In [2]: %precision 3
 289              Out[2]: '%.3f'
 290  
 291              In [3]: pi
 292              Out[3]: 3.142
 293  
 294              In [4]: %precision %i
 295              Out[4]: '%i'
 296  
 297              In [5]: pi
 298              Out[5]: 3
 299  
 300              In [6]: %precision %e
 301              Out[6]: '%e'
 302  
 303              In [7]: pi**10
 304              Out[7]: 9.364805e+04
 305  
 306              In [8]: %precision
 307              Out[8]: '%r'
 308  
 309              In [9]: pi**10
 310              Out[9]: 93648.047476082982
 311          rw)rRrzr{Zfloat_precisionZfloat_format)r�sr}rrr�	precisions*zBasicMagics.precision�filenamezNotebook name or filename)�typerHc
 312  Cs�t�|j|�}tj�|j�}ddlm}m	}g}t
 313  |jj�
 314  ��}t|�dkr*td��|dd�D]\}}	}
 315  |�|j|	|
 316  d��q0|j|d�}tj|d	d
 317  d��}|||dd
 318  �Wd�dS1sawYdS)z�Export and convert IPython notebooks.
 319  
 320          This function can export the current IPython history to a notebook file.
 321          For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
 322          r)�write�v4rMzHistory is empty, cannot exportNrN)�execution_count�source)�cells�wzutf-8)�encoding�)�version)rrP�notebook�os�path�
 323  expanduserr�Znbformatr�r��listrRZhistory_managerZ	get_range�len�
 324  ValueError�appendZ
 325  new_code_cellZnew_notebook�io�open)
 326  rr�rZZoutfnamer�r�r��hist�sessionr�r��nb�frrrr�:s 
 327  �"�zBasicMagics.notebook)r%)FF)r:rCrD�__doc__rrZargumentrrQr'rhrnrr|r�r�r�r�r�r�rlr�rrrrrEIsn�����O
 328  J0
 329  N%,�rEc@seZdZedd��ZdS)�AsyncMagicscCs�|��}ddd�}|std�||jj|jj��dS|��dvr'd|j_dS|��dvr3d	|j_dS||jjvrG|jj|\|j_|j_dS||jjvr[|jj||j_d	|j_dSt	|�}||j_d	|j_dS)
 330  aV
 331          Allow to change the status of the autoawait option.
 332  
 333          This allow you to set a specific asynchronous code runner.
 334  
 335          If no value is passed, print the currently used asynchronous integration
 336          and whether it is activated.
 337  
 338          It can take a number of value evaluated in the following order:
 339  
 340          - False/false/off deactivate autoawait integration
 341          - True/true/on activate autoawait integration using configured default
 342            loop
 343          - asyncio/curio/trio activate autoawait integration and use integration
 344            with said library.
 345  
 346          - `sync` turn on the pseudo-sync integration (mostly used for
 347            `IPython.embed()` which does not run IPython with a real eventloop and
 348            deactivate running asynchronous code. Turning on Asynchronous code with
 349            the pseudo sync loop is undefined behavior and may lead IPython to crash.
 350  
 351          If the passed parameter does not match any of the above and is a python
 352          identifier, get said object from user namespace and set it as the
 353          runner, and activate autoawait.
 354  
 355          If the object is a fully qualified object name, attempt to import it and
 356          set it as the runner, and activate autoawait.
 357  
 358          The exact behavior of autoawait is experimental and subject to change
 359          across version of IPython and Python.
 360          �on�off)TFz.IPython autoawait is `{}`, and set to use `{}`N)�falser�F)�truer�T)
 361  r�rY�formatrR�	autoawaitZloop_runner�lowerZloop_runner_mapZuser_nsr)rr\�paramr=�runnerrrrr�[s0"
 362  
 363  �zAsyncMagics.autoawaitN)r:rCrDrr�rrrrr�Xsr�)"r��loggingrr�r�r|rr��warningsrZtraitlets.utils.importstringrZIPython.corerrZIPython.core.errorrZIPython.core.magicr	r
 364  rrZIPython.utils.textr
 365  rrZIPython.testing.skipdoctestrZIPython.utils.ipstructr�objectrrEr�rrrr�<module>s.5