##// END OF EJS Templates
reformat all of IPython.core
Matthias Bussonnier -
Show More
@@ -1,658 +1,657 b''
1 1 """Implementation of basic magic functions."""
2 2
3 3
4 4 import argparse
5 5 from logging import error
6 6 import io
7 7 from pprint import pformat
8 8 import sys
9 9 from warnings import warn
10 10
11 11 from traitlets.utils.importstring import import_item
12 12 from IPython.core import magic_arguments, page
13 13 from IPython.core.error import UsageError
14 14 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
15 15 from IPython.utils.text import format_screen, dedent, indent
16 16 from IPython.testing.skipdoctest import skip_doctest
17 17 from IPython.utils.ipstruct import Struct
18 18
19 19
20 20 class MagicsDisplay(object):
21 21 def __init__(self, magics_manager, ignore=None):
22 22 self.ignore = ignore if ignore else []
23 23 self.magics_manager = magics_manager
24 24
25 25 def _lsmagic(self):
26 26 """The main implementation of the %lsmagic"""
27 27 mesc = magic_escapes['line']
28 28 cesc = magic_escapes['cell']
29 29 mman = self.magics_manager
30 30 magics = mman.lsmagic()
31 31 out = ['Available line magics:',
32 32 mesc + (' '+mesc).join(sorted([m for m,v in magics['line'].items() if (v not in self.ignore)])),
33 33 '',
34 34 'Available cell magics:',
35 35 cesc + (' '+cesc).join(sorted([m for m,v in magics['cell'].items() if (v not in self.ignore)])),
36 36 '',
37 37 mman.auto_status()]
38 38 return '\n'.join(out)
39 39
40 40 def _repr_pretty_(self, p, cycle):
41 41 p.text(self._lsmagic())
42 42
43 43 def __str__(self):
44 44 return self._lsmagic()
45 45
46 46 def _jsonable(self):
47 47 """turn magics dict into jsonable dict of the same structure
48
48
49 49 replaces object instances with their class names as strings
50 50 """
51 51 magic_dict = {}
52 52 mman = self.magics_manager
53 53 magics = mman.lsmagic()
54 54 for key, subdict in magics.items():
55 55 d = {}
56 56 magic_dict[key] = d
57 57 for name, obj in subdict.items():
58 58 try:
59 59 classname = obj.__self__.__class__.__name__
60 60 except AttributeError:
61 61 classname = 'Other'
62 62
63 63 d[name] = classname
64 64 return magic_dict
65 65
66 66 def _repr_json_(self):
67 67 return self._jsonable()
68 68
69 69
70 70 @magics_class
71 71 class BasicMagics(Magics):
72 72 """Magics that provide central IPython functionality.
73 73
74 74 These are various magics that don't fit into specific categories but that
75 75 are all part of the base 'IPython experience'."""
76 76
77 77 @skip_doctest
78 78 @magic_arguments.magic_arguments()
79 79 @magic_arguments.argument(
80 80 '-l', '--line', action='store_true',
81 81 help="""Create a line magic alias."""
82 82 )
83 83 @magic_arguments.argument(
84 84 '-c', '--cell', action='store_true',
85 85 help="""Create a cell magic alias."""
86 86 )
87 87 @magic_arguments.argument(
88 88 'name',
89 89 help="""Name of the magic to be created."""
90 90 )
91 91 @magic_arguments.argument(
92 92 'target',
93 93 help="""Name of the existing line or cell magic."""
94 94 )
95 95 @magic_arguments.argument(
96 96 '-p', '--params', default=None,
97 97 help="""Parameters passed to the magic function."""
98 98 )
99 99 @line_magic
100 100 def alias_magic(self, line=''):
101 101 """Create an alias for an existing line or cell magic.
102 102
103 103 Examples
104 104 --------
105 105 ::
106 106
107 107 In [1]: %alias_magic t timeit
108 108 Created `%t` as an alias for `%timeit`.
109 109 Created `%%t` as an alias for `%%timeit`.
110 110
111 111 In [2]: %t -n1 pass
112 112 1 loops, best of 3: 954 ns per loop
113 113
114 114 In [3]: %%t -n1
115 115 ...: pass
116 116 ...:
117 117 1 loops, best of 3: 954 ns per loop
118 118
119 119 In [4]: %alias_magic --cell whereami pwd
120 120 UsageError: Cell magic function `%%pwd` not found.
121 121 In [5]: %alias_magic --line whereami pwd
122 122 Created `%whereami` as an alias for `%pwd`.
123 123
124 124 In [6]: %whereami
125 125 Out[6]: u'/home/testuser'
126
126
127 127 In [7]: %alias_magic h history "-p -l 30" --line
128 128 Created `%h` as an alias for `%history -l 30`.
129 129 """
130 130
131 131 args = magic_arguments.parse_argstring(self.alias_magic, line)
132 132 shell = self.shell
133 133 mman = self.shell.magics_manager
134 134 escs = ''.join(magic_escapes.values())
135 135
136 136 target = args.target.lstrip(escs)
137 137 name = args.name.lstrip(escs)
138 138
139 139 params = args.params
140 140 if (params and
141 141 ((params.startswith('"') and params.endswith('"'))
142 142 or (params.startswith("'") and params.endswith("'")))):
143 143 params = params[1:-1]
144 144
145 145 # Find the requested magics.
146 146 m_line = shell.find_magic(target, 'line')
147 147 m_cell = shell.find_magic(target, 'cell')
148 148 if args.line and m_line is None:
149 149 raise UsageError('Line magic function `%s%s` not found.' %
150 150 (magic_escapes['line'], target))
151 151 if args.cell and m_cell is None:
152 152 raise UsageError('Cell magic function `%s%s` not found.' %
153 153 (magic_escapes['cell'], target))
154 154
155 155 # If --line and --cell are not specified, default to the ones
156 156 # that are available.
157 157 if not args.line and not args.cell:
158 158 if not m_line and not m_cell:
159 159 raise UsageError(
160 160 'No line or cell magic with name `%s` found.' % target
161 161 )
162 162 args.line = bool(m_line)
163 163 args.cell = bool(m_cell)
164 164
165 165 params_str = "" if params is None else " " + params
166 166
167 167 if args.line:
168 168 mman.register_alias(name, target, 'line', params)
169 169 print('Created `%s%s` as an alias for `%s%s%s`.' % (
170 170 magic_escapes['line'], name,
171 171 magic_escapes['line'], target, params_str))
172 172
173 173 if args.cell:
174 174 mman.register_alias(name, target, 'cell', params)
175 175 print('Created `%s%s` as an alias for `%s%s%s`.' % (
176 176 magic_escapes['cell'], name,
177 177 magic_escapes['cell'], target, params_str))
178 178
179 179 @line_magic
180 180 def lsmagic(self, parameter_s=''):
181 181 """List currently available magic functions."""
182 182 return MagicsDisplay(self.shell.magics_manager, ignore=[])
183 183
184 184 def _magic_docs(self, brief=False, rest=False):
185 185 """Return docstrings from magic functions."""
186 186 mman = self.shell.magics_manager
187 187 docs = mman.lsmagic_docs(brief, missing='No documentation')
188 188
189 189 if rest:
190 190 format_string = '**%s%s**::\n\n%s\n\n'
191 191 else:
192 192 format_string = '%s%s:\n%s\n'
193 193
194 194 return ''.join(
195 195 [format_string % (magic_escapes['line'], fname,
196 196 indent(dedent(fndoc)))
197 197 for fname, fndoc in sorted(docs['line'].items())]
198 198 +
199 199 [format_string % (magic_escapes['cell'], fname,
200 200 indent(dedent(fndoc)))
201 201 for fname, fndoc in sorted(docs['cell'].items())]
202 202 )
203 203
204 204 @line_magic
205 205 def magic(self, parameter_s=''):
206 206 """Print information about the magic function system.
207 207
208 208 Supported formats: -latex, -brief, -rest
209 209 """
210 210
211 211 mode = ''
212 212 try:
213 213 mode = parameter_s.split()[0][1:]
214 214 except IndexError:
215 215 pass
216 216
217 217 brief = (mode == 'brief')
218 218 rest = (mode == 'rest')
219 219 magic_docs = self._magic_docs(brief, rest)
220 220
221 221 if mode == 'latex':
222 222 print(self.format_latex(magic_docs))
223 223 return
224 224 else:
225 225 magic_docs = format_screen(magic_docs)
226 226
227 227 out = ["""
228 228 IPython's 'magic' functions
229 229 ===========================
230 230
231 231 The magic function system provides a series of functions which allow you to
232 232 control the behavior of IPython itself, plus a lot of system-type
233 233 features. There are two kinds of magics, line-oriented and cell-oriented.
234 234
235 235 Line magics are prefixed with the % character and work much like OS
236 236 command-line calls: they get as an argument the rest of the line, where
237 237 arguments are passed without parentheses or quotes. For example, this will
238 238 time the given statement::
239 239
240 240 %timeit range(1000)
241 241
242 242 Cell magics are prefixed with a double %%, and they are functions that get as
243 243 an argument not only the rest of the line, but also the lines below it in a
244 244 separate argument. These magics are called with two arguments: the rest of the
245 245 call line and the body of the cell, consisting of the lines below the first.
246 246 For example::
247 247
248 248 %%timeit x = numpy.random.randn((100, 100))
249 249 numpy.linalg.svd(x)
250 250
251 251 will time the execution of the numpy svd routine, running the assignment of x
252 252 as part of the setup phase, which is not timed.
253 253
254 254 In a line-oriented client (the terminal or Qt console IPython), starting a new
255 255 input with %% will automatically enter cell mode, and IPython will continue
256 256 reading input until a blank line is given. In the notebook, simply type the
257 257 whole cell as one entity, but keep in mind that the %% escape can only be at
258 258 the very start of the cell.
259 259
260 260 NOTE: If you have 'automagic' enabled (via the command line option or with the
261 261 %automagic function), you don't need to type in the % explicitly for line
262 262 magics; cell magics always require an explicit '%%' escape. By default,
263 263 IPython ships with automagic on, so you should only rarely need the % escape.
264 264
265 265 Example: typing '%cd mydir' (without the quotes) changes your working directory
266 266 to 'mydir', if it exists.
267 267
268 268 For a list of the available magic functions, use %lsmagic. For a description
269 269 of any of them, type %magic_name?, e.g. '%cd?'.
270 270
271 271 Currently the magic system has the following functions:""",
272 272 magic_docs,
273 273 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
274 274 str(self.lsmagic()),
275 275 ]
276 276 page.page('\n'.join(out))
277 277
278 278
279 279 @line_magic
280 280 def page(self, parameter_s=''):
281 281 """Pretty print the object and display it through a pager.
282 282
283 283 %page [options] OBJECT
284 284
285 285 If no object is given, use _ (last output).
286 286
287 287 Options:
288 288
289 289 -r: page str(object), don't pretty-print it."""
290 290
291 291 # After a function contributed by Olivier Aubert, slightly modified.
292 292
293 293 # Process options/args
294 294 opts, args = self.parse_options(parameter_s, 'r')
295 295 raw = 'r' in opts
296 296
297 297 oname = args and args or '_'
298 298 info = self.shell._ofind(oname)
299 299 if info['found']:
300 300 txt = (raw and str or pformat)( info['obj'] )
301 301 page.page(txt)
302 302 else:
303 303 print('Object `%s` not found' % oname)
304 304
305 305 @line_magic
306 306 def pprint(self, parameter_s=''):
307 307 """Toggle pretty printing on/off."""
308 308 ptformatter = self.shell.display_formatter.formatters['text/plain']
309 309 ptformatter.pprint = bool(1 - ptformatter.pprint)
310 310 print('Pretty printing has been turned',
311 311 ['OFF','ON'][ptformatter.pprint])
312 312
313 313 @line_magic
314 314 def colors(self, parameter_s=''):
315 315 """Switch color scheme for prompts, info system and exception handlers.
316 316
317 317 Currently implemented schemes: NoColor, Linux, LightBG.
318 318
319 319 Color scheme names are not case-sensitive.
320 320
321 321 Examples
322 322 --------
323 323 To get a plain black and white terminal::
324 324
325 325 %colors nocolor
326 326 """
327 327 def color_switch_err(name):
328 328 warn('Error changing %s color schemes.\n%s' %
329 329 (name, sys.exc_info()[1]), stacklevel=2)
330 330
331 331
332 332 new_scheme = parameter_s.strip()
333 333 if not new_scheme:
334 334 raise UsageError(
335 335 "%colors: you must specify a color scheme. See '%colors?'")
336 336 # local shortcut
337 337 shell = self.shell
338 338
339 339 # Set shell colour scheme
340 340 try:
341 341 shell.colors = new_scheme
342 342 shell.refresh_style()
343 343 except:
344 344 color_switch_err('shell')
345 345
346 346 # Set exception colors
347 347 try:
348 348 shell.InteractiveTB.set_colors(scheme = new_scheme)
349 349 shell.SyntaxTB.set_colors(scheme = new_scheme)
350 350 except:
351 351 color_switch_err('exception')
352 352
353 353 # Set info (for 'object?') colors
354 354 if shell.color_info:
355 355 try:
356 356 shell.inspector.set_active_scheme(new_scheme)
357 357 except:
358 358 color_switch_err('object inspector')
359 359 else:
360 360 shell.inspector.set_active_scheme('NoColor')
361 361
362 362 @line_magic
363 363 def xmode(self, parameter_s=''):
364 364 """Switch modes for the exception handlers.
365 365
366 366 Valid modes: Plain, Context, Verbose, and Minimal.
367 367
368 368 If called without arguments, acts as a toggle.
369 369
370 When in verbose mode the value --show (and --hide)
370 When in verbose mode the value --show (and --hide)
371 371 will respectively show (or hide) frames with ``__tracebackhide__ =
372 372 True`` value set.
373 373 """
374 374
375 375 def xmode_switch_err(name):
376 376 warn('Error changing %s exception modes.\n%s' %
377 377 (name,sys.exc_info()[1]))
378 378
379 379 shell = self.shell
380 380 if parameter_s.strip() == "--show":
381 381 shell.InteractiveTB.skip_hidden = False
382 382 return
383 383 if parameter_s.strip() == "--hide":
384 384 shell.InteractiveTB.skip_hidden = True
385 385 return
386 386
387 387 new_mode = parameter_s.strip().capitalize()
388 388 try:
389 389 shell.InteractiveTB.set_mode(mode=new_mode)
390 390 print('Exception reporting mode:',shell.InteractiveTB.mode)
391 391 except:
392 392 xmode_switch_err('user')
393 393
394 394 @line_magic
395 395 def quickref(self, arg):
396 396 """ Show a quick reference sheet """
397 397 from IPython.core.usage import quick_reference
398 398 qr = quick_reference + self._magic_docs(brief=True)
399 399 page.page(qr)
400 400
401 401 @line_magic
402 402 def doctest_mode(self, parameter_s=''):
403 403 """Toggle doctest mode on and off.
404 404
405 405 This mode is intended to make IPython behave as much as possible like a
406 406 plain Python shell, from the perspective of how its prompts, exceptions
407 407 and output look. This makes it easy to copy and paste parts of a
408 408 session into doctests. It does so by:
409 409
410 410 - Changing the prompts to the classic ``>>>`` ones.
411 411 - Changing the exception reporting mode to 'Plain'.
412 412 - Disabling pretty-printing of output.
413 413
414 414 Note that IPython also supports the pasting of code snippets that have
415 415 leading '>>>' and '...' prompts in them. This means that you can paste
416 416 doctests from files or docstrings (even if they have leading
417 417 whitespace), and the code will execute correctly. You can then use
418 418 '%history -t' to see the translated history; this will give you the
419 419 input after removal of all the leading prompts and whitespace, which
420 420 can be pasted back into an editor.
421 421
422 422 With these features, you can switch into this mode easily whenever you
423 423 need to do testing and changes to doctests, without having to leave
424 424 your existing IPython session.
425 425 """
426 426
427 427 # Shorthands
428 428 shell = self.shell
429 429 meta = shell.meta
430 430 disp_formatter = self.shell.display_formatter
431 431 ptformatter = disp_formatter.formatters['text/plain']
432 432 # dstore is a data store kept in the instance metadata bag to track any
433 433 # changes we make, so we can undo them later.
434 434 dstore = meta.setdefault('doctest_mode',Struct())
435 435 save_dstore = dstore.setdefault
436 436
437 437 # save a few values we'll need to recover later
438 438 mode = save_dstore('mode',False)
439 439 save_dstore('rc_pprint',ptformatter.pprint)
440 440 save_dstore('xmode',shell.InteractiveTB.mode)
441 441 save_dstore('rc_separate_out',shell.separate_out)
442 442 save_dstore('rc_separate_out2',shell.separate_out2)
443 443 save_dstore('rc_separate_in',shell.separate_in)
444 444 save_dstore('rc_active_types',disp_formatter.active_types)
445 445
446 446 if not mode:
447 447 # turn on
448 448
449 449 # Prompt separators like plain python
450 450 shell.separate_in = ''
451 451 shell.separate_out = ''
452 452 shell.separate_out2 = ''
453 453
454 454
455 455 ptformatter.pprint = False
456 456 disp_formatter.active_types = ['text/plain']
457 457
458 458 shell.magic('xmode Plain')
459 459 else:
460 460 # turn off
461 461 shell.separate_in = dstore.rc_separate_in
462 462
463 463 shell.separate_out = dstore.rc_separate_out
464 464 shell.separate_out2 = dstore.rc_separate_out2
465 465
466 466 ptformatter.pprint = dstore.rc_pprint
467 467 disp_formatter.active_types = dstore.rc_active_types
468 468
469 469 shell.magic('xmode ' + dstore.xmode)
470 470
471 471 # mode here is the state before we switch; switch_doctest_mode takes
472 472 # the mode we're switching to.
473 473 shell.switch_doctest_mode(not mode)
474 474
475 475 # Store new mode and inform
476 476 dstore.mode = bool(not mode)
477 477 mode_label = ['OFF','ON'][dstore.mode]
478 478 print('Doctest mode is:', mode_label)
479 479
480 480 @line_magic
481 481 def gui(self, parameter_s=''):
482 482 """Enable or disable IPython GUI event loop integration.
483 483
484 484 %gui [GUINAME]
485 485
486 486 This magic replaces IPython's threaded shells that were activated
487 487 using the (pylab/wthread/etc.) command line flags. GUI toolkits
488 488 can now be enabled at runtime and keyboard
489 489 interrupts should work without any problems. The following toolkits
490 490 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
491 491
492 492 %gui wx # enable wxPython event loop integration
493 493 %gui qt4|qt # enable PyQt4 event loop integration
494 494 %gui qt5 # enable PyQt5 event loop integration
495 495 %gui gtk # enable PyGTK event loop integration
496 496 %gui gtk3 # enable Gtk3 event loop integration
497 497 %gui gtk4 # enable Gtk4 event loop integration
498 498 %gui tk # enable Tk event loop integration
499 499 %gui osx # enable Cocoa event loop integration
500 500 # (requires %matplotlib 1.1)
501 501 %gui # disable all event loop integration
502 502
503 503 WARNING: after any of these has been called you can simply create
504 504 an application object, but DO NOT start the event loop yourself, as
505 505 we have already handled that.
506 506 """
507 507 opts, arg = self.parse_options(parameter_s, '')
508 508 if arg=='': arg = None
509 509 try:
510 510 return self.shell.enable_gui(arg)
511 511 except Exception as e:
512 512 # print simple error message, rather than traceback if we can't
513 513 # hook up the GUI
514 514 error(str(e))
515 515
516 516 @skip_doctest
517 517 @line_magic
518 518 def precision(self, s=''):
519 519 """Set floating point precision for pretty printing.
520 520
521 521 Can set either integer precision or a format string.
522 522
523 523 If numpy has been imported and precision is an int,
524 524 numpy display precision will also be set, via ``numpy.set_printoptions``.
525 525
526 526 If no argument is given, defaults will be restored.
527 527
528 528 Examples
529 529 --------
530 530 ::
531 531
532 532 In [1]: from math import pi
533 533
534 534 In [2]: %precision 3
535 535 Out[2]: u'%.3f'
536 536
537 537 In [3]: pi
538 538 Out[3]: 3.142
539 539
540 540 In [4]: %precision %i
541 541 Out[4]: u'%i'
542 542
543 543 In [5]: pi
544 544 Out[5]: 3
545 545
546 546 In [6]: %precision %e
547 547 Out[6]: u'%e'
548 548
549 549 In [7]: pi**10
550 550 Out[7]: 9.364805e+04
551 551
552 552 In [8]: %precision
553 553 Out[8]: u'%r'
554 554
555 555 In [9]: pi**10
556 556 Out[9]: 93648.047476082982
557 557 """
558 558 ptformatter = self.shell.display_formatter.formatters['text/plain']
559 559 ptformatter.float_precision = s
560 560 return ptformatter.float_format
561 561
562 562 @magic_arguments.magic_arguments()
563 563 @magic_arguments.argument(
564 564 'filename', type=str,
565 565 help='Notebook name or filename'
566 566 )
567 567 @line_magic
568 568 def notebook(self, s):
569 569 """Export and convert IPython notebooks.
570 570
571 571 This function can export the current IPython history to a notebook file.
572 572 For example, to export the history to "foo.ipynb" do "%notebook foo.ipynb".
573 573 """
574 574 args = magic_arguments.parse_argstring(self.notebook, s)
575 575
576 576 from nbformat import write, v4
577 577
578 578 cells = []
579 579 hist = list(self.shell.history_manager.get_range())
580 580 if(len(hist)<=1):
581 581 raise ValueError('History is empty, cannot export')
582 582 for session, execution_count, source in hist[:-1]:
583 583 cells.append(v4.new_code_cell(
584 584 execution_count=execution_count,
585 585 source=source
586 586 ))
587 587 nb = v4.new_notebook(cells=cells)
588 588 with io.open(args.filename, 'w', encoding='utf-8') as f:
589 589 write(nb, f, version=4)
590 590
591 591 @magics_class
592 592 class AsyncMagics(BasicMagics):
593 593
594 594 @line_magic
595 595 def autoawait(self, parameter_s):
596 596 """
597 597 Allow to change the status of the autoawait option.
598 598
599 599 This allow you to set a specific asynchronous code runner.
600 600
601 601 If no value is passed, print the currently used asynchronous integration
602 602 and whether it is activated.
603 603
604 604 It can take a number of value evaluated in the following order:
605 605
606 606 - False/false/off deactivate autoawait integration
607 607 - True/true/on activate autoawait integration using configured default
608 608 loop
609 609 - asyncio/curio/trio activate autoawait integration and use integration
610 610 with said library.
611 611
612 612 - `sync` turn on the pseudo-sync integration (mostly used for
613 613 `IPython.embed()` which does not run IPython with a real eventloop and
614 614 deactivate running asynchronous code. Turning on Asynchronous code with
615 615 the pseudo sync loop is undefined behavior and may lead IPython to crash.
616 616
617 617 If the passed parameter does not match any of the above and is a python
618 618 identifier, get said object from user namespace and set it as the
619 runner, and activate autoawait.
619 runner, and activate autoawait.
620 620
621 621 If the object is a fully qualified object name, attempt to import it and
622 622 set it as the runner, and activate autoawait.
623
624
623
625 624 The exact behavior of autoawait is experimental and subject to change
626 625 across version of IPython and Python.
627 626 """
628 627
629 628 param = parameter_s.strip()
630 629 d = {True: "on", False: "off"}
631 630
632 631 if not param:
633 632 print("IPython autoawait is `{}`, and set to use `{}`".format(
634 633 d[self.shell.autoawait],
635 634 self.shell.loop_runner
636 635 ))
637 636 return None
638 637
639 638 if param.lower() in ('false', 'off'):
640 639 self.shell.autoawait = False
641 640 return None
642 641 if param.lower() in ('true', 'on'):
643 642 self.shell.autoawait = True
644 643 return None
645 644
646 645 if param in self.shell.loop_runner_map:
647 646 self.shell.loop_runner, self.shell.autoawait = self.shell.loop_runner_map[param]
648 647 return None
649 648
650 649 if param in self.shell.user_ns :
651 650 self.shell.loop_runner = self.shell.user_ns[param]
652 651 self.shell.autoawait = True
653 652 return None
654 653
655 654 runner = import_item(param)
656 655
657 656 self.shell.loop_runner = runner
658 657 self.shell.autoawait = True
@@ -1,1509 +1,1507 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Implementation of execution-related magic functions."""
3 3
4 4 # Copyright (c) IPython Development Team.
5 5 # Distributed under the terms of the Modified BSD License.
6 6
7 7
8 8 import ast
9 9 import bdb
10 10 import builtins as builtin_mod
11 11 import cProfile as profile
12 12 import gc
13 13 import itertools
14 14 import math
15 15 import os
16 16 import pstats
17 17 import re
18 18 import shlex
19 19 import sys
20 20 import time
21 21 import timeit
22 22 from ast import Module
23 23 from io import StringIO
24 24 from logging import error
25 25 from pathlib import Path
26 26 from pdb import Restart
27 27 from warnings import warn
28 28
29 29 from IPython.core import magic_arguments, oinspect, page
30 30 from IPython.core.error import UsageError
31 31 from IPython.core.macro import Macro
32 32 from IPython.core.magic import (
33 33 Magics,
34 34 cell_magic,
35 35 line_cell_magic,
36 36 line_magic,
37 37 magics_class,
38 38 needs_local_scope,
39 39 no_var_expand,
40 40 on_off,
41 41 )
42 42 from IPython.testing.skipdoctest import skip_doctest
43 43 from IPython.utils.capture import capture_output
44 44 from IPython.utils.contexts import preserve_keys
45 45 from IPython.utils.ipstruct import Struct
46 46 from IPython.utils.module_paths import find_mod
47 47 from IPython.utils.path import get_py_filename, shellglob
48 48 from IPython.utils.timing import clock, clock2
49 49
50 50 #-----------------------------------------------------------------------------
51 51 # Magic implementation classes
52 52 #-----------------------------------------------------------------------------
53 53
54 54
55 55 class TimeitResult(object):
56 56 """
57 57 Object returned by the timeit magic with info about the run.
58 58
59 59 Contains the following attributes :
60 60
61 61 loops: (int) number of loops done per measurement
62 62 repeat: (int) number of times the measurement has been repeated
63 63 best: (float) best execution time / number
64 64 all_runs: (list of float) execution time of each run (in s)
65 65 compile_time: (float) time of statement compilation (s)
66 66
67 67 """
68 68 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
69 69 self.loops = loops
70 70 self.repeat = repeat
71 71 self.best = best
72 72 self.worst = worst
73 73 self.all_runs = all_runs
74 74 self.compile_time = compile_time
75 75 self._precision = precision
76 76 self.timings = [ dt / self.loops for dt in all_runs]
77 77
78 78 @property
79 79 def average(self):
80 80 return math.fsum(self.timings) / len(self.timings)
81 81
82 82 @property
83 83 def stdev(self):
84 84 mean = self.average
85 85 return (math.fsum([(x - mean) ** 2 for x in self.timings]) / len(self.timings)) ** 0.5
86 86
87 87 def __str__(self):
88 88 pm = '+-'
89 89 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
90 90 try:
91 91 u'\xb1'.encode(sys.stdout.encoding)
92 92 pm = u'\xb1'
93 93 except:
94 94 pass
95 95 return "{mean} {pm} {std} per loop (mean {pm} std. dev. of {runs} run{run_plural}, {loops:,} loop{loop_plural} each)".format(
96 96 pm=pm,
97 97 runs=self.repeat,
98 98 loops=self.loops,
99 99 loop_plural="" if self.loops == 1 else "s",
100 100 run_plural="" if self.repeat == 1 else "s",
101 101 mean=_format_time(self.average, self._precision),
102 102 std=_format_time(self.stdev, self._precision),
103 103 )
104 104
105 105 def _repr_pretty_(self, p , cycle):
106 106 unic = self.__str__()
107 107 p.text(u'<TimeitResult : '+unic+u'>')
108 108
109 109
110 110 class TimeitTemplateFiller(ast.NodeTransformer):
111 111 """Fill in the AST template for timing execution.
112 112
113 113 This is quite closely tied to the template definition, which is in
114 114 :meth:`ExecutionMagics.timeit`.
115 115 """
116 116 def __init__(self, ast_setup, ast_stmt):
117 117 self.ast_setup = ast_setup
118 118 self.ast_stmt = ast_stmt
119 119
120 120 def visit_FunctionDef(self, node):
121 121 "Fill in the setup statement"
122 122 self.generic_visit(node)
123 123 if node.name == "inner":
124 124 node.body[:1] = self.ast_setup.body
125 125
126 126 return node
127 127
128 128 def visit_For(self, node):
129 129 "Fill in the statement to be timed"
130 130 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
131 131 node.body = self.ast_stmt.body
132 132 return node
133 133
134 134
135 135 class Timer(timeit.Timer):
136 136 """Timer class that explicitly uses self.inner
137 137
138 138 which is an undocumented implementation detail of CPython,
139 139 not shared by PyPy.
140 140 """
141 141 # Timer.timeit copied from CPython 3.4.2
142 142 def timeit(self, number=timeit.default_number):
143 143 """Time 'number' executions of the main statement.
144 144
145 145 To be precise, this executes the setup statement once, and
146 146 then returns the time it takes to execute the main statement
147 147 a number of times, as a float measured in seconds. The
148 148 argument is the number of times through the loop, defaulting
149 149 to one million. The main statement, the setup statement and
150 150 the timer function to be used are passed to the constructor.
151 151 """
152 152 it = itertools.repeat(None, number)
153 153 gcold = gc.isenabled()
154 154 gc.disable()
155 155 try:
156 156 timing = self.inner(it, self.timer)
157 157 finally:
158 158 if gcold:
159 159 gc.enable()
160 160 return timing
161 161
162 162
163 163 @magics_class
164 164 class ExecutionMagics(Magics):
165 165 """Magics related to code execution, debugging, profiling, etc.
166 166
167 167 """
168 168
169 169 def __init__(self, shell):
170 170 super(ExecutionMagics, self).__init__(shell)
171 171 # Default execution function used to actually run user code.
172 172 self.default_runner = None
173 173
174 174 @skip_doctest
175 175 @no_var_expand
176 176 @line_cell_magic
177 177 def prun(self, parameter_s='', cell=None):
178 178
179 179 """Run a statement through the python code profiler.
180 180
181 181 Usage, in line mode:
182 182 %prun [options] statement
183 183
184 184 Usage, in cell mode:
185 185 %%prun [options] [statement]
186 186 code...
187 187 code...
188 188
189 189 In cell mode, the additional code lines are appended to the (possibly
190 190 empty) statement in the first line. Cell mode allows you to easily
191 191 profile multiline blocks without having to put them in a separate
192 192 function.
193 193
194 194 The given statement (which doesn't require quote marks) is run via the
195 195 python profiler in a manner similar to the profile.run() function.
196 196 Namespaces are internally managed to work correctly; profile.run
197 197 cannot be used in IPython because it makes certain assumptions about
198 198 namespaces which do not hold under IPython.
199 199
200 200 Options:
201 201
202 202 -l <limit>
203 203 you can place restrictions on what or how much of the
204 204 profile gets printed. The limit value can be:
205 205
206 206 * A string: only information for function names containing this string
207 207 is printed.
208 208
209 209 * An integer: only these many lines are printed.
210 210
211 211 * A float (between 0 and 1): this fraction of the report is printed
212 212 (for example, use a limit of 0.4 to see the topmost 40% only).
213 213
214 214 You can combine several limits with repeated use of the option. For
215 215 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
216 216 information about class constructors.
217 217
218 218 -r
219 219 return the pstats.Stats object generated by the profiling. This
220 220 object has all the information about the profile in it, and you can
221 221 later use it for further analysis or in other functions.
222 222
223 223 -s <key>
224 224 sort profile by given key. You can provide more than one key
225 225 by using the option several times: '-s key1 -s key2 -s key3...'. The
226 226 default sorting key is 'time'.
227 227
228 228 The following is copied verbatim from the profile documentation
229 229 referenced below:
230 230
231 231 When more than one key is provided, additional keys are used as
232 232 secondary criteria when the there is equality in all keys selected
233 233 before them.
234 234
235 235 Abbreviations can be used for any key names, as long as the
236 236 abbreviation is unambiguous. The following are the keys currently
237 237 defined:
238 238
239 239 ============ =====================
240 240 Valid Arg Meaning
241 241 ============ =====================
242 242 "calls" call count
243 243 "cumulative" cumulative time
244 244 "file" file name
245 245 "module" file name
246 246 "pcalls" primitive call count
247 247 "line" line number
248 248 "name" function name
249 249 "nfl" name/file/line
250 250 "stdname" standard name
251 251 "time" internal time
252 252 ============ =====================
253 253
254 254 Note that all sorts on statistics are in descending order (placing
255 255 most time consuming items first), where as name, file, and line number
256 256 searches are in ascending order (i.e., alphabetical). The subtle
257 257 distinction between "nfl" and "stdname" is that the standard name is a
258 258 sort of the name as printed, which means that the embedded line
259 259 numbers get compared in an odd way. For example, lines 3, 20, and 40
260 260 would (if the file names were the same) appear in the string order
261 261 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
262 262 line numbers. In fact, sort_stats("nfl") is the same as
263 263 sort_stats("name", "file", "line").
264 264
265 265 -T <filename>
266 266 save profile results as shown on screen to a text
267 267 file. The profile is still shown on screen.
268 268
269 269 -D <filename>
270 270 save (via dump_stats) profile statistics to given
271 271 filename. This data is in a format understood by the pstats module, and
272 272 is generated by a call to the dump_stats() method of profile
273 273 objects. The profile is still shown on screen.
274 274
275 275 -q
276 276 suppress output to the pager. Best used with -T and/or -D above.
277 277
278 278 If you want to run complete programs under the profiler's control, use
279 279 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
280 280 contains profiler specific options as described here.
281 281
282 282 You can read the complete documentation for the profile module with::
283 283
284 284 In [1]: import profile; profile.help()
285 285
286 286 .. versionchanged:: 7.3
287 287 User variables are no longer expanded,
288 288 the magic line is always left unmodified.
289 289
290 290 """
291 291 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
292 292 list_all=True, posix=False)
293 293 if cell is not None:
294 294 arg_str += '\n' + cell
295 295 arg_str = self.shell.transform_cell(arg_str)
296 296 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
297 297
298 298 def _run_with_profiler(self, code, opts, namespace):
299 299 """
300 300 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
301 301
302 302 Parameters
303 303 ----------
304 304 code : str
305 305 Code to be executed.
306 306 opts : Struct
307 307 Options parsed by `self.parse_options`.
308 308 namespace : dict
309 309 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
310 310
311 311 """
312 312
313 313 # Fill default values for unspecified options:
314 314 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
315 315
316 316 prof = profile.Profile()
317 317 try:
318 318 prof = prof.runctx(code, namespace, namespace)
319 319 sys_exit = ''
320 320 except SystemExit:
321 321 sys_exit = """*** SystemExit exception caught in code being profiled."""
322 322
323 323 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
324 324
325 325 lims = opts.l
326 326 if lims:
327 327 lims = [] # rebuild lims with ints/floats/strings
328 328 for lim in opts.l:
329 329 try:
330 330 lims.append(int(lim))
331 331 except ValueError:
332 332 try:
333 333 lims.append(float(lim))
334 334 except ValueError:
335 335 lims.append(lim)
336 336
337 337 # Trap output.
338 338 stdout_trap = StringIO()
339 339 stats_stream = stats.stream
340 340 try:
341 341 stats.stream = stdout_trap
342 342 stats.print_stats(*lims)
343 343 finally:
344 344 stats.stream = stats_stream
345 345
346 346 output = stdout_trap.getvalue()
347 347 output = output.rstrip()
348 348
349 349 if 'q' not in opts:
350 350 page.page(output)
351 351 print(sys_exit, end=' ')
352 352
353 353 dump_file = opts.D[0]
354 354 text_file = opts.T[0]
355 355 if dump_file:
356 356 prof.dump_stats(dump_file)
357 357 print(
358 358 f"\n*** Profile stats marshalled to file {repr(dump_file)}.{sys_exit}"
359 359 )
360 360 if text_file:
361 361 pfile = Path(text_file)
362 362 pfile.touch(exist_ok=True)
363 363 pfile.write_text(output)
364 364
365 365 print(
366 366 f"\n*** Profile printout saved to text file {repr(text_file)}.{sys_exit}"
367 367 )
368 368
369 369 if 'r' in opts:
370 370 return stats
371 371
372 372 return None
373 373
374 374 @line_magic
375 375 def pdb(self, parameter_s=''):
376 376 """Control the automatic calling of the pdb interactive debugger.
377 377
378 378 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
379 379 argument it works as a toggle.
380 380
381 381 When an exception is triggered, IPython can optionally call the
382 382 interactive pdb debugger after the traceback printout. %pdb toggles
383 383 this feature on and off.
384 384
385 385 The initial state of this feature is set in your configuration
386 386 file (the option is ``InteractiveShell.pdb``).
387 387
388 388 If you want to just activate the debugger AFTER an exception has fired,
389 389 without having to type '%pdb on' and rerunning your code, you can use
390 390 the %debug magic."""
391 391
392 392 par = parameter_s.strip().lower()
393 393
394 394 if par:
395 395 try:
396 396 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
397 397 except KeyError:
398 398 print ('Incorrect argument. Use on/1, off/0, '
399 399 'or nothing for a toggle.')
400 400 return
401 401 else:
402 402 # toggle
403 403 new_pdb = not self.shell.call_pdb
404 404
405 405 # set on the shell
406 406 self.shell.call_pdb = new_pdb
407 407 print('Automatic pdb calling has been turned',on_off(new_pdb))
408 408
409 409 @magic_arguments.magic_arguments()
410 410 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
411 411 help="""
412 412 Set break point at LINE in FILE.
413 413 """
414 414 )
415 415 @magic_arguments.argument('statement', nargs='*',
416 416 help="""
417 417 Code to run in debugger.
418 418 You can omit this in cell magic mode.
419 419 """
420 420 )
421 421 @no_var_expand
422 422 @line_cell_magic
423 423 def debug(self, line='', cell=None):
424 424 """Activate the interactive debugger.
425 425
426 426 This magic command support two ways of activating debugger.
427 427 One is to activate debugger before executing code. This way, you
428 428 can set a break point, to step through the code from the point.
429 429 You can use this mode by giving statements to execute and optionally
430 430 a breakpoint.
431 431
432 432 The other one is to activate debugger in post-mortem mode. You can
433 433 activate this mode simply running %debug without any argument.
434 434 If an exception has just occurred, this lets you inspect its stack
435 435 frames interactively. Note that this will always work only on the last
436 436 traceback that occurred, so you must call this quickly after an
437 437 exception that you wish to inspect has fired, because if another one
438 438 occurs, it clobbers the previous one.
439 439
440 440 If you want IPython to automatically do this on every exception, see
441 441 the %pdb magic for more details.
442 442
443 443 .. versionchanged:: 7.3
444 444 When running code, user variables are no longer expanded,
445 445 the magic line is always left unmodified.
446 446
447 447 """
448 448 args = magic_arguments.parse_argstring(self.debug, line)
449 449
450 450 if not (args.breakpoint or args.statement or cell):
451 451 self._debug_post_mortem()
452 452 elif not (args.breakpoint or cell):
453 453 # If there is no breakpoints, the line is just code to execute
454 454 self._debug_exec(line, None)
455 455 else:
456 456 # Here we try to reconstruct the code from the output of
457 457 # parse_argstring. This might not work if the code has spaces
458 458 # For example this fails for `print("a b")`
459 459 code = "\n".join(args.statement)
460 460 if cell:
461 461 code += "\n" + cell
462 462 self._debug_exec(code, args.breakpoint)
463 463
464 464 def _debug_post_mortem(self):
465 465 self.shell.debugger(force=True)
466 466
467 467 def _debug_exec(self, code, breakpoint):
468 468 if breakpoint:
469 469 (filename, bp_line) = breakpoint.rsplit(':', 1)
470 470 bp_line = int(bp_line)
471 471 else:
472 472 (filename, bp_line) = (None, None)
473 473 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
474 474
475 475 @line_magic
476 476 def tb(self, s):
477 477 """Print the last traceback.
478 478
479 479 Optionally, specify an exception reporting mode, tuning the
480 480 verbosity of the traceback. By default the currently-active exception
481 481 mode is used. See %xmode for changing exception reporting modes.
482 482
483 483 Valid modes: Plain, Context, Verbose, and Minimal.
484 484 """
485 485 interactive_tb = self.shell.InteractiveTB
486 486 if s:
487 487 # Switch exception reporting mode for this one call.
488 488 # Ensure it is switched back.
489 489 def xmode_switch_err(name):
490 490 warn('Error changing %s exception modes.\n%s' %
491 491 (name,sys.exc_info()[1]))
492 492
493 493 new_mode = s.strip().capitalize()
494 494 original_mode = interactive_tb.mode
495 495 try:
496 496 try:
497 497 interactive_tb.set_mode(mode=new_mode)
498 498 except Exception:
499 499 xmode_switch_err('user')
500 500 else:
501 501 self.shell.showtraceback()
502 502 finally:
503 503 interactive_tb.set_mode(mode=original_mode)
504 504 else:
505 505 self.shell.showtraceback()
506 506
507 507 @skip_doctest
508 508 @line_magic
509 509 def run(self, parameter_s='', runner=None,
510 510 file_finder=get_py_filename):
511 511 """Run the named file inside IPython as a program.
512 512
513 513 Usage::
514 514
515 515 %run [-n -i -e -G]
516 516 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
517 517 ( -m mod | filename ) [args]
518 518
519 519 The filename argument should be either a pure Python script (with
520 520 extension ``.py``), or a file with custom IPython syntax (such as
521 521 magics). If the latter, the file can be either a script with ``.ipy``
522 522 extension, or a Jupyter notebook with ``.ipynb`` extension. When running
523 523 a Jupyter notebook, the output from print statements and other
524 524 displayed objects will appear in the terminal (even matplotlib figures
525 525 will open, if a terminal-compliant backend is being used). Note that,
526 526 at the system command line, the ``jupyter run`` command offers similar
527 527 functionality for executing notebooks (albeit currently with some
528 528 differences in supported options).
529 529
530 530 Parameters after the filename are passed as command-line arguments to
531 531 the program (put in sys.argv). Then, control returns to IPython's
532 532 prompt.
533 533
534 534 This is similar to running at a system prompt ``python file args``,
535 535 but with the advantage of giving you IPython's tracebacks, and of
536 536 loading all variables into your interactive namespace for further use
537 537 (unless -p is used, see below).
538 538
539 539 The file is executed in a namespace initially consisting only of
540 540 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
541 541 sees its environment as if it were being run as a stand-alone program
542 542 (except for sharing global objects such as previously imported
543 543 modules). But after execution, the IPython interactive namespace gets
544 544 updated with all variables defined in the program (except for __name__
545 545 and sys.argv). This allows for very convenient loading of code for
546 546 interactive work, while giving each program a 'clean sheet' to run in.
547 547
548 548 Arguments are expanded using shell-like glob match. Patterns
549 549 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
550 550 tilde '~' will be expanded into user's home directory. Unlike
551 551 real shells, quotation does not suppress expansions. Use
552 552 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
553 553 To completely disable these expansions, you can use -G flag.
554 554
555 555 On Windows systems, the use of single quotes `'` when specifying
556 556 a file is not supported. Use double quotes `"`.
557 557
558 558 Options:
559 559
560 560 -n
561 561 __name__ is NOT set to '__main__', but to the running file's name
562 562 without extension (as python does under import). This allows running
563 563 scripts and reloading the definitions in them without calling code
564 564 protected by an ``if __name__ == "__main__"`` clause.
565 565
566 566 -i
567 567 run the file in IPython's namespace instead of an empty one. This
568 568 is useful if you are experimenting with code written in a text editor
569 569 which depends on variables defined interactively.
570 570
571 571 -e
572 572 ignore sys.exit() calls or SystemExit exceptions in the script
573 573 being run. This is particularly useful if IPython is being used to
574 574 run unittests, which always exit with a sys.exit() call. In such
575 575 cases you are interested in the output of the test results, not in
576 576 seeing a traceback of the unittest module.
577 577
578 578 -t
579 579 print timing information at the end of the run. IPython will give
580 580 you an estimated CPU time consumption for your script, which under
581 581 Unix uses the resource module to avoid the wraparound problems of
582 582 time.clock(). Under Unix, an estimate of time spent on system tasks
583 583 is also given (for Windows platforms this is reported as 0.0).
584 584
585 585 If -t is given, an additional ``-N<N>`` option can be given, where <N>
586 586 must be an integer indicating how many times you want the script to
587 587 run. The final timing report will include total and per run results.
588 588
589 589 For example (testing the script uniq_stable.py)::
590 590
591 591 In [1]: run -t uniq_stable
592 592
593 593 IPython CPU timings (estimated):
594 594 User : 0.19597 s.
595 595 System: 0.0 s.
596 596
597 597 In [2]: run -t -N5 uniq_stable
598 598
599 599 IPython CPU timings (estimated):
600 600 Total runs performed: 5
601 601 Times : Total Per run
602 602 User : 0.910862 s, 0.1821724 s.
603 603 System: 0.0 s, 0.0 s.
604 604
605 605 -d
606 606 run your program under the control of pdb, the Python debugger.
607 607 This allows you to execute your program step by step, watch variables,
608 608 etc. Internally, what IPython does is similar to calling::
609 609
610 610 pdb.run('execfile("YOURFILENAME")')
611 611
612 612 with a breakpoint set on line 1 of your file. You can change the line
613 613 number for this automatic breakpoint to be <N> by using the -bN option
614 614 (where N must be an integer). For example::
615 615
616 616 %run -d -b40 myscript
617 617
618 618 will set the first breakpoint at line 40 in myscript.py. Note that
619 619 the first breakpoint must be set on a line which actually does
620 620 something (not a comment or docstring) for it to stop execution.
621 621
622 622 Or you can specify a breakpoint in a different file::
623 623
624 624 %run -d -b myotherfile.py:20 myscript
625 625
626 626 When the pdb debugger starts, you will see a (Pdb) prompt. You must
627 627 first enter 'c' (without quotes) to start execution up to the first
628 628 breakpoint.
629 629
630 630 Entering 'help' gives information about the use of the debugger. You
631 631 can easily see pdb's full documentation with "import pdb;pdb.help()"
632 632 at a prompt.
633 633
634 634 -p
635 635 run program under the control of the Python profiler module (which
636 636 prints a detailed report of execution times, function calls, etc).
637 637
638 638 You can pass other options after -p which affect the behavior of the
639 639 profiler itself. See the docs for %prun for details.
640 640
641 641 In this mode, the program's variables do NOT propagate back to the
642 642 IPython interactive namespace (because they remain in the namespace
643 643 where the profiler executes them).
644 644
645 645 Internally this triggers a call to %prun, see its documentation for
646 646 details on the options available specifically for profiling.
647 647
648 648 There is one special usage for which the text above doesn't apply:
649 649 if the filename ends with .ipy[nb], the file is run as ipython script,
650 650 just as if the commands were written on IPython prompt.
651 651
652 652 -m
653 653 specify module name to load instead of script path. Similar to
654 654 the -m option for the python interpreter. Use this option last if you
655 655 want to combine with other %run options. Unlike the python interpreter
656 656 only source modules are allowed no .pyc or .pyo files.
657 657 For example::
658 658
659 659 %run -m example
660 660
661 661 will run the example module.
662 662
663 663 -G
664 664 disable shell-like glob expansion of arguments.
665 665
666 666 """
667 667
668 668 # Logic to handle issue #3664
669 669 # Add '--' after '-m <module_name>' to ignore additional args passed to a module.
670 670 if '-m' in parameter_s and '--' not in parameter_s:
671 671 argv = shlex.split(parameter_s, posix=(os.name == 'posix'))
672 672 for idx, arg in enumerate(argv):
673 673 if arg and arg.startswith('-') and arg != '-':
674 674 if arg == '-m':
675 675 argv.insert(idx + 2, '--')
676 676 break
677 677 else:
678 678 # Positional arg, break
679 679 break
680 680 parameter_s = ' '.join(shlex.quote(arg) for arg in argv)
681 681
682 682 # get arguments and set sys.argv for program to be run.
683 683 opts, arg_lst = self.parse_options(parameter_s,
684 684 'nidtN:b:pD:l:rs:T:em:G',
685 685 mode='list', list_all=1)
686 686 if "m" in opts:
687 687 modulename = opts["m"][0]
688 688 modpath = find_mod(modulename)
689 689 if modpath is None:
690 690 msg = '%r is not a valid modulename on sys.path'%modulename
691 691 raise Exception(msg)
692 692 arg_lst = [modpath] + arg_lst
693 693 try:
694 694 fpath = None # initialize to make sure fpath is in scope later
695 695 fpath = arg_lst[0]
696 696 filename = file_finder(fpath)
697 697 except IndexError as e:
698 698 msg = 'you must provide at least a filename.'
699 699 raise Exception(msg) from e
700 700 except IOError as e:
701 701 try:
702 702 msg = str(e)
703 703 except UnicodeError:
704 704 msg = e.message
705 705 if os.name == 'nt' and re.match(r"^'.*'$",fpath):
706 706 warn('For Windows, use double quotes to wrap a filename: %run "mypath\\myfile.py"')
707 707 raise Exception(msg) from e
708 708 except TypeError:
709 709 if fpath in sys.meta_path:
710 710 filename = ""
711 711 else:
712 712 raise
713 713
714 714 if filename.lower().endswith(('.ipy', '.ipynb')):
715 715 with preserve_keys(self.shell.user_ns, '__file__'):
716 716 self.shell.user_ns['__file__'] = filename
717 717 self.shell.safe_execfile_ipy(filename, raise_exceptions=True)
718 718 return
719 719
720 720 # Control the response to exit() calls made by the script being run
721 721 exit_ignore = 'e' in opts
722 722
723 723 # Make sure that the running script gets a proper sys.argv as if it
724 724 # were run from a system shell.
725 725 save_argv = sys.argv # save it for later restoring
726 726
727 727 if 'G' in opts:
728 728 args = arg_lst[1:]
729 729 else:
730 730 # tilde and glob expansion
731 731 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
732 732
733 733 sys.argv = [filename] + args # put in the proper filename
734 734
735 735 if 'n' in opts:
736 736 name = Path(filename).stem
737 737 else:
738 738 name = '__main__'
739 739
740 740 if 'i' in opts:
741 741 # Run in user's interactive namespace
742 742 prog_ns = self.shell.user_ns
743 743 __name__save = self.shell.user_ns['__name__']
744 744 prog_ns['__name__'] = name
745 745 main_mod = self.shell.user_module
746 746
747 747 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
748 748 # set the __file__ global in the script's namespace
749 749 # TK: Is this necessary in interactive mode?
750 750 prog_ns['__file__'] = filename
751 751 else:
752 752 # Run in a fresh, empty namespace
753 753
754 754 # The shell MUST hold a reference to prog_ns so after %run
755 755 # exits, the python deletion mechanism doesn't zero it out
756 756 # (leaving dangling references). See interactiveshell for details
757 757 main_mod = self.shell.new_main_mod(filename, name)
758 758 prog_ns = main_mod.__dict__
759 759
760 760 # pickle fix. See interactiveshell for an explanation. But we need to
761 761 # make sure that, if we overwrite __main__, we replace it at the end
762 762 main_mod_name = prog_ns['__name__']
763 763
764 764 if main_mod_name == '__main__':
765 765 restore_main = sys.modules['__main__']
766 766 else:
767 767 restore_main = False
768 768
769 769 # This needs to be undone at the end to prevent holding references to
770 770 # every single object ever created.
771 771 sys.modules[main_mod_name] = main_mod
772 772
773 773 if 'p' in opts or 'd' in opts:
774 774 if 'm' in opts:
775 775 code = 'run_module(modulename, prog_ns)'
776 776 code_ns = {
777 777 'run_module': self.shell.safe_run_module,
778 778 'prog_ns': prog_ns,
779 779 'modulename': modulename,
780 780 }
781 781 else:
782 782 if 'd' in opts:
783 783 # allow exceptions to raise in debug mode
784 784 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
785 785 else:
786 786 code = 'execfile(filename, prog_ns)'
787 787 code_ns = {
788 788 'execfile': self.shell.safe_execfile,
789 789 'prog_ns': prog_ns,
790 790 'filename': get_py_filename(filename),
791 791 }
792 792
793 793 try:
794 794 stats = None
795 795 if 'p' in opts:
796 796 stats = self._run_with_profiler(code, opts, code_ns)
797 797 else:
798 798 if 'd' in opts:
799 799 bp_file, bp_line = parse_breakpoint(
800 800 opts.get('b', ['1'])[0], filename)
801 801 self._run_with_debugger(
802 802 code, code_ns, filename, bp_line, bp_file)
803 803 else:
804 804 if 'm' in opts:
805 805 def run():
806 806 self.shell.safe_run_module(modulename, prog_ns)
807 807 else:
808 808 if runner is None:
809 809 runner = self.default_runner
810 810 if runner is None:
811 811 runner = self.shell.safe_execfile
812 812
813 813 def run():
814 814 runner(filename, prog_ns, prog_ns,
815 815 exit_ignore=exit_ignore)
816 816
817 817 if 't' in opts:
818 818 # timed execution
819 819 try:
820 820 nruns = int(opts['N'][0])
821 821 if nruns < 1:
822 822 error('Number of runs must be >=1')
823 823 return
824 824 except (KeyError):
825 825 nruns = 1
826 826 self._run_with_timing(run, nruns)
827 827 else:
828 828 # regular execution
829 829 run()
830 830
831 831 if 'i' in opts:
832 832 self.shell.user_ns['__name__'] = __name__save
833 833 else:
834 834 # update IPython interactive namespace
835 835
836 836 # Some forms of read errors on the file may mean the
837 837 # __name__ key was never set; using pop we don't have to
838 838 # worry about a possible KeyError.
839 839 prog_ns.pop('__name__', None)
840 840
841 841 with preserve_keys(self.shell.user_ns, '__file__'):
842 842 self.shell.user_ns.update(prog_ns)
843 843 finally:
844 844 # It's a bit of a mystery why, but __builtins__ can change from
845 845 # being a module to becoming a dict missing some key data after
846 846 # %run. As best I can see, this is NOT something IPython is doing
847 847 # at all, and similar problems have been reported before:
848 848 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
849 849 # Since this seems to be done by the interpreter itself, the best
850 850 # we can do is to at least restore __builtins__ for the user on
851 851 # exit.
852 852 self.shell.user_ns['__builtins__'] = builtin_mod
853 853
854 854 # Ensure key global structures are restored
855 855 sys.argv = save_argv
856 856 if restore_main:
857 857 sys.modules['__main__'] = restore_main
858 858 if '__mp_main__' in sys.modules:
859 859 sys.modules['__mp_main__'] = restore_main
860 860 else:
861 861 # Remove from sys.modules the reference to main_mod we'd
862 862 # added. Otherwise it will trap references to objects
863 863 # contained therein.
864 864 del sys.modules[main_mod_name]
865 865
866 866 return stats
867 867
868 868 def _run_with_debugger(self, code, code_ns, filename=None,
869 869 bp_line=None, bp_file=None):
870 870 """
871 871 Run `code` in debugger with a break point.
872 872
873 873 Parameters
874 874 ----------
875 875 code : str
876 876 Code to execute.
877 877 code_ns : dict
878 878 A namespace in which `code` is executed.
879 879 filename : str
880 880 `code` is ran as if it is in `filename`.
881 881 bp_line : int, optional
882 882 Line number of the break point.
883 883 bp_file : str, optional
884 884 Path to the file in which break point is specified.
885 885 `filename` is used if not given.
886 886
887 887 Raises
888 888 ------
889 889 UsageError
890 890 If the break point given by `bp_line` is not valid.
891 891
892 892 """
893 893 deb = self.shell.InteractiveTB.pdb
894 894 if not deb:
895 895 self.shell.InteractiveTB.pdb = self.shell.InteractiveTB.debugger_cls()
896 896 deb = self.shell.InteractiveTB.pdb
897 897
898 898 # deb.checkline() fails if deb.curframe exists but is None; it can
899 899 # handle it not existing. https://github.com/ipython/ipython/issues/10028
900 900 if hasattr(deb, 'curframe'):
901 901 del deb.curframe
902 902
903 903 # reset Breakpoint state, which is moronically kept
904 904 # in a class
905 905 bdb.Breakpoint.next = 1
906 906 bdb.Breakpoint.bplist = {}
907 907 bdb.Breakpoint.bpbynumber = [None]
908 908 deb.clear_all_breaks()
909 909 if bp_line is not None:
910 910 # Set an initial breakpoint to stop execution
911 911 maxtries = 10
912 912 bp_file = bp_file or filename
913 913 checkline = deb.checkline(bp_file, bp_line)
914 914 if not checkline:
915 915 for bp in range(bp_line + 1, bp_line + maxtries + 1):
916 916 if deb.checkline(bp_file, bp):
917 917 break
918 918 else:
919 919 msg = ("\nI failed to find a valid line to set "
920 920 "a breakpoint\n"
921 921 "after trying up to line: %s.\n"
922 922 "Please set a valid breakpoint manually "
923 923 "with the -b option." % bp)
924 924 raise UsageError(msg)
925 925 # if we find a good linenumber, set the breakpoint
926 926 deb.do_break('%s:%s' % (bp_file, bp_line))
927 927
928 928 if filename:
929 929 # Mimic Pdb._runscript(...)
930 930 deb._wait_for_mainpyfile = True
931 931 deb.mainpyfile = deb.canonic(filename)
932 932
933 933 # Start file run
934 934 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
935 935 try:
936 936 if filename:
937 937 # save filename so it can be used by methods on the deb object
938 938 deb._exec_filename = filename
939 939 while True:
940 940 try:
941 941 trace = sys.gettrace()
942 942 deb.run(code, code_ns)
943 943 except Restart:
944 944 print("Restarting")
945 945 if filename:
946 946 deb._wait_for_mainpyfile = True
947 947 deb.mainpyfile = deb.canonic(filename)
948 948 continue
949 949 else:
950 950 break
951 951 finally:
952 952 sys.settrace(trace)
953 953
954 954
955 955 except:
956 956 etype, value, tb = sys.exc_info()
957 957 # Skip three frames in the traceback: the %run one,
958 958 # one inside bdb.py, and the command-line typed by the
959 959 # user (run by exec in pdb itself).
960 960 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
961 961
962 962 @staticmethod
963 963 def _run_with_timing(run, nruns):
964 964 """
965 965 Run function `run` and print timing information.
966 966
967 967 Parameters
968 968 ----------
969 969 run : callable
970 970 Any callable object which takes no argument.
971 971 nruns : int
972 972 Number of times to execute `run`.
973 973
974 974 """
975 975 twall0 = time.perf_counter()
976 976 if nruns == 1:
977 977 t0 = clock2()
978 978 run()
979 979 t1 = clock2()
980 980 t_usr = t1[0] - t0[0]
981 981 t_sys = t1[1] - t0[1]
982 982 print("\nIPython CPU timings (estimated):")
983 983 print(" User : %10.2f s." % t_usr)
984 984 print(" System : %10.2f s." % t_sys)
985 985 else:
986 986 runs = range(nruns)
987 987 t0 = clock2()
988 988 for nr in runs:
989 989 run()
990 990 t1 = clock2()
991 991 t_usr = t1[0] - t0[0]
992 992 t_sys = t1[1] - t0[1]
993 993 print("\nIPython CPU timings (estimated):")
994 994 print("Total runs performed:", nruns)
995 995 print(" Times : %10s %10s" % ('Total', 'Per run'))
996 996 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
997 997 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
998 998 twall1 = time.perf_counter()
999 999 print("Wall time: %10.2f s." % (twall1 - twall0))
1000 1000
1001 1001 @skip_doctest
1002 1002 @no_var_expand
1003 1003 @line_cell_magic
1004 1004 @needs_local_scope
1005 1005 def timeit(self, line='', cell=None, local_ns=None):
1006 1006 """Time execution of a Python statement or expression
1007 1007
1008 1008 Usage, in line mode:
1009 1009 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
1010 1010 or in cell mode:
1011 1011 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
1012 1012 code
1013 1013 code...
1014 1014
1015 1015 Time execution of a Python statement or expression using the timeit
1016 1016 module. This function can be used both as a line and cell magic:
1017 1017
1018 1018 - In line mode you can time a single-line statement (though multiple
1019 1019 ones can be chained with using semicolons).
1020 1020
1021 1021 - In cell mode, the statement in the first line is used as setup code
1022 1022 (executed but not timed) and the body of the cell is timed. The cell
1023 1023 body has access to any variables created in the setup code.
1024 1024
1025 1025 Options:
1026 1026 -n<N>: execute the given statement <N> times in a loop. If <N> is not
1027 1027 provided, <N> is determined so as to get sufficient accuracy.
1028 1028
1029 1029 -r<R>: number of repeats <R>, each consisting of <N> loops, and take the
1030 1030 best result.
1031 1031 Default: 7
1032 1032
1033 1033 -t: use time.time to measure the time, which is the default on Unix.
1034 1034 This function measures wall time.
1035 1035
1036 1036 -c: use time.clock to measure the time, which is the default on
1037 1037 Windows and measures wall time. On Unix, resource.getrusage is used
1038 1038 instead and returns the CPU user time.
1039 1039
1040 1040 -p<P>: use a precision of <P> digits to display the timing result.
1041 1041 Default: 3
1042 1042
1043 1043 -q: Quiet, do not print result.
1044 1044
1045 1045 -o: return a TimeitResult that can be stored in a variable to inspect
1046 1046 the result in more details.
1047 1047
1048 1048 .. versionchanged:: 7.3
1049 1049 User variables are no longer expanded,
1050 1050 the magic line is always left unmodified.
1051 1051
1052 1052 Examples
1053 1053 --------
1054 1054 ::
1055 1055
1056 1056 In [1]: %timeit pass
1057 1057 8.26 ns Β± 0.12 ns per loop (mean Β± std. dev. of 7 runs, 100000000 loops each)
1058 1058
1059 1059 In [2]: u = None
1060 1060
1061 1061 In [3]: %timeit u is None
1062 1062 29.9 ns Β± 0.643 ns per loop (mean Β± std. dev. of 7 runs, 10000000 loops each)
1063 1063
1064 1064 In [4]: %timeit -r 4 u == None
1065 1065
1066 1066 In [5]: import time
1067 1067
1068 1068 In [6]: %timeit -n1 time.sleep(2)
1069 1069
1070
1071 1070 The times reported by %timeit will be slightly higher than those
1072 1071 reported by the timeit.py script when variables are accessed. This is
1073 1072 due to the fact that %timeit executes the statement in the namespace
1074 1073 of the shell, compared with timeit.py, which uses a single setup
1075 1074 statement to import function or create variables. Generally, the bias
1076 1075 does not matter as long as results from timeit.py are not mixed with
1077 1076 those from %timeit."""
1078 1077
1079 1078 opts, stmt = self.parse_options(
1080 1079 line, "n:r:tcp:qo", posix=False, strict=False, preserve_non_opts=True
1081 1080 )
1082 1081 if stmt == "" and cell is None:
1083 1082 return
1084 1083
1085 1084 timefunc = timeit.default_timer
1086 1085 number = int(getattr(opts, "n", 0))
1087 1086 default_repeat = 7 if timeit.default_repeat < 7 else timeit.default_repeat
1088 1087 repeat = int(getattr(opts, "r", default_repeat))
1089 1088 precision = int(getattr(opts, "p", 3))
1090 1089 quiet = 'q' in opts
1091 1090 return_result = 'o' in opts
1092 1091 if hasattr(opts, "t"):
1093 1092 timefunc = time.time
1094 1093 if hasattr(opts, "c"):
1095 1094 timefunc = clock
1096 1095
1097 1096 timer = Timer(timer=timefunc)
1098 1097 # this code has tight coupling to the inner workings of timeit.Timer,
1099 1098 # but is there a better way to achieve that the code stmt has access
1100 1099 # to the shell namespace?
1101 1100 transform = self.shell.transform_cell
1102 1101
1103 1102 if cell is None:
1104 1103 # called as line magic
1105 1104 ast_setup = self.shell.compile.ast_parse("pass")
1106 1105 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1107 1106 else:
1108 1107 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1109 1108 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1110 1109
1111 1110 ast_setup = self.shell.transform_ast(ast_setup)
1112 1111 ast_stmt = self.shell.transform_ast(ast_stmt)
1113 1112
1114 1113 # Check that these compile to valid Python code *outside* the timer func
1115 1114 # Invalid code may become valid when put inside the function & loop,
1116 1115 # which messes up error messages.
1117 1116 # https://github.com/ipython/ipython/issues/10636
1118 1117 self.shell.compile(ast_setup, "<magic-timeit-setup>", "exec")
1119 1118 self.shell.compile(ast_stmt, "<magic-timeit-stmt>", "exec")
1120 1119
1121 1120 # This codestring is taken from timeit.template - we fill it in as an
1122 1121 # AST, so that we can apply our AST transformations to the user code
1123 1122 # without affecting the timing code.
1124 1123 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1125 1124 ' setup\n'
1126 1125 ' _t0 = _timer()\n'
1127 1126 ' for _i in _it:\n'
1128 1127 ' stmt\n'
1129 1128 ' _t1 = _timer()\n'
1130 1129 ' return _t1 - _t0\n')
1131 1130
1132 1131 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1133 1132 timeit_ast = ast.fix_missing_locations(timeit_ast)
1134 1133
1135 1134 # Track compilation time so it can be reported if too long
1136 1135 # Minimum time above which compilation time will be reported
1137 1136 tc_min = 0.1
1138 1137
1139 1138 t0 = clock()
1140 1139 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1141 1140 tc = clock()-t0
1142 1141
1143 1142 ns = {}
1144 1143 glob = self.shell.user_ns
1145 1144 # handles global vars with same name as local vars. We store them in conflict_globs.
1146 1145 conflict_globs = {}
1147 1146 if local_ns and cell is None:
1148 1147 for var_name, var_val in glob.items():
1149 1148 if var_name in local_ns:
1150 1149 conflict_globs[var_name] = var_val
1151 1150 glob.update(local_ns)
1152 1151
1153 1152 exec(code, glob, ns)
1154 1153 timer.inner = ns["inner"]
1155 1154
1156 1155 # This is used to check if there is a huge difference between the
1157 1156 # best and worst timings.
1158 1157 # Issue: https://github.com/ipython/ipython/issues/6471
1159 1158 if number == 0:
1160 1159 # determine number so that 0.2 <= total time < 2.0
1161 1160 for index in range(0, 10):
1162 1161 number = 10 ** index
1163 1162 time_number = timer.timeit(number)
1164 1163 if time_number >= 0.2:
1165 1164 break
1166 1165
1167 1166 all_runs = timer.repeat(repeat, number)
1168 1167 best = min(all_runs) / number
1169 1168 worst = max(all_runs) / number
1170 1169 timeit_result = TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1171 1170
1172 1171 # Restore global vars from conflict_globs
1173 1172 if conflict_globs:
1174 1173 glob.update(conflict_globs)
1175 1174
1176 1175 if not quiet :
1177 1176 # Check best timing is greater than zero to avoid a
1178 1177 # ZeroDivisionError.
1179 1178 # In cases where the slowest timing is lesser than a microsecond
1180 1179 # we assume that it does not really matter if the fastest
1181 1180 # timing is 4 times faster than the slowest timing or not.
1182 1181 if worst > 4 * best and best > 0 and worst > 1e-6:
1183 1182 print("The slowest run took %0.2f times longer than the "
1184 1183 "fastest. This could mean that an intermediate result "
1185 1184 "is being cached." % (worst / best))
1186 1185
1187 1186 print( timeit_result )
1188 1187
1189 1188 if tc > tc_min:
1190 1189 print("Compiler time: %.2f s" % tc)
1191 1190 if return_result:
1192 1191 return timeit_result
1193 1192
1194 1193 @skip_doctest
1195 1194 @no_var_expand
1196 1195 @needs_local_scope
1197 1196 @line_cell_magic
1198 1197 def time(self,line='', cell=None, local_ns=None):
1199 1198 """Time execution of a Python statement or expression.
1200 1199
1201 1200 The CPU and wall clock times are printed, and the value of the
1202 1201 expression (if any) is returned. Note that under Win32, system time
1203 1202 is always reported as 0, since it can not be measured.
1204
1203
1205 1204 This function can be used both as a line and cell magic:
1206 1205
1207 1206 - In line mode you can time a single-line statement (though multiple
1208 1207 ones can be chained with using semicolons).
1209 1208
1210 1209 - In cell mode, you can time the cell body (a directly
1211 1210 following statement raises an error).
1212 1211
1213 1212 This function provides very basic timing functionality. Use the timeit
1214 1213 magic for more control over the measurement.
1215 1214
1216 1215 .. versionchanged:: 7.3
1217 1216 User variables are no longer expanded,
1218 1217 the magic line is always left unmodified.
1219 1218
1220 1219 Examples
1221 1220 --------
1222 1221 ::
1223 1222
1224 1223 In [1]: %time 2**128
1225 1224 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1226 1225 Wall time: 0.00
1227 1226 Out[1]: 340282366920938463463374607431768211456L
1228 1227
1229 1228 In [2]: n = 1000000
1230 1229
1231 1230 In [3]: %time sum(range(n))
1232 1231 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1233 1232 Wall time: 1.37
1234 1233 Out[3]: 499999500000L
1235 1234
1236 1235 In [4]: %time print 'hello world'
1237 1236 hello world
1238 1237 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1239 1238 Wall time: 0.00
1240 1239
1241
1242 1240 .. note::
1243 1241 The time needed by Python to compile the given expression will be
1244 1242 reported if it is more than 0.1s.
1245 1243
1246 1244 In the example below, the actual exponentiation is done by Python
1247 1245 at compilation time, so while the expression can take a noticeable
1248 1246 amount of time to compute, that time is purely due to the
1249 1247 compilation::
1250 1248
1251 1249 In [5]: %time 3**9999;
1252 1250 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1253 1251 Wall time: 0.00 s
1254 1252
1255 1253 In [6]: %time 3**999999;
1256 1254 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1257 1255 Wall time: 0.00 s
1258 1256 Compiler : 0.78 s
1259 1257 """
1260 1258 # fail immediately if the given expression can't be compiled
1261 1259
1262 1260 if line and cell:
1263 1261 raise UsageError("Can't use statement directly after '%%time'!")
1264 1262
1265 1263 if cell:
1266 1264 expr = self.shell.transform_cell(cell)
1267 1265 else:
1268 1266 expr = self.shell.transform_cell(line)
1269 1267
1270 1268 # Minimum time above which parse time will be reported
1271 1269 tp_min = 0.1
1272 1270
1273 1271 t0 = clock()
1274 1272 expr_ast = self.shell.compile.ast_parse(expr)
1275 1273 tp = clock()-t0
1276 1274
1277 1275 # Apply AST transformations
1278 1276 expr_ast = self.shell.transform_ast(expr_ast)
1279 1277
1280 1278 # Minimum time above which compilation time will be reported
1281 1279 tc_min = 0.1
1282 1280
1283 1281 expr_val=None
1284 1282 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1285 1283 mode = 'eval'
1286 1284 source = '<timed eval>'
1287 1285 expr_ast = ast.Expression(expr_ast.body[0].value)
1288 1286 else:
1289 1287 mode = 'exec'
1290 1288 source = '<timed exec>'
1291 1289 # multi-line %%time case
1292 1290 if len(expr_ast.body) > 1 and isinstance(expr_ast.body[-1], ast.Expr):
1293 1291 expr_val= expr_ast.body[-1]
1294 1292 expr_ast = expr_ast.body[:-1]
1295 1293 expr_ast = Module(expr_ast, [])
1296 1294 expr_val = ast.Expression(expr_val.value)
1297 1295
1298 1296 t0 = clock()
1299 1297 code = self.shell.compile(expr_ast, source, mode)
1300 1298 tc = clock()-t0
1301 1299
1302 1300 # skew measurement as little as possible
1303 1301 glob = self.shell.user_ns
1304 1302 wtime = time.time
1305 1303 # time execution
1306 1304 wall_st = wtime()
1307 1305 if mode=='eval':
1308 1306 st = clock2()
1309 1307 try:
1310 1308 out = eval(code, glob, local_ns)
1311 1309 except:
1312 1310 self.shell.showtraceback()
1313 1311 return
1314 1312 end = clock2()
1315 1313 else:
1316 1314 st = clock2()
1317 1315 try:
1318 1316 exec(code, glob, local_ns)
1319 1317 out=None
1320 1318 # multi-line %%time case
1321 1319 if expr_val is not None:
1322 1320 code_2 = self.shell.compile(expr_val, source, 'eval')
1323 1321 out = eval(code_2, glob, local_ns)
1324 1322 except:
1325 1323 self.shell.showtraceback()
1326 1324 return
1327 1325 end = clock2()
1328 1326
1329 1327 wall_end = wtime()
1330 1328 # Compute actual times and report
1331 1329 wall_time = wall_end-wall_st
1332 1330 cpu_user = end[0]-st[0]
1333 1331 cpu_sys = end[1]-st[1]
1334 1332 cpu_tot = cpu_user+cpu_sys
1335 1333 # On windows cpu_sys is always zero, so no new information to the next print
1336 1334 if sys.platform != 'win32':
1337 1335 print("CPU times: user %s, sys: %s, total: %s" % \
1338 1336 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1339 1337 print("Wall time: %s" % _format_time(wall_time))
1340 1338 if tc > tc_min:
1341 1339 print("Compiler : %s" % _format_time(tc))
1342 1340 if tp > tp_min:
1343 1341 print("Parser : %s" % _format_time(tp))
1344 1342 return out
1345 1343
1346 1344 @skip_doctest
1347 1345 @line_magic
1348 1346 def macro(self, parameter_s=''):
1349 1347 """Define a macro for future re-execution. It accepts ranges of history,
1350 1348 filenames or string objects.
1351 1349
1352 1350 Usage:\\
1353 1351 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1354 1352
1355 1353 Options:
1356 1354
1357 1355 -r: use 'raw' input. By default, the 'processed' history is used,
1358 1356 so that magics are loaded in their transformed version to valid
1359 1357 Python. If this option is given, the raw input as typed at the
1360 1358 command line is used instead.
1361 1359
1362 1360 -q: quiet macro definition. By default, a tag line is printed
1363 1361 to indicate the macro has been created, and then the contents of
1364 1362 the macro are printed. If this option is given, then no printout
1365 1363 is produced once the macro is created.
1366 1364
1367 1365 This will define a global variable called `name` which is a string
1368 1366 made of joining the slices and lines you specify (n1,n2,... numbers
1369 1367 above) from your input history into a single string. This variable
1370 1368 acts like an automatic function which re-executes those lines as if
1371 1369 you had typed them. You just type 'name' at the prompt and the code
1372 1370 executes.
1373 1371
1374 1372 The syntax for indicating input ranges is described in %history.
1375 1373
1376 1374 Note: as a 'hidden' feature, you can also use traditional python slice
1377 1375 notation, where N:M means numbers N through M-1.
1378 1376
1379 1377 For example, if your history contains (print using %hist -n )::
1380 1378
1381 1379 44: x=1
1382 1380 45: y=3
1383 1381 46: z=x+y
1384 1382 47: print x
1385 1383 48: a=5
1386 1384 49: print 'x',x,'y',y
1387 1385
1388 1386 you can create a macro with lines 44 through 47 (included) and line 49
1389 1387 called my_macro with::
1390 1388
1391 1389 In [55]: %macro my_macro 44-47 49
1392 1390
1393 1391 Now, typing `my_macro` (without quotes) will re-execute all this code
1394 1392 in one pass.
1395 1393
1396 1394 You don't need to give the line-numbers in order, and any given line
1397 1395 number can appear multiple times. You can assemble macros with any
1398 1396 lines from your input history in any order.
1399 1397
1400 1398 The macro is a simple object which holds its value in an attribute,
1401 1399 but IPython's display system checks for macros and executes them as
1402 1400 code instead of printing them when you type their name.
1403 1401
1404 1402 You can view a macro's contents by explicitly printing it with::
1405 1403
1406 1404 print macro_name
1407 1405
1408 1406 """
1409 1407 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1410 1408 if not args: # List existing macros
1411 1409 return sorted(k for k,v in self.shell.user_ns.items() if isinstance(v, Macro))
1412 1410 if len(args) == 1:
1413 1411 raise UsageError(
1414 1412 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1415 1413 name, codefrom = args[0], " ".join(args[1:])
1416 1414
1417 1415 #print 'rng',ranges # dbg
1418 1416 try:
1419 1417 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1420 1418 except (ValueError, TypeError) as e:
1421 1419 print(e.args[0])
1422 1420 return
1423 1421 macro = Macro(lines)
1424 1422 self.shell.define_macro(name, macro)
1425 1423 if not ( 'q' in opts) :
1426 1424 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1427 1425 print('=== Macro contents: ===')
1428 1426 print(macro, end=' ')
1429 1427
1430 1428 @magic_arguments.magic_arguments()
1431 1429 @magic_arguments.argument('output', type=str, default='', nargs='?',
1432 1430 help="""The name of the variable in which to store output.
1433 1431 This is a utils.io.CapturedIO object with stdout/err attributes
1434 1432 for the text of the captured output.
1435 1433
1436 1434 CapturedOutput also has a show() method for displaying the output,
1437 1435 and __call__ as well, so you can use that to quickly display the
1438 1436 output.
1439 1437
1440 1438 If unspecified, captured output is discarded.
1441 1439 """
1442 1440 )
1443 1441 @magic_arguments.argument('--no-stderr', action="store_true",
1444 1442 help="""Don't capture stderr."""
1445 1443 )
1446 1444 @magic_arguments.argument('--no-stdout', action="store_true",
1447 1445 help="""Don't capture stdout."""
1448 1446 )
1449 1447 @magic_arguments.argument('--no-display', action="store_true",
1450 1448 help="""Don't capture IPython's rich display."""
1451 1449 )
1452 1450 @cell_magic
1453 1451 def capture(self, line, cell):
1454 1452 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1455 1453 args = magic_arguments.parse_argstring(self.capture, line)
1456 1454 out = not args.no_stdout
1457 1455 err = not args.no_stderr
1458 1456 disp = not args.no_display
1459 1457 with capture_output(out, err, disp) as io:
1460 1458 self.shell.run_cell(cell)
1461 1459 if args.output:
1462 1460 self.shell.user_ns[args.output] = io
1463 1461
1464 1462 def parse_breakpoint(text, current_file):
1465 1463 '''Returns (file, line) for file:line and (current_file, line) for line'''
1466 1464 colon = text.find(':')
1467 1465 if colon == -1:
1468 1466 return current_file, int(text)
1469 1467 else:
1470 1468 return text[:colon], int(text[colon+1:])
1471 1469
1472 1470 def _format_time(timespan, precision=3):
1473 1471 """Formats the timespan in a human readable form"""
1474 1472
1475 1473 if timespan >= 60.0:
1476 1474 # we have more than a minute, format that in a human readable form
1477 1475 # Idea from http://snipplr.com/view/5713/
1478 1476 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1479 1477 time = []
1480 1478 leftover = timespan
1481 1479 for suffix, length in parts:
1482 1480 value = int(leftover / length)
1483 1481 if value > 0:
1484 1482 leftover = leftover % length
1485 1483 time.append(u'%s%s' % (str(value), suffix))
1486 1484 if leftover < 1:
1487 1485 break
1488 1486 return " ".join(time)
1489 1487
1490 1488
1491 1489 # Unfortunately the unicode 'micro' symbol can cause problems in
1492 1490 # certain terminals.
1493 1491 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1494 1492 # Try to prevent crashes by being more secure than it needs to
1495 1493 # E.g. eclipse is able to print a Β΅, but has no sys.stdout.encoding set.
1496 1494 units = [u"s", u"ms",u'us',"ns"] # the save value
1497 1495 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1498 1496 try:
1499 1497 u'\xb5'.encode(sys.stdout.encoding)
1500 1498 units = [u"s", u"ms",u'\xb5s',"ns"]
1501 1499 except:
1502 1500 pass
1503 1501 scaling = [1, 1e3, 1e6, 1e9]
1504 1502
1505 1503 if timespan > 0.0:
1506 1504 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1507 1505 else:
1508 1506 order = 3
1509 1507 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
@@ -1,63 +1,63 b''
1 1 """Implementation of magic functions for the extension machinery.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15
16 16 # Our own packages
17 17 from IPython.core.error import UsageError
18 18 from IPython.core.magic import Magics, magics_class, line_magic
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Magic implementation classes
22 22 #-----------------------------------------------------------------------------
23 23
24 24 @magics_class
25 25 class ExtensionMagics(Magics):
26 26 """Magics to manage the IPython extensions system."""
27 27
28 28 @line_magic
29 29 def load_ext(self, module_str):
30 30 """Load an IPython extension by its module name."""
31 31 if not module_str:
32 32 raise UsageError('Missing module name.')
33 33 res = self.shell.extension_manager.load_extension(module_str)
34 34
35 35 if res == 'already loaded':
36 36 print("The %s extension is already loaded. To reload it, use:" % module_str)
37 37 print(" %reload_ext", module_str)
38 38 elif res == 'no load function':
39 39 print("The %s module is not an IPython extension." % module_str)
40 40
41 41 @line_magic
42 42 def unload_ext(self, module_str):
43 43 """Unload an IPython extension by its module name.
44
44
45 45 Not all extensions can be unloaded, only those which define an
46 46 ``unload_ipython_extension`` function.
47 47 """
48 48 if not module_str:
49 49 raise UsageError('Missing module name.')
50 50
51 51 res = self.shell.extension_manager.unload_extension(module_str)
52 52
53 53 if res == 'no unload function':
54 54 print("The %s extension doesn't define how to unload it." % module_str)
55 55 elif res == "not loaded":
56 56 print("The %s extension is not loaded." % module_str)
57 57
58 58 @line_magic
59 59 def reload_ext(self, module_str):
60 60 """Reload an IPython extension by its module name."""
61 61 if not module_str:
62 62 raise UsageError('Missing module name.')
63 63 self.shell.extension_manager.reload_extension(module_str)
@@ -1,337 +1,337 b''
1 1 """Implementation of magic functions related to History.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012, IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import os
17 17 import sys
18 18 from io import open as io_open
19 19 import fnmatch
20 20
21 21 # Our own packages
22 22 from IPython.core.error import StdinNotImplementedError
23 23 from IPython.core.magic import Magics, magics_class, line_magic
24 24 from IPython.core.magic_arguments import (argument, magic_arguments,
25 25 parse_argstring)
26 26 from IPython.testing.skipdoctest import skip_doctest
27 27 from IPython.utils import io
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Magics class implementation
31 31 #-----------------------------------------------------------------------------
32 32
33 33
34 34 _unspecified = object()
35 35
36 36
37 37 @magics_class
38 38 class HistoryMagics(Magics):
39 39
40 40 @magic_arguments()
41 41 @argument(
42 42 '-n', dest='print_nums', action='store_true', default=False,
43 43 help="""
44 44 print line numbers for each input.
45 45 This feature is only available if numbered prompts are in use.
46 46 """)
47 47 @argument(
48 48 '-o', dest='get_output', action='store_true', default=False,
49 49 help="also print outputs for each input.")
50 50 @argument(
51 51 '-p', dest='pyprompts', action='store_true', default=False,
52 52 help="""
53 53 print classic '>>>' python prompts before each input.
54 54 This is useful for making documentation, and in conjunction
55 55 with -o, for producing doctest-ready output.
56 56 """)
57 57 @argument(
58 58 '-t', dest='raw', action='store_false', default=True,
59 59 help="""
60 60 print the 'translated' history, as IPython understands it.
61 61 IPython filters your input and converts it all into valid Python
62 62 source before executing it (things like magics or aliases are turned
63 63 into function calls, for example). With this option, you'll see the
64 64 native history instead of the user-entered version: '%%cd /' will be
65 65 seen as 'get_ipython().run_line_magic("cd", "/")' instead of '%%cd /'.
66 66 """)
67 67 @argument(
68 68 '-f', dest='filename',
69 69 help="""
70 70 FILENAME: instead of printing the output to the screen, redirect
71 71 it to the given file. The file is always overwritten, though *when
72 72 it can*, IPython asks for confirmation first. In particular, running
73 73 the command 'history -f FILENAME' from the IPython Notebook
74 74 interface will replace FILENAME even if it already exists *without*
75 75 confirmation.
76 76 """)
77 77 @argument(
78 78 '-g', dest='pattern', nargs='*', default=None,
79 79 help="""
80 80 treat the arg as a glob pattern to search for in (full) history.
81 81 This includes the saved history (almost all commands ever written).
82 82 The pattern may contain '?' to match one unknown character and '*'
83 83 to match any number of unknown characters. Use '%%hist -g' to show
84 84 full saved history (may be very long).
85 85 """)
86 86 @argument(
87 87 '-l', dest='limit', type=int, nargs='?', default=_unspecified,
88 88 help="""
89 89 get the last n lines from all sessions. Specify n as a single
90 90 arg, or the default is the last 10 lines.
91 91 """)
92 92 @argument(
93 93 '-u', dest='unique', action='store_true',
94 94 help="""
95 95 when searching history using `-g`, show only unique history.
96 96 """)
97 97 @argument('range', nargs='*')
98 98 @skip_doctest
99 99 @line_magic
100 100 def history(self, parameter_s = ''):
101 101 """Print input history (_i<n> variables), with most recent last.
102 102
103 103 By default, input history is printed without line numbers so it can be
104 104 directly pasted into an editor. Use -n to show them.
105 105
106 106 By default, all input history from the current session is displayed.
107 107 Ranges of history can be indicated using the syntax:
108
108
109 109 ``4``
110 110 Line 4, current session
111 111 ``4-6``
112 112 Lines 4-6, current session
113 113 ``243/1-5``
114 114 Lines 1-5, session 243
115 115 ``~2/7``
116 116 Line 7, session 2 before current
117 117 ``~8/1-~6/5``
118 118 From the first line of 8 sessions ago, to the fifth line of 6
119 119 sessions ago.
120
120
121 121 Multiple ranges can be entered, separated by spaces
122 122
123 123 The same syntax is used by %macro, %save, %edit, %rerun
124 124
125 125 Examples
126 126 --------
127 127 ::
128 128
129 129 In [6]: %history -n 4-6
130 130 4:a = 12
131 131 5:print a**2
132 132 6:%history -n 4-6
133 133
134 134 """
135 135
136 136 args = parse_argstring(self.history, parameter_s)
137 137
138 138 # For brevity
139 139 history_manager = self.shell.history_manager
140 140
141 141 def _format_lineno(session, line):
142 142 """Helper function to format line numbers properly."""
143 143 if session in (0, history_manager.session_number):
144 144 return str(line)
145 145 return "%s/%s" % (session, line)
146 146
147 147 # Check if output to specific file was requested.
148 148 outfname = args.filename
149 149 if not outfname:
150 150 outfile = sys.stdout # default
151 151 # We don't want to close stdout at the end!
152 152 close_at_end = False
153 153 else:
154 154 if os.path.exists(outfname):
155 155 try:
156 156 ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
157 157 except StdinNotImplementedError:
158 158 ans = True
159 159 if not ans:
160 160 print('Aborting.')
161 161 return
162 162 print("Overwriting file.")
163 163 outfile = io_open(outfname, 'w', encoding='utf-8')
164 164 close_at_end = True
165 165
166 166 print_nums = args.print_nums
167 167 get_output = args.get_output
168 168 pyprompts = args.pyprompts
169 169 raw = args.raw
170 170
171 171 pattern = None
172 172 limit = None if args.limit is _unspecified else args.limit
173 173
174 174 range_pattern = False
175 175 if args.pattern is not None and not args.range:
176 176 if args.pattern:
177 177 pattern = "*" + " ".join(args.pattern) + "*"
178 178 else:
179 179 pattern = "*"
180 180 hist = history_manager.search(pattern, raw=raw, output=get_output,
181 181 n=limit, unique=args.unique)
182 182 print_nums = True
183 183 elif args.limit is not _unspecified:
184 184 n = 10 if limit is None else limit
185 185 hist = history_manager.get_tail(n, raw=raw, output=get_output)
186 186 else:
187 187 if args.pattern:
188 188 range_pattern = "*" + " ".join(args.pattern) + "*"
189 189 print_nums = True
190 190 hist = history_manager.get_range_by_str(
191 191 " ".join(args.range), raw, get_output
192 192 )
193 193
194 194 # We could be displaying the entire history, so let's not try to pull
195 195 # it into a list in memory. Anything that needs more space will just
196 196 # misalign.
197 197 width = 4
198 198
199 199 for session, lineno, inline in hist:
200 200 # Print user history with tabs expanded to 4 spaces. The GUI
201 201 # clients use hard tabs for easier usability in auto-indented code,
202 202 # but we want to produce PEP-8 compliant history for safe pasting
203 203 # into an editor.
204 204 if get_output:
205 205 inline, output = inline
206 206 if range_pattern:
207 207 if not fnmatch.fnmatch(inline, range_pattern):
208 208 continue
209 209 inline = inline.expandtabs(4).rstrip()
210 210
211 211 multiline = "\n" in inline
212 212 line_sep = '\n' if multiline else ' '
213 213 if print_nums:
214 214 print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
215 215 line_sep), file=outfile, end=u'')
216 216 if pyprompts:
217 217 print(u">>> ", end=u"", file=outfile)
218 218 if multiline:
219 219 inline = "\n... ".join(inline.splitlines()) + "\n..."
220 220 print(inline, file=outfile)
221 221 if get_output and output:
222 222 print(output, file=outfile)
223 223
224 224 if close_at_end:
225 225 outfile.close()
226 226
227 227 @line_magic
228 228 def recall(self, arg):
229 229 r"""Repeat a command, or get command to input line for editing.
230 230
231 231 %recall and %rep are equivalent.
232 232
233 233 - %recall (no arguments):
234 234
235 235 Place a string version of last computation result (stored in the
236 236 special '_' variable) to the next input prompt. Allows you to create
237 237 elaborate command lines without using copy-paste::
238 238
239 239 In[1]: l = ["hei", "vaan"]
240 240 In[2]: "".join(l)
241 241 Out[2]: heivaan
242 242 In[3]: %recall
243 243 In[4]: heivaan_ <== cursor blinking
244 244
245 245 %recall 45
246 246
247 247 Place history line 45 on the next input prompt. Use %hist to find
248 248 out the number.
249 249
250 250 %recall 1-4
251 251
252 252 Combine the specified lines into one cell, and place it on the next
253 253 input prompt. See %history for the slice syntax.
254 254
255 255 %recall foo+bar
256 256
257 257 If foo+bar can be evaluated in the user namespace, the result is
258 258 placed at the next input prompt. Otherwise, the history is searched
259 259 for lines which contain that substring, and the most recent one is
260 260 placed at the next input prompt.
261 261 """
262 262 if not arg: # Last output
263 263 self.shell.set_next_input(str(self.shell.user_ns["_"]))
264 264 return
265 265 # Get history range
266 266 histlines = self.shell.history_manager.get_range_by_str(arg)
267 267 cmd = "\n".join(x[2] for x in histlines)
268 268 if cmd:
269 269 self.shell.set_next_input(cmd.rstrip())
270 270 return
271 271
272 272 try: # Variable in user namespace
273 273 cmd = str(eval(arg, self.shell.user_ns))
274 274 except Exception: # Search for term in history
275 275 histlines = self.shell.history_manager.search("*"+arg+"*")
276 276 for h in reversed([x[2] for x in histlines]):
277 277 if 'recall' in h or 'rep' in h:
278 278 continue
279 279 self.shell.set_next_input(h.rstrip())
280 280 return
281 281 else:
282 282 self.shell.set_next_input(cmd.rstrip())
283 283 return
284 284 print("Couldn't evaluate or find in history:", arg)
285 285
286 286 @line_magic
287 287 def rerun(self, parameter_s=''):
288 288 """Re-run previous input
289 289
290 290 By default, you can specify ranges of input history to be repeated
291 291 (as with %history). With no arguments, it will repeat the last line.
292 292
293 293 Options:
294 294
295 295 -l <n> : Repeat the last n lines of input, not including the
296 296 current command.
297 297
298 298 -g foo : Repeat the most recent line which contains foo
299 299 """
300 300 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
301 301 if "l" in opts: # Last n lines
302 302 try:
303 303 n = int(opts["l"])
304 304 except ValueError:
305 305 print("Number of lines must be an integer")
306 306 return
307 307
308 308 if n == 0:
309 309 print("Requested 0 last lines - nothing to run")
310 310 return
311 311 elif n < 0:
312 312 print("Number of lines to rerun cannot be negative")
313 313 return
314 314
315 315 hist = self.shell.history_manager.get_tail(n)
316 316 elif "g" in opts: # Search
317 317 p = "*"+opts['g']+"*"
318 318 hist = list(self.shell.history_manager.search(p))
319 319 for l in reversed(hist):
320 320 if "rerun" not in l[2]:
321 321 hist = [l] # The last match which isn't a %rerun
322 322 break
323 323 else:
324 324 hist = [] # No matches except %rerun
325 325 elif args: # Specify history ranges
326 326 hist = self.shell.history_manager.get_range_by_str(args)
327 327 else: # Last line
328 328 hist = self.shell.history_manager.get_tail(1)
329 329 hist = [x[2] for x in hist]
330 330 if not hist:
331 331 print("No lines in history match specification")
332 332 return
333 333 histlines = "\n".join(hist)
334 334 print("=== Executing: ===")
335 335 print(histlines)
336 336 print("=== Output: ===")
337 337 self.shell.run_cell("\n".join(hist), store_history=False)
@@ -1,712 +1,703 b''
1 1 """Implementation of namespace-related magic functions.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012 The IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import gc
17 17 import re
18 18 import sys
19 19
20 20 # Our own packages
21 21 from IPython.core import page
22 22 from IPython.core.error import StdinNotImplementedError, UsageError
23 23 from IPython.core.magic import Magics, magics_class, line_magic
24 24 from IPython.testing.skipdoctest import skip_doctest
25 25 from IPython.utils.encoding import DEFAULT_ENCODING
26 26 from IPython.utils.openpy import read_py_file
27 27 from IPython.utils.path import get_py_filename
28 28
29 29 #-----------------------------------------------------------------------------
30 30 # Magic implementation classes
31 31 #-----------------------------------------------------------------------------
32 32
33 33 @magics_class
34 34 class NamespaceMagics(Magics):
35 35 """Magics to manage various aspects of the user's namespace.
36 36
37 37 These include listing variables, introspecting into them, etc.
38 38 """
39 39
40 40 @line_magic
41 41 def pinfo(self, parameter_s='', namespaces=None):
42 42 """Provide detailed information about an object.
43 43
44 44 '%pinfo object' is just a synonym for object? or ?object."""
45 45
46 46 #print 'pinfo par: <%s>' % parameter_s # dbg
47 47 # detail_level: 0 -> obj? , 1 -> obj??
48 48 detail_level = 0
49 49 # We need to detect if we got called as 'pinfo pinfo foo', which can
50 50 # happen if the user types 'pinfo foo?' at the cmd line.
51 51 pinfo,qmark1,oname,qmark2 = \
52 52 re.match(r'(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
53 53 if pinfo or qmark1 or qmark2:
54 54 detail_level = 1
55 55 if "*" in oname:
56 56 self.psearch(oname)
57 57 else:
58 58 self.shell._inspect('pinfo', oname, detail_level=detail_level,
59 59 namespaces=namespaces)
60 60
61 61 @line_magic
62 62 def pinfo2(self, parameter_s='', namespaces=None):
63 63 """Provide extra detailed information about an object.
64 64
65 65 '%pinfo2 object' is just a synonym for object?? or ??object."""
66 66 self.shell._inspect('pinfo', parameter_s, detail_level=1,
67 67 namespaces=namespaces)
68 68
69 69 @skip_doctest
70 70 @line_magic
71 71 def pdef(self, parameter_s='', namespaces=None):
72 72 """Print the call signature for any callable object.
73 73
74 74 If the object is a class, print the constructor information.
75 75
76 76 Examples
77 77 --------
78 78 ::
79 79
80 80 In [3]: %pdef urllib.urlopen
81 81 urllib.urlopen(url, data=None, proxies=None)
82 82 """
83 83 self.shell._inspect('pdef',parameter_s, namespaces)
84 84
85 85 @line_magic
86 86 def pdoc(self, parameter_s='', namespaces=None):
87 87 """Print the docstring for an object.
88 88
89 89 If the given object is a class, it will print both the class and the
90 90 constructor docstrings."""
91 91 self.shell._inspect('pdoc',parameter_s, namespaces)
92 92
93 93 @line_magic
94 94 def psource(self, parameter_s='', namespaces=None):
95 95 """Print (or run through pager) the source code for an object."""
96 96 if not parameter_s:
97 97 raise UsageError('Missing object name.')
98 98 self.shell._inspect('psource',parameter_s, namespaces)
99 99
100 100 @line_magic
101 101 def pfile(self, parameter_s='', namespaces=None):
102 102 """Print (or run through pager) the file where an object is defined.
103 103
104 104 The file opens at the line where the object definition begins. IPython
105 105 will honor the environment variable PAGER if set, and otherwise will
106 106 do its best to print the file in a convenient form.
107 107
108 108 If the given argument is not an object currently defined, IPython will
109 109 try to interpret it as a filename (automatically adding a .py extension
110 110 if needed). You can thus use %pfile as a syntax highlighting code
111 111 viewer."""
112 112
113 113 # first interpret argument as an object name
114 114 out = self.shell._inspect('pfile',parameter_s, namespaces)
115 115 # if not, try the input as a filename
116 116 if out == 'not found':
117 117 try:
118 118 filename = get_py_filename(parameter_s)
119 119 except IOError as msg:
120 120 print(msg)
121 121 return
122 122 page.page(self.shell.pycolorize(read_py_file(filename, skip_encoding_cookie=False)))
123 123
124 124 @line_magic
125 125 def psearch(self, parameter_s=''):
126 126 """Search for object in namespaces by wildcard.
127 127
128 128 %psearch [options] PATTERN [OBJECT TYPE]
129 129
130 130 Note: ? can be used as a synonym for %psearch, at the beginning or at
131 131 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
132 132 rest of the command line must be unchanged (options come first), so
133 133 for example the following forms are equivalent
134 134
135 135 %psearch -i a* function
136 136 -i a* function?
137 137 ?-i a* function
138 138
139 139 Arguments:
140 140
141 141 PATTERN
142 142
143 143 where PATTERN is a string containing * as a wildcard similar to its
144 144 use in a shell. The pattern is matched in all namespaces on the
145 145 search path. By default objects starting with a single _ are not
146 146 matched, many IPython generated objects have a single
147 147 underscore. The default is case insensitive matching. Matching is
148 148 also done on the attributes of objects and not only on the objects
149 149 in a module.
150 150
151 151 [OBJECT TYPE]
152 152
153 153 Is the name of a python type from the types module. The name is
154 154 given in lowercase without the ending type, ex. StringType is
155 155 written string. By adding a type here only objects matching the
156 156 given type are matched. Using all here makes the pattern match all
157 157 types (this is the default).
158 158
159 159 Options:
160 160
161 161 -a: makes the pattern match even objects whose names start with a
162 162 single underscore. These names are normally omitted from the
163 163 search.
164 164
165 165 -i/-c: make the pattern case insensitive/sensitive. If neither of
166 166 these options are given, the default is read from your configuration
167 167 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
168 168 If this option is not specified in your configuration file, IPython's
169 169 internal default is to do a case sensitive search.
170 170
171 171 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
172 172 specify can be searched in any of the following namespaces:
173 173 'builtin', 'user', 'user_global','internal', 'alias', where
174 174 'builtin' and 'user' are the search defaults. Note that you should
175 175 not use quotes when specifying namespaces.
176
176
177 177 -l: List all available object types for object matching. This function
178 178 can be used without arguments.
179 179
180 180 'Builtin' contains the python module builtin, 'user' contains all
181 181 user data, 'alias' only contain the shell aliases and no python
182 182 objects, 'internal' contains objects used by IPython. The
183 183 'user_global' namespace is only used by embedded IPython instances,
184 184 and it contains module-level globals. You can add namespaces to the
185 185 search with -s or exclude them with -e (these options can be given
186 186 more than once).
187 187
188 188 Examples
189 189 --------
190 190 ::
191 191
192 192 %psearch a* -> objects beginning with an a
193 193 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
194 194 %psearch a* function -> all functions beginning with an a
195 195 %psearch re.e* -> objects beginning with an e in module re
196 196 %psearch r*.e* -> objects that start with e in modules starting in r
197 197 %psearch r*.* string -> all strings in modules beginning with r
198 198
199 199 Case sensitive search::
200 200
201 201 %psearch -c a* list all object beginning with lower case a
202 202
203 203 Show objects beginning with a single _::
204 204
205 205 %psearch -a _* list objects beginning with a single underscore
206
206
207 207 List available objects::
208
208
209 209 %psearch -l list all available object types
210 210 """
211 211 # default namespaces to be searched
212 212 def_search = ['user_local', 'user_global', 'builtin']
213 213
214 214 # Process options/args
215 215 opts,args = self.parse_options(parameter_s,'cias:e:l',list_all=True)
216 216 opt = opts.get
217 217 shell = self.shell
218 218 psearch = shell.inspector.psearch
219 219
220 220 # select list object types
221 221 list_types = False
222 222 if 'l' in opts:
223 223 list_types = True
224 224
225 225 # select case options
226 226 if 'i' in opts:
227 227 ignore_case = True
228 228 elif 'c' in opts:
229 229 ignore_case = False
230 230 else:
231 231 ignore_case = not shell.wildcards_case_sensitive
232 232
233 233 # Build list of namespaces to search from user options
234 234 def_search.extend(opt('s',[]))
235 235 ns_exclude = ns_exclude=opt('e',[])
236 236 ns_search = [nm for nm in def_search if nm not in ns_exclude]
237 237
238 238 # Call the actual search
239 239 try:
240 240 psearch(args,shell.ns_table,ns_search,
241 241 show_all=opt('a'),ignore_case=ignore_case, list_types=list_types)
242 242 except:
243 243 shell.showtraceback()
244 244
245 245 @skip_doctest
246 246 @line_magic
247 247 def who_ls(self, parameter_s=''):
248 248 """Return a sorted list of all interactive variables.
249 249
250 250 If arguments are given, only variables of types matching these
251 251 arguments are returned.
252 252
253 253 Examples
254 254 --------
255
256 255 Define two variables and list them with who_ls::
257 256
258 257 In [1]: alpha = 123
259 258
260 259 In [2]: beta = 'test'
261 260
262 261 In [3]: %who_ls
263 262 Out[3]: ['alpha', 'beta']
264 263
265 264 In [4]: %who_ls int
266 265 Out[4]: ['alpha']
267 266
268 267 In [5]: %who_ls str
269 268 Out[5]: ['beta']
270 269 """
271 270
272 271 user_ns = self.shell.user_ns
273 272 user_ns_hidden = self.shell.user_ns_hidden
274 273 nonmatching = object() # This can never be in user_ns
275 274 out = [ i for i in user_ns
276 275 if not i.startswith('_') \
277 276 and (user_ns[i] is not user_ns_hidden.get(i, nonmatching)) ]
278 277
279 278 typelist = parameter_s.split()
280 279 if typelist:
281 280 typeset = set(typelist)
282 281 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
283 282
284 283 out.sort()
285 284 return out
286 285
287 286 @skip_doctest
288 287 @line_magic
289 288 def who(self, parameter_s=''):
290 289 """Print all interactive variables, with some minimal formatting.
291 290
292 291 If any arguments are given, only variables whose type matches one of
293 292 these are printed. For example::
294 293
295 294 %who function str
296 295
297 296 will only list functions and strings, excluding all other types of
298 297 variables. To find the proper type names, simply use type(var) at a
299 298 command line to see how python prints type names. For example:
300 299
301 300 ::
302 301
303 302 In [1]: type('hello')\\
304 303 Out[1]: <type 'str'>
305 304
306 305 indicates that the type name for strings is 'str'.
307 306
308 307 ``%who`` always excludes executed names loaded through your configuration
309 308 file and things which are internal to IPython.
310 309
311 310 This is deliberate, as typically you may load many modules and the
312 311 purpose of %who is to show you only what you've manually defined.
313 312
314 313 Examples
315 314 --------
316 315
317 316 Define two variables and list them with who::
318 317
319 318 In [1]: alpha = 123
320 319
321 320 In [2]: beta = 'test'
322 321
323 322 In [3]: %who
324 323 alpha beta
325 324
326 325 In [4]: %who int
327 326 alpha
328 327
329 328 In [5]: %who str
330 329 beta
331 330 """
332 331
333 332 varlist = self.who_ls(parameter_s)
334 333 if not varlist:
335 334 if parameter_s:
336 335 print('No variables match your requested type.')
337 336 else:
338 337 print('Interactive namespace is empty.')
339 338 return
340 339
341 340 # if we have variables, move on...
342 341 count = 0
343 342 for i in varlist:
344 343 print(i+'\t', end=' ')
345 344 count += 1
346 345 if count > 8:
347 346 count = 0
348 347 print()
349 348 print()
350 349
351 350 @skip_doctest
352 351 @line_magic
353 352 def whos(self, parameter_s=''):
354 353 """Like %who, but gives some extra information about each variable.
355 354
356 355 The same type filtering of %who can be applied here.
357 356
358 357 For all variables, the type is printed. Additionally it prints:
359 358
360 359 - For {},[],(): their length.
361 360
362 361 - For numpy arrays, a summary with shape, number of
363 362 elements, typecode and size in memory.
364 363
365 364 - Everything else: a string representation, snipping their middle if
366 365 too long.
367 366
368 367 Examples
369 368 --------
370
371 369 Define two variables and list them with whos::
372 370
373 371 In [1]: alpha = 123
374 372
375 373 In [2]: beta = 'test'
376 374
377 375 In [3]: %whos
378 376 Variable Type Data/Info
379 377 --------------------------------
380 378 alpha int 123
381 379 beta str test
382 380 """
383 381
384 382 varnames = self.who_ls(parameter_s)
385 383 if not varnames:
386 384 if parameter_s:
387 385 print('No variables match your requested type.')
388 386 else:
389 387 print('Interactive namespace is empty.')
390 388 return
391 389
392 390 # if we have variables, move on...
393 391
394 392 # for these types, show len() instead of data:
395 393 seq_types = ['dict', 'list', 'tuple']
396 394
397 395 # for numpy arrays, display summary info
398 396 ndarray_type = None
399 397 if 'numpy' in sys.modules:
400 398 try:
401 399 from numpy import ndarray
402 400 except ImportError:
403 401 pass
404 402 else:
405 403 ndarray_type = ndarray.__name__
406 404
407 405 # Find all variable names and types so we can figure out column sizes
408 406
409 407 # some types are well known and can be shorter
410 408 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
411 409 def type_name(v):
412 410 tn = type(v).__name__
413 411 return abbrevs.get(tn,tn)
414 412
415 413 varlist = [self.shell.user_ns[n] for n in varnames]
416 414
417 415 typelist = []
418 416 for vv in varlist:
419 417 tt = type_name(vv)
420 418
421 419 if tt=='instance':
422 420 typelist.append( abbrevs.get(str(vv.__class__),
423 421 str(vv.__class__)))
424 422 else:
425 423 typelist.append(tt)
426 424
427 425 # column labels and # of spaces as separator
428 426 varlabel = 'Variable'
429 427 typelabel = 'Type'
430 428 datalabel = 'Data/Info'
431 429 colsep = 3
432 430 # variable format strings
433 431 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
434 432 aformat = "%s: %s elems, type `%s`, %s bytes"
435 433 # find the size of the columns to format the output nicely
436 434 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
437 435 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
438 436 # table header
439 437 print(varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
440 438 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1))
441 439 # and the table itself
442 440 kb = 1024
443 441 Mb = 1048576 # kb**2
444 442 for vname,var,vtype in zip(varnames,varlist,typelist):
445 443 print(vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth), end=' ')
446 444 if vtype in seq_types:
447 445 print("n="+str(len(var)))
448 446 elif vtype == ndarray_type:
449 447 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
450 448 if vtype==ndarray_type:
451 449 # numpy
452 450 vsize = var.size
453 451 vbytes = vsize*var.itemsize
454 452 vdtype = var.dtype
455 453
456 454 if vbytes < 100000:
457 455 print(aformat % (vshape, vsize, vdtype, vbytes))
458 456 else:
459 457 print(aformat % (vshape, vsize, vdtype, vbytes), end=' ')
460 458 if vbytes < Mb:
461 459 print('(%s kb)' % (vbytes/kb,))
462 460 else:
463 461 print('(%s Mb)' % (vbytes/Mb,))
464 462 else:
465 463 try:
466 464 vstr = str(var)
467 465 except UnicodeEncodeError:
468 466 vstr = var.encode(DEFAULT_ENCODING,
469 467 'backslashreplace')
470 468 except:
471 469 vstr = "<object with id %d (str() failed)>" % id(var)
472 470 vstr = vstr.replace('\n', '\\n')
473 471 if len(vstr) < 50:
474 472 print(vstr)
475 473 else:
476 474 print(vstr[:25] + "<...>" + vstr[-25:])
477 475
478 476 @line_magic
479 477 def reset(self, parameter_s=''):
480 478 """Resets the namespace by removing all names defined by the user, if
481 479 called without arguments, or by removing some types of objects, such
482 480 as everything currently in IPython's In[] and Out[] containers (see
483 481 the parameters for details).
484 482
485 483 Parameters
486 484 ----------
487 485 -f : force reset without asking for confirmation.
488
489 486 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
490 487 References to objects may be kept. By default (without this option),
491 488 we do a 'hard' reset, giving you a new session and removing all
492 489 references to objects from the current session.
493
494 --aggressive: Try to aggressively remove modules from sys.modules ; this
490 --aggressive : Try to aggressively remove modules from sys.modules ; this
495 491 may allow you to reimport Python modules that have been updated and
496 492 pick up changes, but can have unattended consequences.
497
498 493 in : reset input history
499
500 494 out : reset output history
501
502 495 dhist : reset directory history
503
504 496 array : reset only variables that are NumPy arrays
505 497
506 498 See Also
507 499 --------
508 500 reset_selective : invoked as ``%reset_selective``
509 501
510 502 Examples
511 503 --------
512 504 ::
513 505
514 506 In [6]: a = 1
515 507
516 508 In [7]: a
517 509 Out[7]: 1
518 510
519 511 In [8]: 'a' in get_ipython().user_ns
520 512 Out[8]: True
521 513
522 514 In [9]: %reset -f
523 515
524 516 In [1]: 'a' in get_ipython().user_ns
525 517 Out[1]: False
526 518
527 519 In [2]: %reset -f in
528 520 Flushing input history
529 521
530 522 In [3]: %reset -f dhist in
531 523 Flushing directory history
532 524 Flushing input history
533 525
534 526 Notes
535 527 -----
536 528 Calling this magic from clients that do not implement standard input,
537 529 such as the ipython notebook interface, will reset the namespace
538 530 without confirmation.
539 531 """
540 532 opts, args = self.parse_options(parameter_s, "sf", "aggressive", mode="list")
541 533 if "f" in opts:
542 534 ans = True
543 535 else:
544 536 try:
545 537 ans = self.shell.ask_yes_no(
546 538 "Once deleted, variables cannot be recovered. Proceed (y/[n])?",
547 539 default='n')
548 540 except StdinNotImplementedError:
549 541 ans = True
550 542 if not ans:
551 543 print('Nothing done.')
552 544 return
553 545
554 546 if 's' in opts: # Soft reset
555 547 user_ns = self.shell.user_ns
556 548 for i in self.who_ls():
557 549 del(user_ns[i])
558 550 elif len(args) == 0: # Hard reset
559 551 self.shell.reset(new_session=False, aggressive=("aggressive" in opts))
560 552
561 553 # reset in/out/dhist/array: previously extensinions/clearcmd.py
562 554 ip = self.shell
563 555 user_ns = self.shell.user_ns # local lookup, heavily used
564 556
565 557 for target in args:
566 558 target = target.lower() # make matches case insensitive
567 559 if target == 'out':
568 560 print("Flushing output cache (%d entries)" % len(user_ns['_oh']))
569 561 self.shell.displayhook.flush()
570 562
571 563 elif target == 'in':
572 564 print("Flushing input history")
573 565 pc = self.shell.displayhook.prompt_count + 1
574 566 for n in range(1, pc):
575 567 key = '_i'+repr(n)
576 568 user_ns.pop(key,None)
577 569 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
578 570 hm = ip.history_manager
579 571 # don't delete these, as %save and %macro depending on the
580 572 # length of these lists to be preserved
581 573 hm.input_hist_parsed[:] = [''] * pc
582 574 hm.input_hist_raw[:] = [''] * pc
583 575 # hm has internal machinery for _i,_ii,_iii, clear it out
584 576 hm._i = hm._ii = hm._iii = hm._i00 = u''
585 577
586 578 elif target == 'array':
587 579 # Support cleaning up numpy arrays
588 580 try:
589 581 from numpy import ndarray
590 582 # This must be done with items and not iteritems because
591 583 # we're going to modify the dict in-place.
592 584 for x,val in list(user_ns.items()):
593 585 if isinstance(val,ndarray):
594 586 del user_ns[x]
595 587 except ImportError:
596 588 print("reset array only works if Numpy is available.")
597 589
598 590 elif target == 'dhist':
599 591 print("Flushing directory history")
600 592 del user_ns['_dh'][:]
601 593
602 594 else:
603 595 print("Don't know how to reset ", end=' ')
604 596 print(target + ", please run `%reset?` for details")
605 597
606 598 gc.collect()
607 599
608 600 @line_magic
609 601 def reset_selective(self, parameter_s=''):
610 602 """Resets the namespace by removing names defined by the user.
611 603
612 604 Input/Output history are left around in case you need them.
613 605
614 606 %reset_selective [-f] regex
615 607
616 608 No action is taken if regex is not included
617 609
618 610 Options
619 611 -f : force reset without asking for confirmation.
620 612
621 613 See Also
622 614 --------
623 615 reset : invoked as ``%reset``
624 616
625 617 Examples
626 618 --------
627
628 619 We first fully reset the namespace so your output looks identical to
629 620 this example for pedagogical reasons; in practice you do not need a
630 621 full reset::
631 622
632 623 In [1]: %reset -f
633 624
634 625 Now, with a clean namespace we can make a few variables and use
635 626 ``%reset_selective`` to only delete names that match our regexp::
636 627
637 628 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
638 629
639 630 In [3]: who_ls
640 631 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
641 632
642 633 In [4]: %reset_selective -f b[2-3]m
643 634
644 635 In [5]: who_ls
645 636 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
646 637
647 638 In [6]: %reset_selective -f d
648 639
649 640 In [7]: who_ls
650 641 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
651 642
652 643 In [8]: %reset_selective -f c
653 644
654 645 In [9]: who_ls
655 646 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
656 647
657 648 In [10]: %reset_selective -f b
658 649
659 650 In [11]: who_ls
660 651 Out[11]: ['a']
661 652
662 653 Notes
663 654 -----
664 655 Calling this magic from clients that do not implement standard input,
665 656 such as the ipython notebook interface, will reset the namespace
666 657 without confirmation.
667 658 """
668 659
669 660 opts, regex = self.parse_options(parameter_s,'f')
670 661
671 662 if 'f' in opts:
672 663 ans = True
673 664 else:
674 665 try:
675 666 ans = self.shell.ask_yes_no(
676 667 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
677 668 default='n')
678 669 except StdinNotImplementedError:
679 670 ans = True
680 671 if not ans:
681 672 print('Nothing done.')
682 673 return
683 674 user_ns = self.shell.user_ns
684 675 if not regex:
685 676 print('No regex pattern specified. Nothing done.')
686 677 return
687 678 else:
688 679 try:
689 680 m = re.compile(regex)
690 681 except TypeError as e:
691 682 raise TypeError('regex must be a string or compiled pattern') from e
692 683 for i in self.who_ls():
693 684 if m.search(i):
694 685 del(user_ns[i])
695 686
696 687 @line_magic
697 688 def xdel(self, parameter_s=''):
698 689 """Delete a variable, trying to clear it from anywhere that
699 690 IPython's machinery has references to it. By default, this uses
700 691 the identity of the named object in the user namespace to remove
701 692 references held under other names. The object is also removed
702 693 from the output history.
703 694
704 695 Options
705 696 -n : Delete the specified name from all namespaces, without
706 697 checking their identity.
707 698 """
708 699 opts, varname = self.parse_options(parameter_s,'n')
709 700 try:
710 701 self.shell.del_var(varname, ('n' in opts))
711 702 except (NameError, ValueError) as e:
712 703 print(type(e).__name__ +": "+ str(e))
@@ -1,856 +1,854 b''
1 1 """Implementation of magic functions for interaction with the OS.
2 2
3 3 Note: this module is named 'osm' instead of 'os' to avoid a collision with the
4 4 builtin.
5 5 """
6 6 # Copyright (c) IPython Development Team.
7 7 # Distributed under the terms of the Modified BSD License.
8 8
9 9 import io
10 10 import os
11 11 import re
12 12 import sys
13 13 from pprint import pformat
14 14
15 15 from IPython.core import magic_arguments
16 16 from IPython.core import oinspect
17 17 from IPython.core import page
18 18 from IPython.core.alias import AliasError, Alias
19 19 from IPython.core.error import UsageError
20 20 from IPython.core.magic import (
21 21 Magics, compress_dhist, magics_class, line_magic, cell_magic, line_cell_magic
22 22 )
23 23 from IPython.testing.skipdoctest import skip_doctest
24 24 from IPython.utils.openpy import source_to_unicode
25 25 from IPython.utils.process import abbrev_cwd
26 26 from IPython.utils.terminal import set_term_title
27 27 from traitlets import Bool
28 28 from warnings import warn
29 29
30 30
31 31 @magics_class
32 32 class OSMagics(Magics):
33 33 """Magics to interact with the underlying OS (shell-type functionality).
34 34 """
35 35
36 36 cd_force_quiet = Bool(False,
37 37 help="Force %cd magic to be quiet even if -q is not passed."
38 38 ).tag(config=True)
39 39
40 40 def __init__(self, shell=None, **kwargs):
41 41
42 42 # Now define isexec in a cross platform manner.
43 43 self.is_posix = False
44 44 self.execre = None
45 45 if os.name == 'posix':
46 46 self.is_posix = True
47 47 else:
48 48 try:
49 49 winext = os.environ['pathext'].replace(';','|').replace('.','')
50 50 except KeyError:
51 51 winext = 'exe|com|bat|py'
52 52 try:
53 53 self.execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
54 54 except re.error:
55 55 warn("Seems like your pathext environmental "
56 56 "variable is malformed. Please check it to "
57 57 "enable a proper handle of file extensions "
58 58 "managed for your system")
59 59 winext = 'exe|com|bat|py'
60 60 self.execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
61 61
62 62 # call up the chain
63 63 super().__init__(shell=shell, **kwargs)
64 64
65 65
66 66 def _isexec_POSIX(self, file):
67 67 """
68 Test for executable on a POSIX system
68 Test for executable on a POSIX system
69 69 """
70 70 if os.access(file.path, os.X_OK):
71 71 # will fail on maxOS if access is not X_OK
72 72 return file.is_file()
73 73 return False
74 74
75 75
76 76
77 77 def _isexec_WIN(self, file):
78 78 """
79 Test for executable file on non POSIX system
79 Test for executable file on non POSIX system
80 80 """
81 81 return file.is_file() and self.execre.match(file.name) is not None
82 82
83 83 def isexec(self, file):
84 84 """
85 Test for executable file on non POSIX system
85 Test for executable file on non POSIX system
86 86 """
87 87 if self.is_posix:
88 88 return self._isexec_POSIX(file)
89 89 else:
90 90 return self._isexec_WIN(file)
91 91
92 92
93 93 @skip_doctest
94 94 @line_magic
95 95 def alias(self, parameter_s=''):
96 96 """Define an alias for a system command.
97 97
98 98 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
99 99
100 100 Then, typing 'alias_name params' will execute the system command 'cmd
101 101 params' (from your underlying operating system).
102 102
103 103 Aliases have lower precedence than magic functions and Python normal
104 104 variables, so if 'foo' is both a Python variable and an alias, the
105 105 alias can not be executed until 'del foo' removes the Python variable.
106 106
107 107 You can use the %l specifier in an alias definition to represent the
108 108 whole line when the alias is called. For example::
109 109
110 110 In [2]: alias bracket echo "Input in brackets: <%l>"
111 111 In [3]: bracket hello world
112 112 Input in brackets: <hello world>
113 113
114 114 You can also define aliases with parameters using %s specifiers (one
115 115 per parameter)::
116 116
117 117 In [1]: alias parts echo first %s second %s
118 118 In [2]: %parts A B
119 119 first A second B
120 120 In [3]: %parts A
121 121 Incorrect number of arguments: 2 expected.
122 122 parts is an alias to: 'echo first %s second %s'
123 123
124 124 Note that %l and %s are mutually exclusive. You can only use one or
125 125 the other in your aliases.
126 126
127 127 Aliases expand Python variables just like system calls using ! or !!
128 128 do: all expressions prefixed with '$' get expanded. For details of
129 129 the semantic rules, see PEP-215:
130 130 http://www.python.org/peps/pep-0215.html. This is the library used by
131 131 IPython for variable expansion. If you want to access a true shell
132 132 variable, an extra $ is necessary to prevent its expansion by
133 133 IPython::
134 134
135 135 In [6]: alias show echo
136 136 In [7]: PATH='A Python string'
137 137 In [8]: show $PATH
138 138 A Python string
139 139 In [9]: show $$PATH
140 140 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
141 141
142 142 You can use the alias facility to access all of $PATH. See the %rehashx
143 143 function, which automatically creates aliases for the contents of your
144 144 $PATH.
145 145
146 146 If called with no parameters, %alias prints the current alias table
147 147 for your system. For posix systems, the default aliases are 'cat',
148 148 'cp', 'mv', 'rm', 'rmdir', and 'mkdir', and other platform-specific
149 149 aliases are added. For windows-based systems, the default aliases are
150 150 'copy', 'ddir', 'echo', 'ls', 'ldir', 'mkdir', 'ren', and 'rmdir'.
151 151
152 152 You can see the definition of alias by adding a question mark in the
153 153 end::
154 154
155 155 In [1]: cat?
156 156 Repr: <alias cat for 'cat'>"""
157 157
158 158 par = parameter_s.strip()
159 159 if not par:
160 160 aliases = sorted(self.shell.alias_manager.aliases)
161 161 # stored = self.shell.db.get('stored_aliases', {} )
162 162 # for k, v in stored:
163 163 # atab.append(k, v[0])
164 164
165 165 print("Total number of aliases:", len(aliases))
166 166 sys.stdout.flush()
167 167 return aliases
168 168
169 169 # Now try to define a new one
170 170 try:
171 171 alias,cmd = par.split(None, 1)
172 172 except TypeError:
173 173 print(oinspect.getdoc(self.alias))
174 174 return
175 175
176 176 try:
177 177 self.shell.alias_manager.define_alias(alias, cmd)
178 178 except AliasError as e:
179 179 print(e)
180 180 # end magic_alias
181 181
182 182 @line_magic
183 183 def unalias(self, parameter_s=''):
184 184 """Remove an alias"""
185 185
186 186 aname = parameter_s.strip()
187 187 try:
188 188 self.shell.alias_manager.undefine_alias(aname)
189 189 except ValueError as e:
190 190 print(e)
191 191 return
192 192
193 193 stored = self.shell.db.get('stored_aliases', {} )
194 194 if aname in stored:
195 195 print("Removing %stored alias",aname)
196 196 del stored[aname]
197 197 self.shell.db['stored_aliases'] = stored
198 198
199 199 @line_magic
200 200 def rehashx(self, parameter_s=''):
201 201 """Update the alias table with all executable files in $PATH.
202 202
203 203 rehashx explicitly checks that every entry in $PATH is a file
204 204 with execute access (os.X_OK).
205 205
206 206 Under Windows, it checks executability as a match against a
207 207 '|'-separated string of extensions, stored in the IPython config
208 208 variable win_exec_ext. This defaults to 'exe|com|bat'.
209 209
210 210 This function also resets the root module cache of module completer,
211 211 used on slow filesystems.
212 212 """
213 213 from IPython.core.alias import InvalidAliasError
214 214
215 215 # for the benefit of module completer in ipy_completers.py
216 216 del self.shell.db['rootmodules_cache']
217 217
218 218 path = [os.path.abspath(os.path.expanduser(p)) for p in
219 219 os.environ.get('PATH','').split(os.pathsep)]
220 220
221 221 syscmdlist = []
222 222 savedir = os.getcwd()
223 223
224 224 # Now walk the paths looking for executables to alias.
225 225 try:
226 226 # write the whole loop for posix/Windows so we don't have an if in
227 227 # the innermost part
228 228 if self.is_posix:
229 229 for pdir in path:
230 230 try:
231 231 os.chdir(pdir)
232 232 except OSError:
233 233 continue
234 234
235 235 # for python 3.6+ rewrite to: with os.scandir(pdir) as dirlist:
236 236 dirlist = os.scandir(path=pdir)
237 237 for ff in dirlist:
238 238 if self.isexec(ff):
239 239 fname = ff.name
240 240 try:
241 241 # Removes dots from the name since ipython
242 242 # will assume names with dots to be python.
243 243 if not self.shell.alias_manager.is_alias(fname):
244 244 self.shell.alias_manager.define_alias(
245 245 fname.replace('.',''), fname)
246 246 except InvalidAliasError:
247 247 pass
248 248 else:
249 249 syscmdlist.append(fname)
250 250 else:
251 251 no_alias = Alias.blacklist
252 252 for pdir in path:
253 253 try:
254 254 os.chdir(pdir)
255 255 except OSError:
256 256 continue
257 257
258 258 # for python 3.6+ rewrite to: with os.scandir(pdir) as dirlist:
259 259 dirlist = os.scandir(pdir)
260 260 for ff in dirlist:
261 261 fname = ff.name
262 262 base, ext = os.path.splitext(fname)
263 263 if self.isexec(ff) and base.lower() not in no_alias:
264 264 if ext.lower() == '.exe':
265 265 fname = base
266 266 try:
267 267 # Removes dots from the name since ipython
268 268 # will assume names with dots to be python.
269 269 self.shell.alias_manager.define_alias(
270 270 base.lower().replace('.',''), fname)
271 271 except InvalidAliasError:
272 272 pass
273 273 syscmdlist.append(fname)
274 274
275 275 self.shell.db['syscmdlist'] = syscmdlist
276 276 finally:
277 277 os.chdir(savedir)
278 278
279 279 @skip_doctest
280 280 @line_magic
281 281 def pwd(self, parameter_s=''):
282 282 """Return the current working directory path.
283 283
284 284 Examples
285 285 --------
286 286 ::
287 287
288 288 In [9]: pwd
289 289 Out[9]: '/home/tsuser/sprint/ipython'
290 290 """
291 291 try:
292 292 return os.getcwd()
293 293 except FileNotFoundError as e:
294 294 raise UsageError("CWD no longer exists - please use %cd to change directory.") from e
295 295
296 296 @skip_doctest
297 297 @line_magic
298 298 def cd(self, parameter_s=''):
299 299 """Change the current working directory.
300 300
301 301 This command automatically maintains an internal list of directories
302 302 you visit during your IPython session, in the variable ``_dh``. The
303 303 command :magic:`%dhist` shows this history nicely formatted. You can
304 304 also do ``cd -<tab>`` to see directory history conveniently.
305 305 Usage:
306 306
307 307 - ``cd 'dir'``: changes to directory 'dir'.
308 308 - ``cd -``: changes to the last visited directory.
309 309 - ``cd -<n>``: changes to the n-th directory in the directory history.
310 310 - ``cd --foo``: change to directory that matches 'foo' in history
311 311 - ``cd -b <bookmark_name>``: jump to a bookmark set by %bookmark
312 312 - Hitting a tab key after ``cd -b`` allows you to tab-complete
313 313 bookmark names.
314 314
315 315 .. note::
316 316 ``cd <bookmark_name>`` is enough if there is no directory
317 317 ``<bookmark_name>``, but a bookmark with the name exists.
318 318
319
320 319 Options:
321 320
322 321 -q Be quiet. Do not print the working directory after the
323 322 cd command is executed. By default IPython's cd
324 323 command does print this directory, since the default
325 324 prompts do not display path information.
326 325
327 326 .. note::
328 327 Note that ``!cd`` doesn't work for this purpose because the shell
329 328 where ``!command`` runs is immediately discarded after executing
330 329 'command'.
331 330
332
333 331 Examples
334 332 --------
335 333 ::
336 334
337 335 In [10]: cd parent/child
338 336 /home/tsuser/parent/child
339 337 """
340 338
341 339 try:
342 340 oldcwd = os.getcwd()
343 341 except FileNotFoundError:
344 342 # Happens if the CWD has been deleted.
345 343 oldcwd = None
346 344
347 345 numcd = re.match(r'(-)(\d+)$',parameter_s)
348 346 # jump in directory history by number
349 347 if numcd:
350 348 nn = int(numcd.group(2))
351 349 try:
352 350 ps = self.shell.user_ns['_dh'][nn]
353 351 except IndexError:
354 352 print('The requested directory does not exist in history.')
355 353 return
356 354 else:
357 355 opts = {}
358 356 elif parameter_s.startswith('--'):
359 357 ps = None
360 358 fallback = None
361 359 pat = parameter_s[2:]
362 360 dh = self.shell.user_ns['_dh']
363 361 # first search only by basename (last component)
364 362 for ent in reversed(dh):
365 363 if pat in os.path.basename(ent) and os.path.isdir(ent):
366 364 ps = ent
367 365 break
368 366
369 367 if fallback is None and pat in ent and os.path.isdir(ent):
370 368 fallback = ent
371 369
372 370 # if we have no last part match, pick the first full path match
373 371 if ps is None:
374 372 ps = fallback
375 373
376 374 if ps is None:
377 375 print("No matching entry in directory history")
378 376 return
379 377 else:
380 378 opts = {}
381 379
382 380
383 381 else:
384 382 opts, ps = self.parse_options(parameter_s, 'qb', mode='string')
385 383 # jump to previous
386 384 if ps == '-':
387 385 try:
388 386 ps = self.shell.user_ns['_dh'][-2]
389 387 except IndexError as e:
390 388 raise UsageError('%cd -: No previous directory to change to.') from e
391 389 # jump to bookmark if needed
392 390 else:
393 391 if not os.path.isdir(ps) or 'b' in opts:
394 392 bkms = self.shell.db.get('bookmarks', {})
395 393
396 394 if ps in bkms:
397 395 target = bkms[ps]
398 396 print('(bookmark:%s) -> %s' % (ps, target))
399 397 ps = target
400 398 else:
401 399 if 'b' in opts:
402 400 raise UsageError("Bookmark '%s' not found. "
403 401 "Use '%%bookmark -l' to see your bookmarks." % ps)
404 402
405 403 # at this point ps should point to the target dir
406 404 if ps:
407 405 try:
408 406 os.chdir(os.path.expanduser(ps))
409 407 if hasattr(self.shell, 'term_title') and self.shell.term_title:
410 408 set_term_title(self.shell.term_title_format.format(cwd=abbrev_cwd()))
411 409 except OSError:
412 410 print(sys.exc_info()[1])
413 411 else:
414 412 cwd = os.getcwd()
415 413 dhist = self.shell.user_ns['_dh']
416 414 if oldcwd != cwd:
417 415 dhist.append(cwd)
418 416 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
419 417
420 418 else:
421 419 os.chdir(self.shell.home_dir)
422 420 if hasattr(self.shell, 'term_title') and self.shell.term_title:
423 421 set_term_title(self.shell.term_title_format.format(cwd="~"))
424 422 cwd = os.getcwd()
425 423 dhist = self.shell.user_ns['_dh']
426 424
427 425 if oldcwd != cwd:
428 426 dhist.append(cwd)
429 427 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
430 428 if not 'q' in opts and not self.cd_force_quiet and self.shell.user_ns['_dh']:
431 429 print(self.shell.user_ns['_dh'][-1])
432 430
433 431 @line_magic
434 432 def env(self, parameter_s=''):
435 433 """Get, set, or list environment variables.
436 434
437 435 Usage:\\
438 436
439 437 :``%env``: lists all environment variables/values
440 438 :``%env var``: get value for var
441 439 :``%env var val``: set value for var
442 440 :``%env var=val``: set value for var
443 441 :``%env var=$val``: set value for var, using python expansion if possible
444 442 """
445 443 if parameter_s.strip():
446 444 split = '=' if '=' in parameter_s else ' '
447 445 bits = parameter_s.split(split)
448 446 if len(bits) == 1:
449 447 key = parameter_s.strip()
450 448 if key in os.environ:
451 449 return os.environ[key]
452 450 else:
453 451 err = "Environment does not have key: {0}".format(key)
454 452 raise UsageError(err)
455 453 if len(bits) > 1:
456 454 return self.set_env(parameter_s)
457 455 env = dict(os.environ)
458 456 # hide likely secrets when printing the whole environment
459 457 for key in list(env):
460 458 if any(s in key.lower() for s in ('key', 'token', 'secret')):
461 459 env[key] = '<hidden>'
462 460
463 461 return env
464 462
465 463 @line_magic
466 464 def set_env(self, parameter_s):
467 465 """Set environment variables. Assumptions are that either "val" is a
468 466 name in the user namespace, or val is something that evaluates to a
469 467 string.
470 468
471 469 Usage:\\
472 470 %set_env var val: set value for var
473 471 %set_env var=val: set value for var
474 472 %set_env var=$val: set value for var, using python expansion if possible
475 473 """
476 474 split = '=' if '=' in parameter_s else ' '
477 475 bits = parameter_s.split(split, 1)
478 476 if not parameter_s.strip() or len(bits)<2:
479 477 raise UsageError("usage is 'set_env var=val'")
480 478 var = bits[0].strip()
481 479 val = bits[1].strip()
482 480 if re.match(r'.*\s.*', var):
483 481 # an environment variable with whitespace is almost certainly
484 482 # not what the user intended. what's more likely is the wrong
485 483 # split was chosen, ie for "set_env cmd_args A=B", we chose
486 484 # '=' for the split and should have chosen ' '. to get around
487 485 # this, users should just assign directly to os.environ or use
488 486 # standard magic {var} expansion.
489 487 err = "refusing to set env var with whitespace: '{0}'"
490 488 err = err.format(val)
491 489 raise UsageError(err)
492 490 os.environ[var] = val
493 491 print('env: {0}={1}'.format(var,val))
494 492
495 493 @line_magic
496 494 def pushd(self, parameter_s=''):
497 495 """Place the current dir on stack and change directory.
498 496
499 497 Usage:\\
500 498 %pushd ['dirname']
501 499 """
502 500
503 501 dir_s = self.shell.dir_stack
504 502 tgt = os.path.expanduser(parameter_s)
505 503 cwd = os.getcwd().replace(self.shell.home_dir,'~')
506 504 if tgt:
507 505 self.cd(parameter_s)
508 506 dir_s.insert(0,cwd)
509 507 return self.shell.run_line_magic('dirs', '')
510 508
511 509 @line_magic
512 510 def popd(self, parameter_s=''):
513 511 """Change to directory popped off the top of the stack.
514 512 """
515 513 if not self.shell.dir_stack:
516 514 raise UsageError("%popd on empty stack")
517 515 top = self.shell.dir_stack.pop(0)
518 516 self.cd(top)
519 517 print("popd ->",top)
520 518
521 519 @line_magic
522 520 def dirs(self, parameter_s=''):
523 521 """Return the current directory stack."""
524 522
525 523 return self.shell.dir_stack
526 524
527 525 @line_magic
528 526 def dhist(self, parameter_s=''):
529 527 """Print your history of visited directories.
530 528
531 529 %dhist -> print full history\\
532 530 %dhist n -> print last n entries only\\
533 531 %dhist n1 n2 -> print entries between n1 and n2 (n2 not included)\\
534 532
535 533 This history is automatically maintained by the %cd command, and
536 534 always available as the global list variable _dh. You can use %cd -<n>
537 535 to go to directory number <n>.
538 536
539 537 Note that most of time, you should view directory history by entering
540 538 cd -<TAB>.
541 539
542 540 """
543 541
544 542 dh = self.shell.user_ns['_dh']
545 543 if parameter_s:
546 544 try:
547 545 args = map(int,parameter_s.split())
548 546 except:
549 547 self.arg_err(self.dhist)
550 548 return
551 549 if len(args) == 1:
552 550 ini,fin = max(len(dh)-(args[0]),0),len(dh)
553 551 elif len(args) == 2:
554 552 ini,fin = args
555 553 fin = min(fin, len(dh))
556 554 else:
557 555 self.arg_err(self.dhist)
558 556 return
559 557 else:
560 558 ini,fin = 0,len(dh)
561 559 print('Directory history (kept in _dh)')
562 560 for i in range(ini, fin):
563 561 print("%d: %s" % (i, dh[i]))
564 562
565 563 @skip_doctest
566 564 @line_magic
567 565 def sc(self, parameter_s=''):
568 566 """Shell capture - run shell command and capture output (DEPRECATED use !).
569 567
570 568 DEPRECATED. Suboptimal, retained for backwards compatibility.
571 569
572 570 You should use the form 'var = !command' instead. Example:
573 571
574 572 "%sc -l myfiles = ls ~" should now be written as
575 573
576 574 "myfiles = !ls ~"
577 575
578 576 myfiles.s, myfiles.l and myfiles.n still apply as documented
579 577 below.
580 578
581 579 --
582 580 %sc [options] varname=command
583 581
584 582 IPython will run the given command using commands.getoutput(), and
585 583 will then update the user's interactive namespace with a variable
586 584 called varname, containing the value of the call. Your command can
587 585 contain shell wildcards, pipes, etc.
588 586
589 587 The '=' sign in the syntax is mandatory, and the variable name you
590 588 supply must follow Python's standard conventions for valid names.
591 589
592 590 (A special format without variable name exists for internal use)
593 591
594 592 Options:
595 593
596 594 -l: list output. Split the output on newlines into a list before
597 595 assigning it to the given variable. By default the output is stored
598 596 as a single string.
599 597
600 598 -v: verbose. Print the contents of the variable.
601 599
602 600 In most cases you should not need to split as a list, because the
603 601 returned value is a special type of string which can automatically
604 602 provide its contents either as a list (split on newlines) or as a
605 603 space-separated string. These are convenient, respectively, either
606 604 for sequential processing or to be passed to a shell command.
607 605
608 606 For example::
609 607
610 608 # Capture into variable a
611 609 In [1]: sc a=ls *py
612 610
613 611 # a is a string with embedded newlines
614 612 In [2]: a
615 613 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
616 614
617 615 # which can be seen as a list:
618 616 In [3]: a.l
619 617 Out[3]: ['setup.py', 'win32_manual_post_install.py']
620 618
621 619 # or as a whitespace-separated string:
622 620 In [4]: a.s
623 621 Out[4]: 'setup.py win32_manual_post_install.py'
624 622
625 623 # a.s is useful to pass as a single command line:
626 624 In [5]: !wc -l $a.s
627 625 146 setup.py
628 626 130 win32_manual_post_install.py
629 627 276 total
630 628
631 629 # while the list form is useful to loop over:
632 630 In [6]: for f in a.l:
633 631 ...: !wc -l $f
634 632 ...:
635 633 146 setup.py
636 634 130 win32_manual_post_install.py
637 635
638 636 Similarly, the lists returned by the -l option are also special, in
639 637 the sense that you can equally invoke the .s attribute on them to
640 638 automatically get a whitespace-separated string from their contents::
641 639
642 640 In [7]: sc -l b=ls *py
643 641
644 642 In [8]: b
645 643 Out[8]: ['setup.py', 'win32_manual_post_install.py']
646 644
647 645 In [9]: b.s
648 646 Out[9]: 'setup.py win32_manual_post_install.py'
649 647
650 648 In summary, both the lists and strings used for output capture have
651 649 the following special attributes::
652 650
653 651 .l (or .list) : value as list.
654 652 .n (or .nlstr): value as newline-separated string.
655 653 .s (or .spstr): value as space-separated string.
656 654 """
657 655
658 656 opts,args = self.parse_options(parameter_s, 'lv')
659 657 # Try to get a variable name and command to run
660 658 try:
661 659 # the variable name must be obtained from the parse_options
662 660 # output, which uses shlex.split to strip options out.
663 661 var,_ = args.split('=', 1)
664 662 var = var.strip()
665 663 # But the command has to be extracted from the original input
666 664 # parameter_s, not on what parse_options returns, to avoid the
667 665 # quote stripping which shlex.split performs on it.
668 666 _,cmd = parameter_s.split('=', 1)
669 667 except ValueError:
670 668 var,cmd = '',''
671 669 # If all looks ok, proceed
672 670 split = 'l' in opts
673 671 out = self.shell.getoutput(cmd, split=split)
674 672 if 'v' in opts:
675 673 print('%s ==\n%s' % (var, pformat(out)))
676 674 if var:
677 675 self.shell.user_ns.update({var:out})
678 676 else:
679 677 return out
680 678
681 679 @line_cell_magic
682 680 def sx(self, line='', cell=None):
683 681 """Shell execute - run shell command and capture output (!! is short-hand).
684 682
685 683 %sx command
686 684
687 685 IPython will run the given command using commands.getoutput(), and
688 686 return the result formatted as a list (split on '\\n'). Since the
689 687 output is _returned_, it will be stored in ipython's regular output
690 688 cache Out[N] and in the '_N' automatic variables.
691 689
692 690 Notes:
693 691
694 692 1) If an input line begins with '!!', then %sx is automatically
695 693 invoked. That is, while::
696 694
697 695 !ls
698 696
699 697 causes ipython to simply issue system('ls'), typing::
700 698
701 699 !!ls
702 700
703 701 is a shorthand equivalent to::
704 702
705 703 %sx ls
706 704
707 705 2) %sx differs from %sc in that %sx automatically splits into a list,
708 706 like '%sc -l'. The reason for this is to make it as easy as possible
709 707 to process line-oriented shell output via further python commands.
710 708 %sc is meant to provide much finer control, but requires more
711 709 typing.
712 710
713 711 3) Just like %sc -l, this is a list with special attributes:
714 712 ::
715 713
716 714 .l (or .list) : value as list.
717 715 .n (or .nlstr): value as newline-separated string.
718 716 .s (or .spstr): value as whitespace-separated string.
719 717
720 718 This is very useful when trying to use such lists as arguments to
721 719 system commands."""
722 720
723 721 if cell is None:
724 722 # line magic
725 723 return self.shell.getoutput(line)
726 724 else:
727 725 opts,args = self.parse_options(line, '', 'out=')
728 726 output = self.shell.getoutput(cell)
729 727 out_name = opts.get('out', opts.get('o'))
730 728 if out_name:
731 729 self.shell.user_ns[out_name] = output
732 730 else:
733 731 return output
734 732
735 733 system = line_cell_magic('system')(sx)
736 734 bang = cell_magic('!')(sx)
737 735
738 736 @line_magic
739 737 def bookmark(self, parameter_s=''):
740 738 """Manage IPython's bookmark system.
741 739
742 740 %bookmark <name> - set bookmark to current dir
743 741 %bookmark <name> <dir> - set bookmark to <dir>
744 742 %bookmark -l - list all bookmarks
745 743 %bookmark -d <name> - remove bookmark
746 744 %bookmark -r - remove all bookmarks
747 745
748 746 You can later on access a bookmarked folder with::
749 747
750 748 %cd -b <name>
751 749
752 750 or simply '%cd <name>' if there is no directory called <name> AND
753 751 there is such a bookmark defined.
754 752
755 753 Your bookmarks persist through IPython sessions, but they are
756 754 associated with each profile."""
757 755
758 756 opts,args = self.parse_options(parameter_s,'drl',mode='list')
759 757 if len(args) > 2:
760 758 raise UsageError("%bookmark: too many arguments")
761 759
762 760 bkms = self.shell.db.get('bookmarks',{})
763 761
764 762 if 'd' in opts:
765 763 try:
766 764 todel = args[0]
767 765 except IndexError as e:
768 766 raise UsageError(
769 767 "%bookmark -d: must provide a bookmark to delete") from e
770 768 else:
771 769 try:
772 770 del bkms[todel]
773 771 except KeyError as e:
774 772 raise UsageError(
775 773 "%%bookmark -d: Can't delete bookmark '%s'" % todel) from e
776 774
777 775 elif 'r' in opts:
778 776 bkms = {}
779 777 elif 'l' in opts:
780 778 bks = sorted(bkms)
781 779 if bks:
782 780 size = max(map(len, bks))
783 781 else:
784 782 size = 0
785 783 fmt = '%-'+str(size)+'s -> %s'
786 784 print('Current bookmarks:')
787 785 for bk in bks:
788 786 print(fmt % (bk, bkms[bk]))
789 787 else:
790 788 if not args:
791 789 raise UsageError("%bookmark: You must specify the bookmark name")
792 790 elif len(args)==1:
793 791 bkms[args[0]] = os.getcwd()
794 792 elif len(args)==2:
795 793 bkms[args[0]] = args[1]
796 794 self.shell.db['bookmarks'] = bkms
797 795
798 796 @line_magic
799 797 def pycat(self, parameter_s=''):
800 798 """Show a syntax-highlighted file through a pager.
801 799
802 800 This magic is similar to the cat utility, but it will assume the file
803 801 to be Python source and will show it with syntax highlighting.
804 802
805 803 This magic command can either take a local filename, an url,
806 804 an history range (see %history) or a macro as argument.
807 805
808 806 If no parameter is given, prints out history of current session up to
809 807 this point. ::
810 808
811 809 %pycat myscript.py
812 810 %pycat 7-27
813 811 %pycat myMacro
814 812 %pycat http://www.example.com/myscript.py
815 813 """
816 814 try:
817 815 cont = self.shell.find_user_code(parameter_s, skip_encoding_cookie=False)
818 816 except (ValueError, IOError):
819 817 print("Error: no such file, variable, URL, history range or macro")
820 818 return
821 819
822 820 page.page(self.shell.pycolorize(source_to_unicode(cont)))
823 821
824 822 @magic_arguments.magic_arguments()
825 823 @magic_arguments.argument(
826 824 '-a', '--append', action='store_true', default=False,
827 825 help='Append contents of the cell to an existing file. '
828 826 'The file will be created if it does not exist.'
829 827 )
830 828 @magic_arguments.argument(
831 829 'filename', type=str,
832 830 help='file to write'
833 831 )
834 832 @cell_magic
835 833 def writefile(self, line, cell):
836 834 """Write the contents of the cell to a file.
837
835
838 836 The file will be overwritten unless the -a (--append) flag is specified.
839 837 """
840 838 args = magic_arguments.parse_argstring(self.writefile, line)
841 839 if re.match(r'^(\'.*\')|(".*")$', args.filename):
842 840 filename = os.path.expanduser(args.filename[1:-1])
843 841 else:
844 842 filename = os.path.expanduser(args.filename)
845 843
846 844 if os.path.exists(filename):
847 845 if args.append:
848 846 print("Appending to %s" % filename)
849 847 else:
850 848 print("Overwriting %s" % filename)
851 849 else:
852 850 print("Writing %s" % filename)
853 851
854 852 mode = 'a' if args.append else 'w'
855 853 with io.open(filename, mode, encoding='utf-8') as f:
856 854 f.write(cell)
@@ -1,375 +1,375 b''
1 1 """Magic functions for running cells in various scripts."""
2 2
3 3 # Copyright (c) IPython Development Team.
4 4 # Distributed under the terms of the Modified BSD License.
5 5
6 6 import asyncio
7 7 import atexit
8 8 import errno
9 9 import functools
10 10 import os
11 11 import signal
12 12 import sys
13 13 import time
14 14 from contextlib import contextmanager
15 15 from subprocess import CalledProcessError
16 16
17 17 from traitlets import Dict, List, default
18 18
19 19 from IPython.core import magic_arguments
20 20 from IPython.core.magic import Magics, cell_magic, line_magic, magics_class
21 21 from IPython.lib.backgroundjobs import BackgroundJobManager
22 22 from IPython.utils.process import arg_split
23 23
24 24 #-----------------------------------------------------------------------------
25 25 # Magic implementation classes
26 26 #-----------------------------------------------------------------------------
27 27
28 28 def script_args(f):
29 29 """single decorator for adding script args"""
30 30 args = [
31 31 magic_arguments.argument(
32 32 '--out', type=str,
33 33 help="""The variable in which to store stdout from the script.
34 34 If the script is backgrounded, this will be the stdout *pipe*,
35 35 instead of the stderr text itself and will not be auto closed.
36 36 """
37 37 ),
38 38 magic_arguments.argument(
39 39 '--err', type=str,
40 40 help="""The variable in which to store stderr from the script.
41 41 If the script is backgrounded, this will be the stderr *pipe*,
42 42 instead of the stderr text itself and will not be autoclosed.
43 43 """
44 44 ),
45 45 magic_arguments.argument(
46 46 '--bg', action="store_true",
47 47 help="""Whether to run the script in the background.
48 48 If given, the only way to see the output of the command is
49 49 with --out/err.
50 50 """
51 51 ),
52 52 magic_arguments.argument(
53 53 '--proc', type=str,
54 54 help="""The variable in which to store Popen instance.
55 55 This is used only when --bg option is given.
56 56 """
57 57 ),
58 58 magic_arguments.argument(
59 59 '--no-raise-error', action="store_false", dest='raise_error',
60 60 help="""Whether you should raise an error message in addition to
61 61 a stream on stderr if you get a nonzero exit code.
62 62 """
63 63 )
64 64 ]
65 65 for arg in args:
66 66 f = arg(f)
67 67 return f
68 68
69 69
70 70 @contextmanager
71 71 def safe_watcher():
72 72 if sys.platform == "win32":
73 73 yield
74 74 return
75 75
76 76 from asyncio import SafeChildWatcher
77 77
78 78 policy = asyncio.get_event_loop_policy()
79 79 old_watcher = policy.get_child_watcher()
80 80 if isinstance(old_watcher, SafeChildWatcher):
81 81 yield
82 82 return
83 83
84 84 try:
85 85 loop = policy.get_event_loop()
86 86 if loop.is_closed():
87 87 raise RuntimeError("open a new one")
88 88 except RuntimeError:
89 89 # closed loop, make a new one
90 90 loop = policy.new_event_loop()
91 91 policy.set_event_loop(loop)
92 92
93 93 try:
94 94 watcher = asyncio.SafeChildWatcher()
95 95 watcher.attach_loop(loop)
96 96 policy.set_child_watcher(watcher)
97 97 yield
98 98 finally:
99 99 watcher.close()
100 100 policy.set_child_watcher(old_watcher)
101 101
102 102
103 103 def dec_safe_watcher(fun):
104 104 @functools.wraps(fun)
105 105 def _inner(*args, **kwargs):
106 106 with safe_watcher():
107 107 return fun(*args, **kwargs)
108 108
109 109 return _inner
110 110
111 111
112 112 @magics_class
113 113 class ScriptMagics(Magics):
114 114 """Magics for talking to scripts
115 115
116 116 This defines a base `%%script` cell magic for running a cell
117 117 with a program in a subprocess, and registers a few top-level
118 118 magics that call %%script with common interpreters.
119 119 """
120 120 script_magics = List(
121 121 help="""Extra script cell magics to define
122 122
123 123 This generates simple wrappers of `%%script foo` as `%%foo`.
124 124
125 125 If you want to add script magics that aren't on your path,
126 126 specify them in script_paths
127 127 """,
128 128 ).tag(config=True)
129 129 @default('script_magics')
130 130 def _script_magics_default(self):
131 131 """default to a common list of programs"""
132 132
133 133 defaults = [
134 134 'sh',
135 135 'bash',
136 136 'perl',
137 137 'ruby',
138 138 'python',
139 139 'python2',
140 140 'python3',
141 141 'pypy',
142 142 ]
143 143 if os.name == 'nt':
144 144 defaults.extend([
145 145 'cmd',
146 146 ])
147 147
148 148 return defaults
149 149
150 150 script_paths = Dict(
151 151 help="""Dict mapping short 'ruby' names to full paths, such as '/opt/secret/bin/ruby'
152 152
153 153 Only necessary for items in script_magics where the default path will not
154 154 find the right interpreter.
155 155 """
156 156 ).tag(config=True)
157 157
158 158 def __init__(self, shell=None):
159 159 super(ScriptMagics, self).__init__(shell=shell)
160 160 self._generate_script_magics()
161 161 self.job_manager = BackgroundJobManager()
162 162 self.bg_processes = []
163 163 atexit.register(self.kill_bg_processes)
164 164
165 165 def __del__(self):
166 166 self.kill_bg_processes()
167 167
168 168 def _generate_script_magics(self):
169 169 cell_magics = self.magics['cell']
170 170 for name in self.script_magics:
171 171 cell_magics[name] = self._make_script_magic(name)
172 172
173 173 def _make_script_magic(self, name):
174 174 """make a named magic, that calls %%script with a particular program"""
175 175 # expand to explicit path if necessary:
176 176 script = self.script_paths.get(name, name)
177 177
178 178 @magic_arguments.magic_arguments()
179 179 @script_args
180 180 def named_script_magic(line, cell):
181 181 # if line, add it as cl-flags
182 182 if line:
183 183 line = "%s %s" % (script, line)
184 184 else:
185 185 line = script
186 186 return self.shebang(line, cell)
187 187
188 188 # write a basic docstring:
189 189 named_script_magic.__doc__ = \
190 190 """%%{name} script magic
191 191
192 192 Run cells with {script} in a subprocess.
193 193
194 194 This is a shortcut for `%%script {script}`
195 195 """.format(**locals())
196 196
197 197 return named_script_magic
198 198
199 199 @magic_arguments.magic_arguments()
200 200 @script_args
201 201 @cell_magic("script")
202 202 @dec_safe_watcher
203 203 def shebang(self, line, cell):
204 204 """Run a cell via a shell command
205
205
206 206 The `%%script` line is like the #! line of script,
207 207 specifying a program (bash, perl, ruby, etc.) with which to run.
208
208
209 209 The rest of the cell is run by that program.
210
210
211 211 Examples
212 212 --------
213 213 ::
214
214
215 215 In [1]: %%script bash
216 216 ...: for i in 1 2 3; do
217 217 ...: echo $i
218 218 ...: done
219 219 1
220 220 2
221 221 3
222 222 """
223 223
224 224 async def _handle_stream(stream, stream_arg, file_object):
225 225 while True:
226 226 line = (await stream.readline()).decode("utf8")
227 227 if not line:
228 228 break
229 229 if stream_arg:
230 230 self.shell.user_ns[stream_arg] = line
231 231 else:
232 232 file_object.write(line)
233 233 file_object.flush()
234 234
235 235 async def _stream_communicate(process, cell):
236 236 process.stdin.write(cell)
237 237 process.stdin.close()
238 238 stdout_task = asyncio.create_task(
239 239 _handle_stream(process.stdout, args.out, sys.stdout)
240 240 )
241 241 stderr_task = asyncio.create_task(
242 242 _handle_stream(process.stderr, args.err, sys.stderr)
243 243 )
244 244 await asyncio.wait([stdout_task, stderr_task])
245 245 await process.wait()
246 246
247 247 policy = asyncio.get_event_loop_policy()
248 248 if sys.platform.startswith("win") and not isinstance(
249 249 policy, asyncio.WindowsProactorEventLoopPolicy
250 250 ):
251 251 # _do not_ overwrite the current policy
252 252 policy = asyncio.WindowsProactorEventLoopPolicy()
253 253
254 254 try:
255 255 loop = policy.get_event_loop()
256 256 except RuntimeError:
257 257 # closed loop, make a new one
258 258 loop = policy.new_event_loop()
259 259 policy.set_event_loop(loop)
260 260 argv = arg_split(line, posix=not sys.platform.startswith("win"))
261 261 args, cmd = self.shebang.parser.parse_known_args(argv)
262 262 try:
263 263 p = loop.run_until_complete(
264 264 asyncio.create_subprocess_exec(
265 265 *cmd,
266 266 stdout=asyncio.subprocess.PIPE,
267 267 stderr=asyncio.subprocess.PIPE,
268 268 stdin=asyncio.subprocess.PIPE,
269 269 )
270 270 )
271 271 except OSError as e:
272 272 if e.errno == errno.ENOENT:
273 273 print("Couldn't find program: %r" % cmd[0])
274 274 return
275 275 else:
276 276 raise
277 277
278 278 if not cell.endswith('\n'):
279 279 cell += '\n'
280 280 cell = cell.encode('utf8', 'replace')
281 281 if args.bg:
282 282 self.bg_processes.append(p)
283 283 self._gc_bg_processes()
284 284 to_close = []
285 285 if args.out:
286 286 self.shell.user_ns[args.out] = p.stdout
287 287 else:
288 288 to_close.append(p.stdout)
289 289 if args.err:
290 290 self.shell.user_ns[args.err] = p.stderr
291 291 else:
292 292 to_close.append(p.stderr)
293 293 self.job_manager.new(self._run_script, p, cell, to_close, daemon=True)
294 294 if args.proc:
295 295 self.shell.user_ns[args.proc] = p
296 296 return
297 297
298 298 try:
299 299 loop.run_until_complete(_stream_communicate(p, cell))
300 300 except KeyboardInterrupt:
301 301 try:
302 302 p.send_signal(signal.SIGINT)
303 303 time.sleep(0.1)
304 304 if p.returncode is not None:
305 305 print("Process is interrupted.")
306 306 return
307 307 p.terminate()
308 308 time.sleep(0.1)
309 309 if p.returncode is not None:
310 310 print("Process is terminated.")
311 311 return
312 312 p.kill()
313 313 print("Process is killed.")
314 314 except OSError:
315 315 pass
316 316 except Exception as e:
317 317 print("Error while terminating subprocess (pid=%i): %s" % (p.pid, e))
318 318 return
319 319 if args.raise_error and p.returncode!=0:
320 320 # If we get here and p.returncode is still None, we must have
321 321 # killed it but not yet seen its return code. We don't wait for it,
322 322 # in case it's stuck in uninterruptible sleep. -9 = SIGKILL
323 323 rc = p.returncode or -9
324 324 raise CalledProcessError(rc, cell)
325 325
326 326 shebang.__skip_doctest__ = os.name != "posix"
327 327
328 328 def _run_script(self, p, cell, to_close):
329 329 """callback for running the script in the background"""
330 330 p.stdin.write(cell)
331 331 p.stdin.close()
332 332 for s in to_close:
333 333 s.close()
334 334 p.wait()
335 335
336 336 @line_magic("killbgscripts")
337 337 def killbgscripts(self, _nouse_=''):
338 338 """Kill all BG processes started by %%script and its family."""
339 339 self.kill_bg_processes()
340 340 print("All background processes were killed.")
341 341
342 342 def kill_bg_processes(self):
343 343 """Kill all BG processes which are still running."""
344 344 if not self.bg_processes:
345 345 return
346 346 for p in self.bg_processes:
347 347 if p.returncode is None:
348 348 try:
349 349 p.send_signal(signal.SIGINT)
350 350 except:
351 351 pass
352 352 time.sleep(0.1)
353 353 self._gc_bg_processes()
354 354 if not self.bg_processes:
355 355 return
356 356 for p in self.bg_processes:
357 357 if p.returncode is None:
358 358 try:
359 359 p.terminate()
360 360 except:
361 361 pass
362 362 time.sleep(0.1)
363 363 self._gc_bg_processes()
364 364 if not self.bg_processes:
365 365 return
366 366 for p in self.bg_processes:
367 367 if p.returncode is None:
368 368 try:
369 369 p.kill()
370 370 except:
371 371 pass
372 372 self._gc_bg_processes()
373 373
374 374 def _gc_bg_processes(self):
375 375 self.bg_processes = [p for p in self.bg_processes if p.returncode is None]
@@ -1,108 +1,108 b''
1 1 [metadata]
2 2 name = ipython
3 3 version = attr: IPython.core.release.__version__
4 4 url = https://ipython.org
5 5 description = IPython: Productive Interactive Computing
6 6 long_description_content_type = text/x-rst
7 7 long_description = IPython provides a rich toolkit to help you make the most out of using Python
8 8 interactively. Its main components are:
9 9
10 10 * A powerful interactive Python shell
11 11 * A `Jupyter <https://jupyter.org/>`_ kernel to work with Python code in Jupyter
12 12 notebooks and other interactive frontends.
13 13
14 14 The enhanced interactive Python shells have the following main features:
15 15
16 16 * Comprehensive object introspection.
17 17
18 18 * Input history, persistent across sessions.
19 19
20 20 * Caching of output results during a session with automatically generated
21 21 references.
22 22
23 23 * Extensible tab completion, with support by default for completion of python
24 24 variables and keywords, filenames and function keywords.
25 25
26 26 * Extensible system of 'magic' commands for controlling the environment and
27 27 performing many tasks related either to IPython or the operating system.
28 28
29 29 * A rich configuration system with easy switching between different setups
30 30 (simpler than changing $PYTHONSTARTUP environment variables every time).
31 31
32 32 * Session logging and reloading.
33 33
34 34 * Extensible syntax processing for special purpose situations.
35 35
36 36 * Access to the system shell with user-extensible alias system.
37 37
38 38 * Easily embeddable in other Python programs and GUIs.
39 39
40 40 * Integrated access to the pdb debugger and the Python profiler.
41 41
42 42 The latest development version is always available from IPython's `GitHub
43 43 site <http://github.com/ipython>`_.
44 44
45 45 license_file = LICENSE
46 46 project_urls =
47 47 Documentation = https://ipython.readthedocs.io/
48 48 Funding = https://numfocus.org/
49 49 Source = https://github.com/ipython/ipython
50 50 Tracker = https://github.com/ipython/ipython/issues
51 51 keywords = Interactive, Interpreter, Shell, Embedding
52 52 platforms = Linux, Mac OSX, Windows
53 53 classifiers =
54 54 Framework :: IPython
55 55 Intended Audience :: Developers
56 56 Intended Audience :: Science/Research
57 57 License :: OSI Approved :: BSD License
58 58 Programming Language :: Python
59 59 Programming Language :: Python :: 3
60 60 Programming Language :: Python :: 3 :: Only
61 61 Topic :: System :: Shell
62 62
63 63
64 64 [options]
65 65 packages = find:
66 66 python_requires = >=3.8
67 67 zip_safe = False
68 68 install_requires =
69 69 setuptools>=18.5
70 70 jedi>=0.16
71 71 decorator
72 72 pickleshare
73 73 traitlets>=5
74 74 prompt_toolkit>=2.0.0,<3.1.0,!=3.0.0,!=3.0.1
75 75 pygments
76 76 backcall
77 77 stack_data
78 78 matplotlib-inline
79 79 pexpect>4.3; sys_platform != "win32"
80 80 appnope; sys_platform == "darwin"
81 81 colorama; sys_platform == "win32"
82 82
83 83 [options.packages.find]
84 84 exclude =
85 85 setupext
86 86
87 87 [options.package_data]
88 88 IPython.core = profile/README*
89 89 IPython.core.tests = *.png, *.jpg, daft_extension/*.py
90 90 IPython.lib.tests = *.wav
91 91 IPython.testing.plugin = *.txt
92 92
93 93 [options.entry_points]
94 94 console_scripts =
95 95 ipython = IPython:start_ipython
96 96 ipython3 = IPython:start_ipython
97 97 pygments.lexers =
98 98 ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer
99 99 ipython = IPython.lib.lexers:IPythonLexer
100 100 ipython3 = IPython.lib.lexers:IPython3Lexer
101 101
102 102 [velin]
103 103 ignore_patterns =
104 IPython/core/tests,
104 IPython/core/tests
105 105 IPython/testing
106 106
107 107 [tool.black]
108 108 exclude = 'timing\.py'
General Comments 0
You need to be logged in to leave comments. Login now