Format: application/x-python-code
⬇ Download File (21.0 KB)
   1  o
   2  
   3  ��h�m�@shdZddlZddlZddlZddlZddlZddlZddlmZddl	m
   4  Z
   5  mZddlm
   6  Z
   7  ddlmZddlmZmZmZddlmZdd	lmZmZmZdd
   8  lmZmZddlmZddlm Z dd
   9  l!m"Z"ddl#m$Z$ddl%m&Z&ddl'm(Z(ddl)m*Z*Gdd�de+�Z,e�-d�Z.e�-dej/�Z0dd�Z1dd�Z2dd�Z3Gdd�de4�Z5eGdd�de��Z6dS) z3Implementation of code management magic functions.
  10  �N)�chain)�Request�urlopen)�	urlencode)�Path)�TryNext�StdinNotImplementedError�
  11  UsageError)�Macro)�Magics�magics_class�
  12  line_magic)�	find_file�find_source_lines)�version)�skip_doctest)�
  13  preserve_keys)�get_py_filename)�warn)�error)�
  14  get_text_listc@�eZdZdS)�MacroToEditN��__name__�
  15  __module__�__qualname__�rr�Nc:\Users\shubh\Videos\agent\nova\Lib\site-packages\IPython/core/magics/code.pyr-�rz!<ipython\-input\-(\d+)-[a-z\d]+>$z3
  16  (?P<start>\d+)?
  17  ((?P<sep>[\-:])
  18   (?P<end>\d+)?)?
  19  $ccs��|��D]X}t�|�}|sq|�d�}|�d�}|�d�}|dkr5|r*t|�dnd}|r2t|�nd}n#|dkrN|rAt|�dnd}|rKt|�dnd}n
  20  t|�}t|�d}||fVqdS)z�Turn a string of range for %%load into 2-tuples of (start, stop)
  21      ready to use as a slice of the content split by lines.
  22  
  23      Examples
  24      --------
  25      list(extract_input_ranges("5-10 2"))
  26      [(4, 10), (1, 2)]
  27      �sep�start�end�-�N�:)�split�range_re�match�group�int)Z
  28  ranges_strZ	range_strZrmatchr r!r"rrr�extract_code_ranges9s$�	
  29  
  30  
  31  
  32  �r+cCs�|�d�}t�|�}dd�|jD�}|�d�}i}t|�}t|�D]&\}}||d��s9|d8}||d��r-|rC|d|f||<|d}q!g}g}	|D] }
  33  |
  34  |vri||
  35  \}}|�d�|||��d�qN|	�|
  36  �qN||	fS)a�
  37      Return a tuple  (blocks, not_found)
  38      where ``blocks`` is a list of code fragments
  39      for each symbol parsed from code, and ``not_found`` are
  40      symbols not found in the code.
  41  
  42      For example::
  43  
  44          In [1]: code = '''a = 10
  45             ...: def b(): return 42
  46             ...: class A: pass'''
  47  
  48          In [2]: extract_symbols(code, 'A,b,z')
  49          Out[2]: (['class A: pass\n', 'def b(): return 42\n'], ['z'])
  50      �,cSsg|]}t|dd�|jf�qS)�nameN)�getattr�lineno)�.0�srrr�
  51  <listcomp>ksz#extract_symbols.<locals>.<listcomp>�
  52  r$)	r&�ast�parse�body�len�reversed�strip�append�join)�code�symbolsZpy_codeZmarksZ
  53  symbols_linesr"r-r!�blocks�	not_found�symbolrrr�extract_symbolsVs*
  54  
  55  
  56  �
  57  rAccs��t�d�}t|�}t|�}|�|�}|rH|��}|t|�d�V|D]"}|�|�r5|t|�d�Vq$|dvs?t|�dkrC|Vq$|Vn|V|D]}|VqMdS)z}For %load, strip indent from lines until finding an unindented line.
  58  
  59      https://github.com/ipython/ipython/issues/9775
  60      z\s+N)r3z
  61  r)�re�compile�iter�nextr(r)r7�
  62  startswith)�linesZ	indent_re�it�
  63  first_lineZindent_match�indent�linerrr�strip_initial_indent�s(�
  64  
  65  
  66  ��rLc@seZdZdZdd�ZdS)�InteractivelyDefinedz:Exception for interactively defined variable in magic_editcCs
  67  ||_dS�N)�index)�selfrOrrr�__init__�s
  68  zInteractivelyDefined.__init__N)rrr�__doc__rQrrrrrM�srMcs�eZdZdZ�fdd�Zeddd��Zeddd��Zed	d
  69  ��Zedd��Z	e
  70  d
  71  d��Zdd�Ze
  72  edddgfdd���Z�ZS)�
  73  CodeMagicszBMagics related to code management (loading, saving, editing, ...).cs"t�|_tt|�j|i|��dSrN)�set�_knowntemps�superrSrQ)rP�args�kwargs��	__class__rrrQ�szCodeMagics.__init__�c
  74  Cs�|j|ddd�\}}|std��d|v}d|v}d|v}|r dnd}|r&d	nd
  75  }|dd�|d
  76  d��}	}
  77  |	�d�s?|	|7}	tj�|	�}	tj�|	�}|rx|sx|sxz|jj	d|	dd�}Wnt
  78  yotd|	|f�YdSw|sxtd�dSz	|j�|
  79  |�}
  80  Wnt
  81  tfy�}zt|jd�WYd}~dSd}~wwtj|	|dd�� }|r�|s�|�d�|�|
  82  �|
  83  �d�s�|�d�Wd�n1s�wYtd|	�t|
  84  �dS)aSave a set of lines or a macro to a given filename.
  85  
  86          Usage:\
  87            %save [options] filename [history]
  88  
  89          Options:
  90  
  91            -r: use 'raw' input.  By default, the 'processed' history is used,
  92            so that magics are loaded in their transformed version to valid
  93            Python.  If this option is given, the raw input as typed as the
  94            command line is used instead.
  95            
  96            -f: force overwrite.  If file exists, %save will prompt for overwrite
  97            unless -f is given.
  98  
  99            -a: append to the file instead of overwriting it.
 100  
 101          The history argument uses the same syntax as %history for input ranges,
 102          then saves the lines to the filename you specify.
 103  
 104          If no ranges are specified, saves history of the current session up to
 105          this point.
 106  
 107          It adds a '.py' extension to the file if you don't do so yourself, and
 108          it asks for confirmation before overwriting existing files.
 109  
 110          If `-r` option is used, the default extension is `.ipy`.
 111          Zfra�list)�modezMissing filename.�r�f�a�w�.ipy�.pyr� r$N)rcrbz%File `%s` exists. Overwrite (y/[N])? �n��defaultz7File `%s` exists. Use `%%save -f %s` to force overwrite�Operation cancelled.�utf-8��encodingz# coding: utf-8
 112  r3z1The following commands were written to file `%s`:)�
 113  parse_optionsr	r;�endswith�os�path�
 114  expanduser�isfile�shell�
 115  ask_yes_nor�print�find_user_code�	TypeError�
 116  ValueErrorrW�io�open�write)rP�parameter_s�optsrW�raw�forcer:r]�ext�fnameZcodefromZfile_exists�	overwriteZcmds�er_rrr�save�sP
 117  ���
 118  
 119  
 120  
 121  ��zCodeMagics.savec
 122  
 123  Cs|�|d�\}}z|j�|�}Wnttfy,}zt|jd�WYd}~dSd}~wwd}z
 124  t|�dd��}WntyU}zt|jd�	��WYd}~dSd}~ww|dks^|dkrdtd�dSt
 125  |�d	d
 126  �d||d���d
 127  �}tddd�
 128  t�id�}t||�}	|	j�d�S)a+Upload code to dpaste.com, returning the URL.
 129  
 130          Usage:\
 131            %pastebin [-d "Custom description"][-e 24] 1-7
 132  
 133          The argument can be an input history range, a filename, or the name of a
 134          string or macro.
 135  
 136          If no arguments are given, uploads the history of this session up to
 137          this point.
 138  
 139          Options:
 140  
 141            -d: Pass a custom description. The default will say
 142                "Pasted from IPython".
 143            -e: Pass number of days for the link to be expired.
 144                The default will be 7 days.
 145          zd:e:rN�r�r$imz*Expiry days should be in range of 1 to 365�dzPasted from IPython�python)�title�syntax�content�expiry_daysrizhttps://dpaste.com/api/v2/z
 146  User-AgentzIPython v{})�headersZLocation)rlrrrurwrvrtrWr*�get�
 147  capitalizer�encoder�formatrrr�)
 148  rPr{r|rWr<r�r�Z	post_data�request�responserrr�pastebin�sD����
 149  ���	�
 150  zCodeMagics.pastebincCs|�|�dS)z�Alias of `%load`
 151  
 152          `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
 153          extension. So it has been renamed simply into %load. You can look at
 154          `%load`'s docstring for more info.
 155          N)�load)rP�arg_srrr�loadpy3szCodeMagics.loadpycsz|�|d�\}}d|v}|jj||d�}d|vrVzt||d�\}}Wnty1td�YdSwt|�dkrAtd|d	�nt|�dkrQtd
 156  t|dd��d
 157  �	|�}d|vr~|d�
 158  dd�}|�d
 159  ��t|�}	�fdd�|	D�}d
 160  �	t
 161  t�|���}t|�}
 162  |
 163  dkr�d|vr�z|jjd|
 164  dd�}Wnty�d}Ynw|dur�td�dSd�|�|}|jj|dd�dS)a�Load code into the current frontend.
 165  
 166          Usage:\
 167            %load [options] source
 168  
 169            where source can be a filename, URL, input history range, macro, or
 170            element in the user namespace
 171  
 172          If no arguments are given, loads the history of this session up to this
 173          point.
 174  
 175          Options:
 176  
 177            -r <lines>: Specify lines or ranges of lines to load from the source.
 178            Ranges could be specified as x-y (x..y) or in python-style x:y 
 179            (x..(y-1)). Both limits x and y can be left blank (meaning the 
 180            beginning and end of the file, respectively).
 181  
 182            -s <symbols>: Specify function or classes to load from python source. 
 183  
 184            -y : Don't ask confirmation for loading source above 200 000 characters.
 185  
 186            -n : Include the user's namespace when searching for source code.
 187  
 188          This magic command can either take a local filename, a URL, an history
 189          range (see %history) or a macro as argument, it will prompt for
 190          confirmation before loading source with more than 200 000 characters, unless
 191          -y flag is passed or if the frontend does not support raw_input::
 192  
 193          %load
 194          %load myscript.py
 195          %load 7-27
 196          %load myMacro
 197          %load http://www.example.com/myscript.py
 198          %load -r 5-10 myscript.py
 199          %load -r 10-20,30,40: foo.py
 200          %load -s MyClass,wonder_function myscript.py
 201          %load -n MyClass
 202          %load -n my_module.wonder_function
 203          zyns:r:re)�	search_nsr1z.Unable to parse the input as valid Python codeNr$zThe symbol `%s` was not foundrzThe symbols %s were not found�`)Zwrap_item_withr3r^r,rdcsg|]}�t|��qSr)�slice)r0Zslc�rGrrr2�sz#CodeMagics.load.<locals>.<listcomp>i@
 204  �yzSThe text you're trying to load seems pretty big (%d characters). Continue (y/[N]) ?rfTFrhz# %load {}
 205  )�replace)rlrrrurA�SyntaxErrorrr7rrr;r�r&r+rLr�
 206  from_iterablersrrtr�Zset_next_input)rPr�r|rWr��contentsr>r?�rangesZslices�lZansrr�rr�=sN*�
 207  �
 208  
 209  �
 210  ��zCodeMagics.loadc
 211  s�dd�}d|v}d|v}Gdd�dt�}|�dd�}|r+d	|d
 212  }||jvr+|d}d}	d
 213  �||�}
 214  |
 215  r8d}	n�|�r|�||����szt||j��t�t�sR|�Wn�ttfyq||�}
 216  |
 217  durmt	d|�YdSd}	Yn�|�y}z�t�t
 218  �r�t��|�t��}
 219  |
 220  r�d|
 221  �
 222  �vr�t���r��fdd�t��D�}|D]}
 223  t�|
 224  �s�q�t|
 225  �}
 226  |
 227  r�d|
 228  �
 229  �vr�|
 230  �nq�t�tj�|
 231  ��}|r�tt|��d
 232  ��|�d}|
 233  dur�||�}
 234  d}|
 235  dur�t	d||
 236  f�|�r|dur�t��}|du�r||�}
 237  |
 238  du�rt	d��WYd}~dSd}	WYd}~nd}~ww|	�r(|���}
 239  td|
 240  �z|jj|d
 241  <|�s6||d<WnY|
 242  ||	fS)z7Utility method used by magic_edit to find what to edit.cSs<zt|�}W|Sty|�d�r|}Y|Sd}Y|Sw)z#Make a filename from the given argsrcN)r�IOErrorrm)�arg�filenamerrr�
 243  make_filename�s
 244  �
 245  ��z3CodeMagics._find_edit_target.<locals>.make_filename�pr^c@r)z2CodeMagics._find_edit_target.<locals>.DataIsObjectNrrrrr�DataIsObject�rr�reNz_%srr$Tr[FzBArgument given (%s) can't be found as a variable or as a filename.)NNNZ
 246  fakemodulecsg|]}t�|��qSr)r.)r0Zaname��datarrr2�sz0CodeMagics._find_edit_target.<locals>.<listcomp>zDCould not find file where `%s` is defined.
 247  Opening a file named `%s`z8The file where `%s` was defined cannot be read or found.z)IPython will make a temporary file named:)�	Exceptionr��user_nsZextract_input_lines�eval�
 248  isinstance�str�	NameErrorr�rr
 249  rr�lower�inspect�isclass�dir�ismethod�ipython_input_patr(rnro�basenamerMr*�groupsr�
 250  mktempfilert�displayhookZprompt_count)rrrWr|�	last_callr�Z	opts_prevZopts_rawr�r/Zuse_tempr�r��attrs�attr�mZdatafilerr�r�_find_edit_target�s�
 251  
 252  ��
 253  
 254  �
 255  ��
 256  
 257  ���2
 258  
 259  �
 260  zCodeMagics._find_edit_targetcCs@|j�|j�}|jj�|�t|�jdd�}t|�|jj|<dS)z,open an editor with the macro data in a filerirjN)	rrr��value�hooks�editorr�	read_textr
 261  r�)rPZmname�macror�Zmvaluerrr�_edit_macroszCodeMagics._edit_macroc
 262  
 263  Csz|�|d�\}}z|�|j|||�\}}}WnEty2}z|�||jd�WYd}~dSd}~wty[}ztd|j�t	|j�}|�|j|||�\}}}WYd}~nd}~ww|durbdS|rk|j
 264  �|�n||j
 265  vrrd}tddd�tj
 266  ��t|�}	zt	|	���}
 267  }d|
 268  vr�d	|
 269  }
 270  |jj�|
 271  |�Wnty�td
 272  �YdSw|��dkr�|	jdd
 273  �|jjd<d|vr�t�nBtd�t|jjd��/|s�||jjd<d|vr�|	jdd
 274  �}|jj|dd�n|j�||jj|jj�Wd�n1s�wY|�r;z|	jdd
 275  �WSt�y:}zt|j�|	k�r*td�WYd}~dS|j��WYd}~dSd}~wwdS)a�Bring up an editor and execute the resulting code.
 276  
 277          Usage:
 278            %edit [options] [args]
 279  
 280          %edit runs IPython's editor hook. The default version of this hook is
 281          set to call the editor specified by your $EDITOR environment variable.
 282          If this isn't found, it will default to vi under Linux/Unix and to
 283          notepad under Windows. See the end of this docstring for how to change
 284          the editor hook.
 285  
 286          You can also set the value of this editor via the
 287          ``TerminalInteractiveShell.editor`` option in your configuration file.
 288          This is useful if you wish to use a different editor from your typical
 289          default with IPython (and for Windows users who typically don't set
 290          environment variables).
 291  
 292          This command allows you to conveniently edit multi-line code right in
 293          your IPython session.
 294  
 295          If called without arguments, %edit opens up an empty editor with a
 296          temporary file and will execute the contents of this file when you
 297          close it (don't forget to save it!).
 298  
 299  
 300          Options:
 301  
 302          -n <number>: open the editor at a specified line number.  By default,
 303          the IPython editor hook uses the unix syntax 'editor +N filename', but
 304          you can configure this by providing your own modified hook if your
 305          favorite editor supports line-number specifications with a different
 306          syntax.
 307  
 308          -p: this will call the editor with the same data as the previous time
 309          it was used, regardless of how long ago (in your current session) it
 310          was.
 311  
 312          -r: use 'raw' input.  This option only applies to input taken from the
 313          user's history.  By default, the 'processed' history is used, so that
 314          magics are loaded in their transformed version to valid Python.  If
 315          this option is given, the raw input as typed as the command line is
 316          used instead.  When you exit the editor, it will be executed by
 317          IPython's own processor.
 318  
 319          -x: do not execute the edited code immediately upon exit. This is
 320          mainly useful if you are editing programs which need to be called with
 321          command line arguments, which you can then do using %run.
 322  
 323  
 324          Arguments:
 325  
 326          If arguments are given, the following possibilities exist:
 327  
 328          - If the argument is a filename, IPython will load that into the
 329            editor. It will execute its contents with execfile() when you exit,
 330            loading any code in the file into your interactive namespace.
 331  
 332          - The arguments are ranges of input history,  e.g. "7 ~1/4-6".
 333            The syntax is the same as in the %history magic.
 334  
 335          - If the argument is a string variable, its contents are loaded
 336            into the editor. You can thus edit any string which contains
 337            python code (including the result of previous edits).
 338  
 339          - If the argument is the name of an object (other than a string),
 340            IPython will try to locate the file where it was defined and open the
 341            editor at the point where it is defined. You can use `%edit function`
 342            to load an editor exactly at the point where 'function' is defined,
 343            edit it and have the file be executed automatically.
 344  
 345          - If the object is a macro (see %macro for details), this opens up your
 346            specified editor with a temporary file containing the macro's data.
 347            Upon exit, the macro is reloaded with the contents of the file.
 348  
 349          Note: opening at an exact line is only supported under Unix, and some
 350          editors (like kedit and gedit up to Gnome 2.8) do not understand the
 351          '+NUMBER' parameter necessary for this feature. Good editors like
 352          (X)Emacs, vi, jed, pico and joe all do.
 353  
 354          After executing your code, %edit will return as output the code you
 355          typed in the editor (except when it was an existing file). This way
 356          you can reload the code in further invocations of %edit as a variable,
 357          via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
 358          the output.
 359  
 360          Note that %edit is also available through the alias %ed.
 361  
 362          This is an example of creating a simple function inside the editor and
 363          then modifying it. First, start up the editor::
 364  
 365            In [1]: edit
 366            Editing... done. Executing edited code...
 367            Out[1]: 'def foo():\n    print("foo() was defined in an editing
 368            session")\n'
 369  
 370          We can then call the function foo()::
 371  
 372            In [2]: foo()
 373            foo() was defined in an editing session
 374  
 375          Now we edit foo.  IPython automatically loads the editor with the
 376          (temporary) file where foo() was previously defined::
 377  
 378            In [3]: edit foo
 379            Editing... done. Executing edited code...
 380  
 381          And if we call foo() again we get the modified version::
 382  
 383            In [4]: foo()
 384            foo() has now been changed!
 385  
 386          Here is an example of how to edit a code snippet successive
 387          times. First we call the editor::
 388  
 389            In [5]: edit
 390            Editing... done. Executing edited code...
 391            hello
 392            Out[5]: "print('hello')\n"
 393  
 394          Now we call it again with the previous output (stored in _)::
 395  
 396            In [6]: edit _
 397            Editing... done. Executing edited code...
 398            hello world
 399            Out[6]: "print('hello world')\n"
 400  
 401          Now we call it with the output #8 (stored in _8, also as Out[8])::
 402  
 403            In [7]: edit _8
 404            Editing... done. Executing edited code...
 405            hello again
 406            Out[7]: "print('hello again')\n"
 407  
 408  
 409          Changing the default editor hook:
 410  
 411          If you wish to write your own editor hook, you can put it in a
 412          configuration file which you load at startup time.  The default hook
 413          is defined in the IPython.core.hooks module, and you can use that as a
 414          starting example for further modifications.  That file also has
 415          general instructions on how to set a new hook for use once you've
 416          defined it.zprxn:rNzEditing In[%i]Tz
 417  Editing...rd)r"z'%s'zCould not open editorZpasted_blockrirj�xzdone. Executing edited code...�__file__r^F)Z
 418  store_historyz'File not found. Did you forget to save?)rlr�rrrr�rWrMrtrOr�rU�add�sys�stdout�flushr�absoluter�r�rrr9r�r�rZrun_cellZ
 419  safe_execfiler�r��
 420  showtraceback)
 421  rPr{r�r|rWr�r/Zis_tempr��filepath�quoted�source�msgrrr�edit"s~��
 422  ���
 423  
 424  ����
 425  ���zCodeMagics.edit)r[)rrrrRrQr
 426  r�r�r�r��staticmethodr�r�rr��
 427  __classcell__rrrYrrS�s$C5
 428  	
 429  Y
 430  	rS)7rRr�rxrnrBr�r4�	itertoolsr�urllib.requestrr�urllib.parser�pathlibrZIPython.core.errorrrr	ZIPython.core.macror
 431  ZIPython.core.magicrrr
 432  ZIPython.core.oinspectrrZIPython.core.releaserZIPython.testing.skipdoctestrZIPython.utils.contextsrZIPython.utils.pathr�warningsr�loggingrZIPython.utils.textrrwrrCr��VERBOSEr'r+rArLr�rMrSrrrr�<module>sB
 433  �4!