Format: application/x-python-code
⬇ Download File (46.4 KB)
   1  o
   2  
   3  ��h���@s2dZddlZddlZddlZddlZddlZddlZddl	Z	ddl
   4  Z
   5  ddlZddlZddl
   6  Z
   7  ddlZddlZddlZddlZddlmZmZddlmZmZmZmZmZmZmZmZmZmZddlm Z ddl!m"Z"ddl#m$Z$ddl%m&Z&dd	l'm(Z(m)Z)dd
   8  l*m+Z+ddl,m-Z-m.Z.m/Z/ddl0m1Z1dd
   9  l2m3Z3ddl4m5Z5ddl6m7Z7m8Z8m9Z9m:Z:m;Z;m<Z<m=Z=m>Z>m?Z?ddl@mAZAddlBmCZCddlDmEZEddlFmGZGddlHmIZIddlJmKZKmLZLddlMmNZNmOZOddlPmQZQGdd�deR�ZSGdd�dej�ZTGdd�dejU�ZUe;Gdd�de7��ZVd d!�ZWd%d#d$�ZXdS)&z4Implementation of execution-related magic functions.�N)�Dict�Any)
  10  �Assign�Call�Expr�Load�Module�Name�NodeTransformer�Store�parse�unparse)�StringIO)�error)�Path)�Restart)�dedent�indent)�warn)�magic_arguments�oinspect�page)�DisplayHook)�
  11  UsageError)�Macro)	�Magics�
  12  cell_magic�line_cell_magic�
  13  line_magic�magics_class�needs_local_scope�
  14  no_var_expand�on_off�output_can_be_silenced)�skip_doctest)�capture_output)�
  15  preserve_keys)�Struct)�find_mod)�get_py_filename�	shellglob)�clock�clock2)�ReplaceCodeTransformerc@s@eZdZdZdd�Zedd��Zedd��Zdd	�Zd
  16  d�Z	dS)
  17  �TimeitResulta�
  18      Object returned by the timeit magic with info about the run.
  19  
  20      Contains the following attributes :
  21  
  22      loops: (int) number of loops done per measurement
  23      repeat: (int) number of times the measurement has been repeated
  24      best: (float) best execution time / number
  25      all_runs: (list of float) execution time of each run (in s)
  26      compile_time: (float) time of statement compilation (s)
  27  
  28      csB|�_|�_|�_|�_|�_|�_|�_�fdd�|D��_dS)Ncsg|]}|�j�qS�)�loops)�.0�dt��selfr/�Sc:\Users\shubh\Videos\agent\nova\Lib\site-packages\IPython/core/magics/execution.py�
  29  <listcomp>]sz)TimeitResult.__init__.<locals>.<listcomp>)r0�repeat�best�worst�all_runs�compile_time�
  30  _precision�timings)r4r0r7r8r9r:r;�	precisionr/r3r5�__init__UszTimeitResult.__init__cCst�|j�t|j�S�N)�math�fsumr=�lenr3r/r/r5�average_szTimeitResult.averagecs.|j�t��fdd�|jD��t|j�dS)Ncsg|]}|�d�qS)�r/)r1�x��meanr/r5r6fsz&TimeitResult.stdev.<locals>.<listcomp>g�?)rDrArBr=rCr3r/rGr5�stdevcs(zTimeitResult.stdevc
  31  Cs�d}ttjd�rtjjrzd�tjj�d}WnYdj||j|j|jdkr*dnd|jdkr2dndt|j	|j
  32  �t|j|j
  33  �d�S)	Nz+-�encoding�±zl{mean} {pm} {std} per loop (mean {pm} std. dev. of {runs} run{run_plural}, {loops:,} loop{loop_plural} each)���s)�pm�runsr0Zloop_pluralZ
  34  run_pluralrHZstd)�hasattr�sys�stdoutrJ�encode�formatr7r0�_format_timerDr<rI)r4rOr/r/r5�__str__hs �zTimeitResult.__str__cCs|��}|�d|d�dS)Nz<TimeitResult : �>)rW�text)r4�p�cycleZunicr/r/r5�
  35  _repr_pretty_zszTimeitResult._repr_pretty_N)
  36  �__name__�
  37  __module__�__qualname__�__doc__r?�propertyrDrIrWr\r/r/r/r5r.Hs
  38  
  39  
  40  r.c@s(eZdZdZdd�Zdd�Zdd�ZdS)	�TimeitTemplateFillerz�Fill in the AST template for timing execution.
  41  
  42      This is quite closely tied to the template definition, which is in
  43      :meth:`ExecutionMagics.timeit`.
  44      cCs||_||_dSr@)�	ast_setup�ast_stmt)r4rcrdr/r/r5r?�s
  45  zTimeitTemplateFiller.__init__cCs*|�|�|jdkr|jj|jdd�<|S)zFill in the setup statement�innerNrL)�
  46  generic_visit�namerc�body�r4�noder/r/r5�visit_FunctionDef�s
  47  
  48  z&TimeitTemplateFiller.visit_FunctionDefcCs,tt|jddd�dd�dkr|jj|_|S)z!Fill in the statement to be timedr�valueN�id�stmt)�getattrrhrdrir/r/r5�	visit_For�s
  49  zTimeitTemplateFiller.visit_ForN)r]r^r_r`r?rkrpr/r/r/r5rbs
  50  rbc@seZdZdZejfdd�ZdS)�Timerz�Timer class that explicitly uses self.inner
  51      
  52      which is an undocumented implementation detail of CPython,
  53      not shared by PyPy.
  54      cCsNt�d|�}t��}t��z|�||j�}W|rt��|S|r&t��ww)a�Time 'number' executions of the main statement.
  55  
  56          To be precise, this executes the setup statement once, and
  57          then returns the time it takes to execute the main statement
  58          a number of times, as a float measured in seconds.  The
  59          argument is the number of times through the loop, defaulting
  60          to one million.  The main statement, the setup statement and
  61          the timer function to be used are passed to the constructor.
  62          N)�	itertoolsr7�gc�	isenabled�disablere�timer�enable)r4�number�itZgcoldZtimingr/r/r5�timeit�s
  63  �
  64  �zTimer.timeitN)r]r^r_r`rzZdefault_numberr/r/r/r5rq�srqc
  65  s�eZdZUdZiZeeefed<�fdd�Z	e
  66  eedCdd����Z
  67  d	d
  68  �ZedDdd��Ze��ejd
  69  dddd�ejdddd�eeedEdd�������Zdd�ZdFdd�Zedd��Ze
  70  eddefdd���Z	dGd d!�Zed"d#��Ze
  71  eeedEd$d%�����Ze
  72  eeeedEd&d'������Ze
  73  edDd(d)���Z e��ejd*edd+d,d-�ejd.d/d0d1�ejd2d/d3d1�ejd4d/d5d1�e!d6d7�������Z"e
  74  e��ejd8ed9d+d:�ejd;d/d<d1�ejd=d/d>d1�ejd?d/d@d1�edFdAdB��������Z#�Z$S)H�ExecutionMagicsz<Magics related to code execution, debugging, profiling, etc.�
  75  _transformerscstt|��|�d|_dSr@)�superr{r?�default_runner)r4�shell��	__class__r/r5r?�s
  76  zExecutionMagics.__init__rMNcCsH|j|dddd�\}}|dur|d|7}|j�|�}|�|||jj�S)aqRun a statement through the python code profiler.
  77  
  78          **Usage, in line mode:**
  79  
  80            %prun [options] statement
  81  
  82          **Usage, in cell mode:**
  83  
  84            %%prun [options] [statement]
  85  
  86            code...
  87  
  88            code...
  89  
  90          In cell mode, the additional code lines are appended to the (possibly
  91          empty) statement in the first line.  Cell mode allows you to easily
  92          profile multiline blocks without having to put them in a separate
  93          function.
  94  
  95          The given statement (which doesn't require quote marks) is run via the
  96          python profiler in a manner similar to the profile.run() function.
  97          Namespaces are internally managed to work correctly; profile.run
  98          cannot be used in IPython because it makes certain assumptions about
  99          namespaces which do not hold under IPython.
 100  
 101          Options:
 102  
 103          -l <limit>
 104            you can place restrictions on what or how much of the
 105            profile gets printed. The limit value can be:
 106  
 107               * A string: only information for function names containing this string
 108                 is printed.
 109  
 110               * An integer: only these many lines are printed.
 111  
 112               * A float (between 0 and 1): this fraction of the report is printed
 113                 (for example, use a limit of 0.4 to see the topmost 40% only).
 114  
 115            You can combine several limits with repeated use of the option. For
 116            example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
 117            information about class constructors.
 118  
 119          -r
 120            return the pstats.Stats object generated by the profiling. This
 121            object has all the information about the profile in it, and you can
 122            later use it for further analysis or in other functions.
 123  
 124          -s <key>
 125            sort profile by given key. You can provide more than one key
 126            by using the option several times: '-s key1 -s key2 -s key3...'. The
 127            default sorting key is 'time'.
 128  
 129            The following is copied verbatim from the profile documentation
 130            referenced below:
 131  
 132            When more than one key is provided, additional keys are used as
 133            secondary criteria when the there is equality in all keys selected
 134            before them.
 135  
 136            Abbreviations can be used for any key names, as long as the
 137            abbreviation is unambiguous.  The following are the keys currently
 138            defined:
 139  
 140            ============  =====================
 141            Valid Arg     Meaning
 142            ============  =====================
 143            "calls"       call count
 144            "cumulative"  cumulative time
 145            "file"        file name
 146            "module"      file name
 147            "pcalls"      primitive call count
 148            "line"        line number
 149            "name"        function name
 150            "nfl"         name/file/line
 151            "stdname"     standard name
 152            "time"        internal time
 153            ============  =====================
 154  
 155            Note that all sorts on statistics are in descending order (placing
 156            most time consuming items first), where as name, file, and line number
 157            searches are in ascending order (i.e., alphabetical). The subtle
 158            distinction between "nfl" and "stdname" is that the standard name is a
 159            sort of the name as printed, which means that the embedded line
 160            numbers get compared in an odd way.  For example, lines 3, 20, and 40
 161            would (if the file names were the same) appear in the string order
 162            "20" "3" and "40".  In contrast, "nfl" does a numeric compare of the
 163            line numbers.  In fact, sort_stats("nfl") is the same as
 164            sort_stats("name", "file", "line").
 165  
 166          -T <filename>
 167            save profile results as shown on screen to a text
 168            file. The profile is still shown on screen.
 169  
 170          -D <filename>
 171            save (via dump_stats) profile statistics to given
 172            filename. This data is in a format understood by the pstats module, and
 173            is generated by a call to the dump_stats() method of profile
 174            objects. The profile is still shown on screen.
 175  
 176          -q
 177            suppress output to the pager.  Best used with -T and/or -D above.
 178  
 179          If you want to run complete programs under the profiler's control, use
 180          ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
 181          contains profiler specific options as described here.
 182  
 183          You can read the complete documentation for the profile module with::
 184  
 185            In [1]: import profile; profile.help()
 186  
 187          .. versionchanged:: 7.3
 188              User variables are no longer expanded,
 189              the magic line is always left unmodified.
 190  
 191          z
 192  D:l:rs:T:qTF)�list_all�posixN�
 193  )�
 194  parse_optionsr�transform_cell�_run_with_profiler�user_ns)r4�parameter_s�cell�optsZarg_strr/r/r5�prun�sy
 195  �zExecutionMagics.pruncCs�|�tdggdgdgd��t��}z|�|||�}d}Wnty(d}Ynwt�|���j	|j
 196  �}|j}|rkg}|jD],}z	|�t
 197  |��Wq>tyjz	|�t|��Wntyg|�|�YnwYq>wt�}	|j}
 198  z
 199  |	|_|j|�W|
 200  |_n|
 201  |_w|	��}|��}d|vr�t�|�t|dd�|jd}|jd}
 202  |r�|�|�td	t|��d
 203  |���|
 204  r�t|
 205  �}|jdd�|j|d
 206  d�tdt|
 207  ��d
 208  |���d|vr�|SdS)aZ
 209          Run `code` with profiler.  Used by ``%prun`` and ``%run -p``.
 210  
 211          Parameters
 212          ----------
 213          code : str
 214              Code to be executed.
 215          opts : Struct
 216              Options parsed by `self.parse_options`.
 217          namespace : dict
 218              A dictionary for Python namespace (e.g., `self.shell.user_ns`).
 219  
 220          rM�time)�D�lrN�Tz7*** SystemExit exception caught in code being profiled.�q� ��endrz&
 221  *** Profile stats marshalled to file �.T)�exist_okzutf-8)rJz)
 222  *** Profile printout saved to text file �rN)�merger'�profileZProfileZrunctx�
 223  SystemExit�pstatsZStatsZ
 224  strip_dirsZ
 225  sort_statsrNr��append�int�
 226  ValueError�floatr�streamZprint_stats�getvalue�rstripr�printr�r�Z
 227  dump_stats�reprr�touch�
 228  write_text)r4�coder��	namespaceZprofZsys_exit�statsZlimsZlimZstdout_trapZstats_stream�outputZ	dump_fileZ	text_fileZpfiler/r/r5r�?sf�
 229  ���
 230  
 231  
 232  
 233  ��z"ExecutionMagics._run_with_profilercCsh|����}|r"zddddd�|}Wnty!td�YdSw|jj}||j_tdt|��dS)a�Control the automatic calling of the pdb interactive debugger.
 234  
 235          Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
 236          argument it works as a toggle.
 237  
 238          When an exception is triggered, IPython can optionally call the
 239          interactive pdb debugger after the traceback printout. %pdb toggles
 240          this feature on and off.
 241  
 242          The initial state of this feature is set in your configuration
 243          file (the option is ``InteractiveShell.pdb``).
 244  
 245          If you want to just activate the debugger AFTER an exception has fired,
 246          without having to type '%pdb on' and rerunning your code, you can use
 247          the %debug magic.rrL)�off�0�on�1z=Incorrect argument. Use on/1, off/0, or nothing for a toggle.Nz%Automatic pdb calling has been turned)�strip�lower�KeyErrorr�rZcall_pdbr")r4r��parZnew_pdbr/r/r5�pdb�s�
 248  zExecutionMagics.pdbz--breakpointz-bz	FILE:LINEz2
 249          Set break point at LINE in FILE.
 250          )�metavar�help�	statement�*zX
 251          Code to run in debugger.
 252          You can omit this in cell magic mode.
 253          )�nargsr�cCsvt�|j|�}|js|js|s|��dS|js#|s#|�|d|�dSd�|j�}|r1|d|7}|�||j|�dS)alActivate the interactive debugger.
 254  
 255          This magic command support two ways of activating debugger.
 256          One is to activate debugger before executing code.  This way, you
 257          can set a break point, to step through the code from the point.
 258          You can use this mode by giving statements to execute and optionally
 259          a breakpoint.
 260  
 261          The other one is to activate debugger in post-mortem mode.  You can
 262          activate this mode simply running %debug without any argument.
 263          If an exception has just occurred, this lets you inspect its stack
 264          frames interactively.  Note that this will always work only on the last
 265          traceback that occurred, so you must call this quickly after an
 266          exception that you wish to inspect has fired, because if another one
 267          occurs, it clobbers the previous one.
 268  
 269          If you want IPython to automatically do this on every exception, see
 270          the %pdb magic for more details.
 271  
 272          .. versionchanged:: 7.3
 273              When running code, user variables are no longer expanded,
 274              the magic line is always left unmodified.
 275  
 276          Nr�)r�parse_argstring�debug�
 277  breakpointr��_debug_post_mortem�_debug_exec�join)r4�liner��local_ns�argsr�r/r/r5r��s(
 278  zExecutionMagics.debugcCs|jjdd�dS)NT)�force)rZdebuggerr3r/r/r5r���z"ExecutionMagics._debug_post_mortemcCsB|r|�dd�\}}t|�}nd\}}|j||jj|||d�dS)N�:rL)NN)r�)�rsplitr��_run_with_debuggerrr�)r4r�r�r��filename�bp_liner/r/r5r��s
 279  
 280  �zExecutionMagics._debug_execc	Cs�|jj}|rHdd�}|����}|j}z-z|j|d�Wn
 281  ty)|d�Ynw|j��W|j|d�dSW|j|d�dS|j|d�w|j��dS)a:Print the last traceback.
 282  
 283          Optionally, specify an exception reporting mode, tuning the
 284          verbosity of the traceback. By default the currently-active exception
 285          mode is used. See %xmode for changing exception reporting modes.
 286  
 287          Valid modes: Plain, Context, Verbose, and Minimal.
 288          cSstd|t��df�dS)Nz%Error changing %s exception modes.
 289  %srL)rrR�exc_info)rgr/r/r5�xmode_switch_errs
 290  �z,ExecutionMagics.tb.<locals>.xmode_switch_err��mode�userN)r�
 291  InteractiveTBr��
 292  capitalizer��set_mode�	Exception�
 293  showtraceback)r4rNZinteractive_tbr�Znew_modeZ
 294  original_moder/r/r5�tb�s 
 295  ��zExecutionMagics.tbcszd|vr?d|vr?tj|tjdkd�}t|�D]\}}|r4|�d�r4|dkr4|dkr3|�|dd�nqd�dd	�|D��}�j|d
 296  ddd
 297  �\}}d|vri|dd�t	��}	|	durdd�}
 298  t
 299  |
 300  ��|	g|}zd}|d}||��WnVty�}zd}
 301  t
 302  |
 303  �|�d}~wty�}z'zt
 304  |�}
 305  Wnty�|j}
 306  Ynwtjdkr�t�d|�r�td�t
 307  |
 308  �|�d}~wty�|tjvr�d�n�Ynw����d�r�t�jjd����jjd<�jj�dd�Wd�dS1s�wYdSd|v�tj}
 309  d|v�r|dd�}n
 310  tttjj |dd���}�g|t_d|v�r,t!��j"}nd}d|v�rJ�jj��jjd }|�d <�jj#}��d<n
 311  �j�$�|�}|j%��d }|dk�rctj&d}nd!}|tj&|<d"|v�std#|v�r�d|v�r�d$}�jj'��d%�}nd#|v�r�d&}nd'}�jj(�t)��d(�}�zd}d"|v�r���*|||�}n�d#|v�r�t+|�,d)d*g�d��\}}��-||�||�nd|v�rԇ��fd+d,�}n�du�r܈j.��du�r�jj(�����fd-d,�}d.|v�rBz;t/|d/d�}|dk�r-t0d0�WWt1�jjd1<|
 312  t_|�r'|tj&d<d2tj&v�r%|tj&d2<dSdStj&|=dSWnt2�y:d}Ynw��3||�n|�d|v�rQ|�jjd <n%��4d d�t�jjd���jj�5��Wd�n	1�sqwYWt1�jjd1<|
 313  t_|�r�|tj&d<d2tj&v�r�|tj&d2<|Stj&|=|St1�jjd1<|
 314  t_|�r�|tj&d<d2tj&v�r�|tj&d2<wtj&|=w)3aRun the named file inside IPython as a program.
 315  
 316          Usage::
 317  
 318            %run [-n -i -e -G]
 319                 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
 320                 ( -m mod | filename ) [args]
 321  
 322          The filename argument should be either a pure Python script (with
 323          extension ``.py``), or a file with custom IPython syntax (such as
 324          magics). If the latter, the file can be either a script with ``.ipy``
 325          extension, or a Jupyter notebook with ``.ipynb`` extension. When running
 326          a Jupyter notebook, the output from print statements and other
 327          displayed objects will appear in the terminal (even matplotlib figures
 328          will open, if a terminal-compliant backend is being used). Note that,
 329          at the system command line, the ``jupyter run`` command offers similar
 330          functionality for executing notebooks (albeit currently with some
 331          differences in supported options).
 332  
 333          Parameters after the filename are passed as command-line arguments to
 334          the program (put in sys.argv). Then, control returns to IPython's
 335          prompt.
 336  
 337          This is similar to running at a system prompt ``python file args``,
 338          but with the advantage of giving you IPython's tracebacks, and of
 339          loading all variables into your interactive namespace for further use
 340          (unless -p is used, see below).
 341  
 342          The file is executed in a namespace initially consisting only of
 343          ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
 344          sees its environment as if it were being run as a stand-alone program
 345          (except for sharing global objects such as previously imported
 346          modules). But after execution, the IPython interactive namespace gets
 347          updated with all variables defined in the program (except for __name__
 348          and sys.argv). This allows for very convenient loading of code for
 349          interactive work, while giving each program a 'clean sheet' to run in.
 350  
 351          Arguments are expanded using shell-like glob match.  Patterns
 352          '*', '?', '[seq]' and '[!seq]' can be used.  Additionally,
 353          tilde '~' will be expanded into user's home directory.  Unlike
 354          real shells, quotation does not suppress expansions.  Use
 355          *two* back slashes (e.g. ``\\*``) to suppress expansions.
 356          To completely disable these expansions, you can use -G flag.
 357  
 358          On Windows systems, the use of single quotes `'` when specifying
 359          a file is not supported. Use double quotes `"`.
 360  
 361          Options:
 362  
 363          -n
 364            __name__ is NOT set to '__main__', but to the running file's name
 365            without extension (as python does under import).  This allows running
 366            scripts and reloading the definitions in them without calling code
 367            protected by an ``if __name__ == "__main__"`` clause.
 368  
 369          -i
 370            run the file in IPython's namespace instead of an empty one. This
 371            is useful if you are experimenting with code written in a text editor
 372            which depends on variables defined interactively.
 373  
 374          -e
 375            ignore sys.exit() calls or SystemExit exceptions in the script
 376            being run.  This is particularly useful if IPython is being used to
 377            run unittests, which always exit with a sys.exit() call.  In such
 378            cases you are interested in the output of the test results, not in
 379            seeing a traceback of the unittest module.
 380  
 381          -t
 382            print timing information at the end of the run.  IPython will give
 383            you an estimated CPU time consumption for your script, which under
 384            Unix uses the resource module to avoid the wraparound problems of
 385            time.clock().  Under Unix, an estimate of time spent on system tasks
 386            is also given (for Windows platforms this is reported as 0.0).
 387  
 388          If -t is given, an additional ``-N<N>`` option can be given, where <N>
 389          must be an integer indicating how many times you want the script to
 390          run.  The final timing report will include total and per run results.
 391  
 392          For example (testing the script uniq_stable.py)::
 393  
 394              In [1]: run -t uniq_stable
 395  
 396              IPython CPU timings (estimated):
 397                User  :    0.19597 s.
 398                System:        0.0 s.
 399  
 400              In [2]: run -t -N5 uniq_stable
 401  
 402              IPython CPU timings (estimated):
 403              Total runs performed: 5
 404                Times :      Total       Per run
 405                User  :   0.910862 s,  0.1821724 s.
 406                System:        0.0 s,        0.0 s.
 407  
 408          -d
 409            run your program under the control of pdb, the Python debugger.
 410            This allows you to execute your program step by step, watch variables,
 411            etc.  Internally, what IPython does is similar to calling::
 412  
 413                pdb.run('execfile("YOURFILENAME")')
 414  
 415            with a breakpoint set on line 1 of your file.  You can change the line
 416            number for this automatic breakpoint to be <N> by using the -bN option
 417            (where N must be an integer). For example::
 418  
 419                %run -d -b40 myscript
 420  
 421            will set the first breakpoint at line 40 in myscript.py.  Note that
 422            the first breakpoint must be set on a line which actually does
 423            something (not a comment or docstring) for it to stop execution.
 424  
 425            Or you can specify a breakpoint in a different file::
 426  
 427                %run -d -b myotherfile.py:20 myscript
 428  
 429            When the pdb debugger starts, you will see a (Pdb) prompt.  You must
 430            first enter 'c' (without quotes) to start execution up to the first
 431            breakpoint.
 432  
 433            Entering 'help' gives information about the use of the debugger.  You
 434            can easily see pdb's full documentation with "import pdb;pdb.help()"
 435            at a prompt.
 436  
 437          -p
 438            run program under the control of the Python profiler module (which
 439            prints a detailed report of execution times, function calls, etc).
 440  
 441            You can pass other options after -p which affect the behavior of the
 442            profiler itself. See the docs for %prun for details.
 443  
 444            In this mode, the program's variables do NOT propagate back to the
 445            IPython interactive namespace (because they remain in the namespace
 446            where the profiler executes them).
 447  
 448            Internally this triggers a call to %prun, see its documentation for
 449            details on the options available specifically for profiling.
 450  
 451          There is one special usage for which the text above doesn't apply:
 452          if the filename ends with .ipy[nb], the file is run as ipython script,
 453          just as if the commands were written on IPython prompt.
 454  
 455          -m
 456            specify module name to load instead of script path. Similar to
 457            the -m option for the python interpreter. Use this option last if you
 458            want to combine with other %run options. Unlike the python interpreter
 459            only source modules are allowed no .pyc or .pyo files.
 460            For example::
 461  
 462                %run -m example
 463  
 464            will run the example module.
 465  
 466          -G
 467            disable shell-like glob expansion of arguments.
 468  
 469          z-mz--r�)r��-rEr�css�|]}t�|�VqdSr@)�shlex�quote)r1�argr/r/r5�	<genexpr>�s�z&ExecutionMagics.run.<locals>.<genexpr>znidtN:b:pD:l:rs:T:em:G�listrL)r�r��mrNz(%r is not a valid modulename on sys.pathz%you must provide at least a filename.�ntz^'.*'$zJFor Windows, use double quotes to wrap a filename: %run "mypath\myfile.py"rM)z.ipyz.ipynb�__file__T)Zraise_exceptions�e�G�n�__main__�ir]FrZ�dzrun_module(modulename, prog_ns))�
 470  run_module�prog_ns�
 471  modulenamez2execfile(filename, prog_ns, raise_exceptions=True)zexecfile(filename, prog_ns))Zexecfiler�r��br�cs�j����dSr@)r�safe_run_moduler/)r�r�r4r/r5�run=r�z ExecutionMagics.run.<locals>.runcs�����d�dS)N)�exit_ignorer/r/)r�r�r��runnerr/r5r�Es
 472  ��t�NzNumber of runs must be >=1�__builtins__�__mp_main__)6r��split�osrg�	enumerate�
 473  startswith�insertr�r�r(r��
 474  IndexError�IOError�str�UnicodeError�message�re�matchr�	TypeErrorrR�	meta_pathr��endswithr&rr�Zsafe_execfile_ipy�argvr*�map�path�
 475  expanduserr�stemZuser_moduleZnew_main_mod�__dict__�modulesr�Z
 476  safe_execfiler)r��parse_breakpoint�getr�r~r�r�builtin_modr��_run_with_timing�pop�update)r4r�r�Zfile_finderr��idxr�r�Zarg_lst�modpath�msgZfpathr�Z	save_argvr�rgZ_ExecutionMagics__name__saveZmain_modZ
 477  main_mod_nameZrestore_mainr��code_nsr��bp_filer�r��nrunsr/)r�r�r�r�r�r4r5r�s.$�
 478  �
 479  
 480  �
 481  �
 482  �
 483  ��
 484  ��
 485  
 486  
 487  
 488  
 489  
 490  
 491  �
 492  �
 493  
 494  �
 495  �
 496  
 497  
 498  
 499  
 500  
 501  ���
 502  ��
 503  
 504  ��
 505  
 506  zExecutionMagics.runc	Cs�|jjj}|s|jj��|jj_|jjj}t|d�r|`dtj_itj_	dgtj_
 507  |��|durfd}|p6|}|�||�}	|	s]t
 508  |d||d�D]
 509  }
 510  |�||
 511  �rTn	qJd|
 512  }t|��|�d||f�|rqd|_|�|�|_td|j�zj|r~||_	z3z
 513  t��}|�|||�Wnty�td	�|r�d|_|�|�|_YWt�|�q~wWt�|�nt�|�wt|d
 514  �r�|��|j�dg�z|�d||�WWdSty�YWdSwWdSt��\}
 515  }}|jj|
 516  ||d
 517  d�YdS)a�
 518          Run `code` in debugger with a break point.
 519  
 520          Parameters
 521          ----------
 522          code : str
 523              Code to execute.
 524          code_ns : dict
 525              A namespace in which `code` is executed.
 526          filename : str
 527              `code` is ran as if it is in `filename`.
 528          bp_line : int, optional
 529              Line number of the break point.
 530          bp_file : str, optional
 531              Path to the file in which break point is specified.
 532              `filename` is used if not given.
 533          local_ns : dict, optional
 534              A local namespace in which `code` is executed.
 535  
 536          Raises
 537          ------
 538          UsageError
 539              If the break point given by `bp_line` is not valid.
 540  
 541          �curframerLN�
 542  z�
 543  I failed to find a valid line to set a breakpoint
 544  after trying up to line: %s.
 545  Please set a valid breakpoint manually with the -b option.z%s:%sTz7NOTE: Enter 'c' at the %s prompt to continue execution.Z
 546  Restarting�rcLinesr�rM�)�	tb_offset) rr�r�Zdebugger_clsrQr�bdbZ
 547  Breakpoint�nextZbplistZ
 548  bpbynumberZclear_all_breaks�	checkline�rangerZdo_breakZ_wait_for_mainpyfileZcanonicZ
 549  mainpyfiler��promptZ_exec_filenamerR�gettracer�r�settraceZset_quitr�extend�
 550  StopIterationr�)r4r�rr�r�rr�Zdeb�maxtriesr�bpr
 551  �trace�etyperlr�r/r/r5r�|sr
 552  
 553  
 554  
 555  ���
 556  ��
 557  z"ExecutionMagics._run_with_debuggerc
 558  Cs
 559  t��}|dkr2t�}|�t�}|d|d}|d|d}td�td|�td|�nEt|�}t�}|D]}|�q;t�}|d|d}|d|d}td�td|�tdd�td	|||f�td
 560  |||f�t��}	td|	|�dS)
 561  z�
 562          Run function `run` and print timing information.
 563  
 564          Parameters
 565          ----------
 566          run : callable
 567              Any callable object which takes no argument.
 568          nruns : int
 569              Number of times to execute `run`.
 570  
 571          rLrz!
 572  IPython CPU timings (estimated):z  User   : %10.2f s.z  System : %10.2f s.zTotal runs performed:z  Times  : %10s   %10s)ZTotalzPer runz  User   : %10.2f s, %10.2f s.z  System : %10.2f s, %10.2f s.zWall time: %10.2f s.N)r��perf_counterr,r�r)
 573  r�rZtwall0�t0�t1Zt_usrZt_sysrP�nrZtwall1r/r/r5r�s0
 574  
 575  z ExecutionMagics._run_with_timingc"Cs�|j|ddddd�\}}|dkr|durdStj}tt|dd��}tjd	kr(d	ntj}tt|d
 576  |��}	tt|dd��}
 577  d
 578  |v}d|v}t|d�rKtj}t|d�rRt}t	|d�}
 579  |j
 580  j}|durp|j
 581  j�
 582  d�}|j
 583  j�
 584  ||��}n|j
 585  j�
 586  ||��}|j
 587  j�
 588  ||��}|j
 589  �|�}|j
 590  �|�}|j
 591  �|dd�|j
 592  �|dd�t�d�}t||��|�}t�|�}d}t�}|j
 593  �|dd�}t�|}i}|j
 594  j}i}|r�|dur�|��D]\}}||vr�|||<q�|�|�t|||�|d|
 595  _|dk�rtdd�D]}d|}|
 596  �|�}|dk�r
 597  nq�|
 598  �|	|�}t|�|}t|�|} t||	|| |||
 599  �}!|�r2|�|�|�s]| d|k�rN|dk�rN| dk�rNtd| |�t|!�||k�r]td|�|�rb|!SdS) u�
 600  Time execution of a Python statement or expression
 601  
 602          **Usage, in line mode:**
 603  
 604            %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
 605  
 606          **or in cell mode:**
 607  
 608            %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
 609  
 610            code
 611  
 612            code...
 613  
 614          Time execution of a Python statement or expression using the timeit
 615          module.  This function can be used both as a line and cell magic:
 616  
 617          - In line mode you can time a single-line statement (though multiple
 618            ones can be chained with using semicolons).
 619  
 620          - In cell mode, the statement in the first line is used as setup code
 621            (executed but not timed) and the body of the cell is timed.  The cell
 622            body has access to any variables created in the setup code.
 623  
 624          Options:
 625  
 626          -n<N>: execute the given statement <N> times in a loop. If <N> is not
 627          provided, <N> is determined so as to get sufficient accuracy.
 628  
 629          -r<R>: number of repeats <R>, each consisting of <N> loops, and take the
 630          average result.
 631          Default: 7
 632  
 633          -t: use time.time to measure the time, which is the default on Unix.
 634          This function measures wall time.
 635  
 636          -c: use time.clock to measure the time, which is the default on
 637          Windows and measures wall time. On Unix, resource.getrusage is used
 638          instead and returns the CPU user time.
 639  
 640          -p<P>: use a precision of <P> digits to display the timing result.
 641          Default: 3
 642  
 643          -q: Quiet, do not print result.
 644  
 645          -o: return a TimeitResult that can be stored in a variable to inspect
 646          the result in more details.
 647  
 648          .. versionchanged:: 7.3
 649              User variables are no longer expanded,
 650              the magic line is always left unmodified.
 651  
 652          Examples
 653          --------
 654          ::
 655  
 656            In [1]: %timeit pass
 657            8.26 ns ± 0.12 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
 658  
 659            In [2]: u = None
 660  
 661            In [3]: %timeit u is None
 662            29.9 ns ± 0.643 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
 663  
 664            In [4]: %timeit -r 4 u == None
 665  
 666            In [5]: import time
 667  
 668            In [6]: %timeit -n1 time.sleep(2)
 669  
 670          The times reported by %timeit will be slightly higher than those
 671          reported by the timeit.py script when variables are accessed. This is
 672          due to the fact that %timeit executes the statement in the namespace
 673          of the shell, compared with timeit.py, which uses a single setup
 674          statement to import function or create variables. Generally, the bias
 675          does not matter as long as results from timeit.py are not mixed with
 676          those from %timeit.z
 677  n:r:tcp:qoFT)r��strictZpreserve_non_optsrMNr�r�r�rZrr��or��c)rv�passz<magic-timeit-setup>�execz<magic-timeit-stmt>z}def inner(_it, _timer):
 678      setup
 679      _t0 = _timer()
 680      for _i in _it:
 681          stmt
 682      _t1 = _timer()
 683      return _t1 - _t0
 684  皙�����?z<magic-timeit>rerg�������?�g�����ư>zvThe slowest run took %0.2f times longer than the fastest. This could mean that an intermediate result is being cached.zCompiler time: %.2f s)r�rzZ
 685  default_timerr�ro�default_repeatrQr�r+rqrr��compile�	ast_parse�
 686  transform_ast�astrrb�visit�fix_missing_locationsr��itemsr
 687  r,rerr7�min�maxr.r�)"r4r�r�r�r�rnZtimefuncrxr/r7r>�quietZ
 688  return_resultrvZ	transformrcrdZtimeit_ast_templateZ
 689  timeit_ast�tc_minr$r��tc�ns�globZconflict_globs�var_nameZvar_val�indexZtime_numberr:r8r9Z
 690  timeit_resultr/r/r5rzs�S
 691  
 692  �
 693  
 694  
 695  
 696  
 697  
 698  �
 699  
 700  
 701  
 702  
 703  �
 704  "�
 705  �zExecutionMagics.timeitcCs�|r|rtd��|r|j�|�}n|j�|�}d}t�}|jj�|�}t�|}|j�|�}d}	d}
 706  t|j�dkrPt	|jdt
 707  j�rPd}d}t
 708  �|jdj
 709  �}n+d}d	}t|j�dkr{t	|jd
 710  t
 711  j�r{|jd
 712  }
 713  |jdd
 714  �}t|g�}t
 715  �|
 716  j
 717  �}
 718  t�}|j�|||�}
 719  t�|}|jj}tj}|�}|dkr�t�}zt|
 720  ||�}Wn|j��YdSt�}n.t�}zt|
 721  ||�d}|
 722  dur�|j�|
 723  |d�}t|||�}Wn|j��YdSt�}|�}||}|d|d}|d|d}||}tjdk�rtdt|��d
 724  t|��dt|����n	tdt|����tdt|����||	k�r7tdt|����||k�rEtdt|����|S)aYTime execution of a Python statement or expression.
 725  
 726          The CPU and wall clock times are printed, and the value of the
 727          expression (if any) is returned.  Note that under Win32, system time
 728          is always reported as 0, since it can not be measured.
 729  
 730          This function can be used both as a line and cell magic:
 731  
 732          - In line mode you can time a single-line statement (though multiple
 733            ones can be chained with using semicolons).
 734  
 735          - In cell mode, you can time the cell body (a directly
 736            following statement raises an error).
 737  
 738          This function provides very basic timing functionality.  Use the timeit
 739          magic for more control over the measurement.
 740  
 741          .. versionchanged:: 7.3
 742              User variables are no longer expanded,
 743              the magic line is always left unmodified.
 744  
 745          Examples
 746          --------
 747          ::
 748  
 749            In [1]: %time 2**128
 750            CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
 751            Wall time: 0.00
 752            Out[1]: 340282366920938463463374607431768211456L
 753  
 754            In [2]: n = 1000000
 755  
 756            In [3]: %time sum(range(n))
 757            CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
 758            Wall time: 1.37
 759            Out[3]: 499999500000L
 760  
 761            In [4]: %time print('hello world')
 762            hello world
 763            CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
 764            Wall time: 0.00
 765  
 766          .. note::
 767              The time needed by Python to compile the given expression will be
 768              reported if it is more than 0.1s.
 769  
 770              In the example below, the actual exponentiation is done by Python
 771              at compilation time, so while the expression can take a noticeable
 772              amount of time to compute, that time is purely due to the
 773              compilation::
 774  
 775                  In [5]: %time 3**9999;
 776                  CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
 777                  Wall time: 0.00 s
 778  
 779                  In [6]: %time 3**999999;
 780                  CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
 781                  Wall time: 0.00 s
 782                  Compiler : 0.78 s
 783          z,Can't use statement directly after '%%time'!r-NrLr�evalz<timed eval>r,z<timed exec>������win32zCPU times: user z, sys: z	, total: zCPU times: total: zWall time: zCompiler : zParser   : )rrr�r+r0r1r2rCrh�
 784  isinstancer3r�
 785  Expressionrlrr�r�r,r@r�r,rR�platformr�rV)r4r�r�r��exprZtp_minr$Zexpr_ast�tpr:Zexpr_valr��sourcer�r;r=ZwtimeZwall_st�st�outr�Zcode_2Zwall_endZ	wall_timeZcpu_userZcpu_sysZcpu_totr/r/r5r��s�D
 786    
 787  
 788  
 789  
 790  �
 791   �
 792  
 793  zExecutionMagics.timec	
 794  Cs�|j|ddd�\}}|stdd�|jj��D��St|�dkr#td��|dd	�|dd
 795  ��}}z|j�|d|v�}Wnt	t
 796  fyX}zt|jd�WYd
 797  }~d
 798  Sd
 799  }~wwt
 800  |�}|j�||�d|vrztd
 801  |�td�t|d	d�d
 802  Sd
 803  S)a5	Define a macro for future re-execution. It accepts ranges of history,
 804          filenames or string objects.
 805  
 806          Usage:\
 807            %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
 808  
 809          Options:
 810  
 811            -r: use 'raw' input.  By default, the 'processed' history is used,
 812            so that magics are loaded in their transformed version to valid
 813            Python.  If this option is given, the raw input as typed at the
 814            command line is used instead.
 815            
 816            -q: quiet macro definition.  By default, a tag line is printed 
 817            to indicate the macro has been created, and then the contents of 
 818            the macro are printed.  If this option is given, then no printout
 819            is produced once the macro is created.
 820  
 821          This will define a global variable called `name` which is a string
 822          made of joining the slices and lines you specify (n1,n2,... numbers
 823          above) from your input history into a single string. This variable
 824          acts like an automatic function which re-executes those lines as if
 825          you had typed them. You just type 'name' at the prompt and the code
 826          executes.
 827  
 828          The syntax for indicating input ranges is described in %history.
 829  
 830          Note: as a 'hidden' feature, you can also use traditional python slice
 831          notation, where N:M means numbers N through M-1.
 832  
 833          For example, if your history contains (print using %hist -n )::
 834  
 835            44: x=1
 836            45: y=3
 837            46: z=x+y
 838            47: print(x)
 839            48: a=5
 840            49: print('x',x,'y',y)
 841  
 842          you can create a macro with lines 44 through 47 (included) and line 49
 843          called my_macro with::
 844  
 845            In [55]: %macro my_macro 44-47 49
 846  
 847          Now, typing `my_macro` (without quotes) will re-execute all this code
 848          in one pass.
 849  
 850          You don't need to give the line-numbers in order, and any given line
 851          number can appear multiple times. You can assemble macros with any
 852          lines from your input history in any order.
 853  
 854          The macro is a simple object which holds its value in an attribute,
 855          but IPython's display system checks for macros and executes them as
 856          code instead of printing them when you type their name.
 857  
 858          You can view a macro's contents by explicitly printing it with::
 859  
 860            print(macro_name)
 861  
 862          Zrqr�r�css"�|]\}}t|t�r|VqdSr@)rCr)r1�k�vr/r/r5r��s� z(ExecutionMagics.macro.<locals>.<genexpr>rLz:%macro insufficient args; usage '%macro name n1-n2 n3-4...rr�Nr�r�z?Macro `%s` created. To execute, type its name (without quotes).z=== Macro contents: ===r�)r��sortedrr�r6rCrr�Zfind_user_coder�r�r�r�rZdefine_macro)	r4r�r�r�rgZcodefrom�linesr��macror/r/r5rOss,?����zExecutionMagics.macror��?a�The name of the variable in which to store output.
 863          This is a utils.io.CapturedIO object with stdout/err attributes
 864          for the text of the captured output.
 865  
 866          CapturedOutput also has a show() method for displaying the output,
 867          and __call__ as well, so you can use that to quickly display the
 868          output.
 869  
 870          If unspecified, captured output is discarded.
 871          )�type�defaultr�r�z--no-stderr�
 872  store_truezDon't capture stderr.)�actionr�z--no-stdoutzDon't capture stdout.z--no-displayz%Don't capture IPython's rich display.cCs�t�|j|�}|j}|j}|j}t|||��}|j�|�Wd�n1s*wYt	�
 873  |�rE|j|jjvrC|jj|j=dSdS|jrQ||jj|j<dSdS)zKrun the cell, capturing stdout, stderr, and IPython's rich display() calls.N)
 874  rr��captureZ	no_stdoutZ	no_stderrZ
 875  no_displayr%rZrun_cellrZsemicolon_at_end_of_expressionr�r�)r4r�r�r�rJ�errZdisp�ior/r/r5rU�s�
 876  ��zExecutionMagics.capturergrR)rQrRr�z--removezremove the current transformerz--listzlist existing transformers namez
 877  --list-allz1list existing transformers name and code templatecCs�t�|j|�}|jr|j��D]}t|�qdS|jr:|j��D]\}}t|d�tt	t
 878  �|j�d��q t�dS|j�
 879  |jd�}||jjvrO|jj�|�|dusV|jrXdStt
 880  �|��}||j|j<|jj�|�dS)ao
 881          Simple magic to quickly define a code transformer for all IPython's future input.
 882  
 883          ``__code__`` and ``__ret__`` are special variable that represent the code to run
 884          and the value of the last expression of ``__code__`` respectively.
 885  
 886          Examples
 887          --------
 888  
 889          .. ipython::
 890  
 891              In [1]: %%code_wrap before_after
 892                 ...: print('before')
 893                 ...: __code__
 894                 ...: print('after')
 895                 ...: __ret__
 896  
 897  
 898              In [2]: 1
 899              before
 900              after
 901              Out[2]: 1
 902  
 903              In [3]: %code_wrap --list
 904              before_after
 905  
 906              In [4]: %code_wrap --list-all
 907              before_after :
 908                  print('before')
 909                  __code__
 910                  print('after')
 911                  __ret__
 912  
 913              In [5]: %code_wrap --remove before_after
 914  
 915          Nr�z    )rr��	code_wrapr�r|�keysr�r�r6rr3r
 916  �templater	rgrZast_transformers�remover-rr�)r4r�r�r�rgZ_t�	to_removeZ_trsr/r/r5rX�s&4
 917  
 918  zExecutionMagics.code_wrap)rMN)rM)rMNNr@)NNNN)%r]r^r_r`r|rr�r�__annotations__r?r$r!rr�r�rr�rZargumentr r�r�r�r�r)r�r��staticmethodrrzr#r�rOrrUrX�
 919  __classcell__r/r/r�r5r{�s�
 920  }L"
 921  ��)
 922  
 923  
 924  �j
 925  �o
 926  &CR������� r{cCs>|�d�}|dkr|t|�fS|d|�t||dd��fS)zDReturns (file, line) for file:line and (current_file, line) for liner�rANrL)�findr�)rYZcurrent_file�colonr/r/r5r9s
 927   rrcCs�|dkr7gd�}g}|}|D]#\}}t||�}|dkr+||}|�dt|�|f�|dkr1nqd�|�Sgd�}ttjd�rWtjjrWz
 928  d	�tjj�gd
 929  �}WnYgd�}	|dkrpt	tt
 930  �t
 931  �|��d
 932  �d
 933  �}
 934  nd
 935  }
 936  d|||	|
 937  ||
 938  fS)z-Formats the timespan in a human readable formgN@))r�i�Q)�hi)r7�<)rNrLrz%s%srLr�)rN�ms�usr<rJuμ)rNrduμsr<)rLg@�@g��.Age��Agrz%.*g %s)
 939  r�r�r�r�rQrRrSrJrTr7rA�floor�log10)Ztimespanr>�partsr��leftover�suffix�lengthrlZunitsZscaling�orderr/r/r5rVAs2�
 940  "rV)r)Yr`r3r�builtinsr�copyZcProfiler�rsrrrAr�r�r�r�rRr�rz�typingrrrrrrrr	r
 941  rrr
 942  rWr�loggingr�pathlibrr�r�textwraprr�warningsrZIPython.corerrrZIPython.core.displayhookrZIPython.core.errorrZIPython.core.macrorZIPython.core.magicrrrrrr r!r"r#ZIPython.testing.skipdoctestr$ZIPython.utils.capturer%ZIPython.utils.contextsr&ZIPython.utils.ipstructr'ZIPython.utils.module_pathsr(ZIPython.utils.pathr)r*ZIPython.utils.timingr+r,ZIPython.core.magics.ast_modr-�objectr.rbrqr{rrVr/r/r/r5�<module>sn0,7