##// END OF EJS Templates
@carreau comment's
Pierre Gerold -
Show More
@@ -1,129 +1,130 b''
1 1 """Implementation of magic functions that control various automatic behaviors.
2 2 """
3 3 from __future__ import print_function
4 from __future__ import absolute_import
4 5 #-----------------------------------------------------------------------------
5 6 # Copyright (c) 2012 The IPython Development Team.
6 7 #
7 8 # Distributed under the terms of the Modified BSD License.
8 9 #
9 10 # The full license is in the file COPYING.txt, distributed with this software.
10 11 #-----------------------------------------------------------------------------
11 12
12 13 #-----------------------------------------------------------------------------
13 14 # Imports
14 15 #-----------------------------------------------------------------------------
15 16
16 17 # Our own packages
17 18 from IPython.core.magic import Bunch, Magics, magics_class, line_magic
18 19 from IPython.testing.skipdoctest import skip_doctest
19 20 from logging import error
20 21
21 22 #-----------------------------------------------------------------------------
22 23 # Magic implementation classes
23 24 #-----------------------------------------------------------------------------
24 25
25 26 @magics_class
26 27 class AutoMagics(Magics):
27 28 """Magics that control various autoX behaviors."""
28 29
29 30 def __init__(self, shell):
30 31 super(AutoMagics, self).__init__(shell)
31 32 # namespace for holding state we may need
32 33 self._magic_state = Bunch()
33 34
34 35 @line_magic
35 36 def automagic(self, parameter_s=''):
36 37 """Make magic functions callable without having to type the initial %.
37 38
38 39 Without argumentsl toggles on/off (when off, you must call it as
39 40 %automagic, of course). With arguments it sets the value, and you can
40 41 use any of (case insensitive):
41 42
42 43 - on, 1, True: to activate
43 44
44 45 - off, 0, False: to deactivate.
45 46
46 47 Note that magic functions have lowest priority, so if there's a
47 48 variable whose name collides with that of a magic fn, automagic won't
48 49 work for that function (you get the variable instead). However, if you
49 50 delete the variable (del var), the previously shadowed magic function
50 51 becomes visible to automagic again."""
51 52
52 53 arg = parameter_s.lower()
53 54 mman = self.shell.magics_manager
54 55 if arg in ('on', '1', 'true'):
55 56 val = True
56 57 elif arg in ('off', '0', 'false'):
57 58 val = False
58 59 else:
59 60 val = not mman.auto_magic
60 61 mman.auto_magic = val
61 62 print('\n' + self.shell.magics_manager.auto_status())
62 63
63 64 @skip_doctest
64 65 @line_magic
65 66 def autocall(self, parameter_s=''):
66 67 """Make functions callable without having to type parentheses.
67 68
68 69 Usage:
69 70
70 71 %autocall [mode]
71 72
72 73 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
73 74 value is toggled on and off (remembering the previous state).
74 75
75 76 In more detail, these values mean:
76 77
77 78 0 -> fully disabled
78 79
79 80 1 -> active, but do not apply if there are no arguments on the line.
80 81
81 82 In this mode, you get::
82 83
83 84 In [1]: callable
84 85 Out[1]: <built-in function callable>
85 86
86 87 In [2]: callable 'hello'
87 88 ------> callable('hello')
88 89 Out[2]: False
89 90
90 91 2 -> Active always. Even if no arguments are present, the callable
91 92 object is called::
92 93
93 94 In [2]: float
94 95 ------> float()
95 96 Out[2]: 0.0
96 97
97 98 Note that even with autocall off, you can still use '/' at the start of
98 99 a line to treat the first argument on the command line as a function
99 100 and add parentheses to it::
100 101
101 102 In [8]: /str 43
102 103 ------> str(43)
103 104 Out[8]: '43'
104 105
105 106 # all-random (note for auto-testing)
106 107 """
107 108
108 109 if parameter_s:
109 110 arg = int(parameter_s)
110 111 else:
111 112 arg = 'toggle'
112 113
113 114 if not arg in (0, 1, 2, 'toggle'):
114 115 error('Valid modes: (0->Off, 1->Smart, 2->Full')
115 116 return
116 117
117 118 if arg in (0, 1, 2):
118 119 self.shell.autocall = arg
119 120 else: # toggle
120 121 if self.shell.autocall:
121 122 self._magic_state.autocall_save = self.shell.autocall
122 123 self.shell.autocall = 0
123 124 else:
124 125 try:
125 126 self.shell.autocall = self._magic_state.autocall_save
126 127 except AttributeError:
127 128 self.shell.autocall = self._magic_state.autocall_save = 1
128 129
129 130 print("Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall])
@@ -1,613 +1,614 b''
1 1 """Implementation of basic magic functions."""
2 2
3 3 from __future__ import print_function
4 from __future__ import absolute_import
4 5
5 6 import io
6 7 import sys
7 8 from pprint import pformat
8 9
9 10 from IPython.core import magic_arguments, page
10 11 from IPython.core.error import UsageError
11 12 from IPython.core.magic import Magics, magics_class, line_magic, magic_escapes
12 13 from IPython.utils.text import format_screen, dedent, indent
13 14 from IPython.testing.skipdoctest import skip_doctest
14 15 from IPython.utils.ipstruct import Struct
15 16 from IPython.utils.path import unquote_filename
16 17 from IPython.utils.py3compat import unicode_type
17 18 from warnings import warn
18 19 from logging import error
19 20
20 21
21 22 class MagicsDisplay(object):
22 23 def __init__(self, magics_manager):
23 24 self.magics_manager = magics_manager
24 25
25 26 def _lsmagic(self):
26 27 """The main implementation of the %lsmagic"""
27 28 mesc = magic_escapes['line']
28 29 cesc = magic_escapes['cell']
29 30 mman = self.magics_manager
30 31 magics = mman.lsmagic()
31 32 out = ['Available line magics:',
32 33 mesc + (' '+mesc).join(sorted(magics['line'])),
33 34 '',
34 35 'Available cell magics:',
35 36 cesc + (' '+cesc).join(sorted(magics['cell'])),
36 37 '',
37 38 mman.auto_status()]
38 39 return '\n'.join(out)
39 40
40 41 def _repr_pretty_(self, p, cycle):
41 42 p.text(self._lsmagic())
42 43
43 44 def __str__(self):
44 45 return self._lsmagic()
45 46
46 47 def _jsonable(self):
47 48 """turn magics dict into jsonable dict of the same structure
48 49
49 50 replaces object instances with their class names as strings
50 51 """
51 52 magic_dict = {}
52 53 mman = self.magics_manager
53 54 magics = mman.lsmagic()
54 55 for key, subdict in magics.items():
55 56 d = {}
56 57 magic_dict[key] = d
57 58 for name, obj in subdict.items():
58 59 try:
59 60 classname = obj.__self__.__class__.__name__
60 61 except AttributeError:
61 62 classname = 'Other'
62 63
63 64 d[name] = classname
64 65 return magic_dict
65 66
66 67 def _repr_json_(self):
67 68 return self._jsonable()
68 69
69 70
70 71 @magics_class
71 72 class BasicMagics(Magics):
72 73 """Magics that provide central IPython functionality.
73 74
74 75 These are various magics that don't fit into specific categories but that
75 76 are all part of the base 'IPython experience'."""
76 77
77 78 @magic_arguments.magic_arguments()
78 79 @magic_arguments.argument(
79 80 '-l', '--line', action='store_true',
80 81 help="""Create a line magic alias."""
81 82 )
82 83 @magic_arguments.argument(
83 84 '-c', '--cell', action='store_true',
84 85 help="""Create a cell magic alias."""
85 86 )
86 87 @magic_arguments.argument(
87 88 'name',
88 89 help="""Name of the magic to be created."""
89 90 )
90 91 @magic_arguments.argument(
91 92 'target',
92 93 help="""Name of the existing line or cell magic."""
93 94 )
94 95 @line_magic
95 96 def alias_magic(self, line=''):
96 97 """Create an alias for an existing line or cell magic.
97 98
98 99 Examples
99 100 --------
100 101 ::
101 102
102 103 In [1]: %alias_magic t timeit
103 104 Created `%t` as an alias for `%timeit`.
104 105 Created `%%t` as an alias for `%%timeit`.
105 106
106 107 In [2]: %t -n1 pass
107 108 1 loops, best of 3: 954 ns per loop
108 109
109 110 In [3]: %%t -n1
110 111 ...: pass
111 112 ...:
112 113 1 loops, best of 3: 954 ns per loop
113 114
114 115 In [4]: %alias_magic --cell whereami pwd
115 116 UsageError: Cell magic function `%%pwd` not found.
116 117 In [5]: %alias_magic --line whereami pwd
117 118 Created `%whereami` as an alias for `%pwd`.
118 119
119 120 In [6]: %whereami
120 121 Out[6]: u'/home/testuser'
121 122 """
122 123 args = magic_arguments.parse_argstring(self.alias_magic, line)
123 124 shell = self.shell
124 125 mman = self.shell.magics_manager
125 126 escs = ''.join(magic_escapes.values())
126 127
127 128 target = args.target.lstrip(escs)
128 129 name = args.name.lstrip(escs)
129 130
130 131 # Find the requested magics.
131 132 m_line = shell.find_magic(target, 'line')
132 133 m_cell = shell.find_magic(target, 'cell')
133 134 if args.line and m_line is None:
134 135 raise UsageError('Line magic function `%s%s` not found.' %
135 136 (magic_escapes['line'], target))
136 137 if args.cell and m_cell is None:
137 138 raise UsageError('Cell magic function `%s%s` not found.' %
138 139 (magic_escapes['cell'], target))
139 140
140 141 # If --line and --cell are not specified, default to the ones
141 142 # that are available.
142 143 if not args.line and not args.cell:
143 144 if not m_line and not m_cell:
144 145 raise UsageError(
145 146 'No line or cell magic with name `%s` found.' % target
146 147 )
147 148 args.line = bool(m_line)
148 149 args.cell = bool(m_cell)
149 150
150 151 if args.line:
151 152 mman.register_alias(name, target, 'line')
152 153 print('Created `%s%s` as an alias for `%s%s`.' % (
153 154 magic_escapes['line'], name,
154 155 magic_escapes['line'], target))
155 156
156 157 if args.cell:
157 158 mman.register_alias(name, target, 'cell')
158 159 print('Created `%s%s` as an alias for `%s%s`.' % (
159 160 magic_escapes['cell'], name,
160 161 magic_escapes['cell'], target))
161 162
162 163 @line_magic
163 164 def lsmagic(self, parameter_s=''):
164 165 """List currently available magic functions."""
165 166 return MagicsDisplay(self.shell.magics_manager)
166 167
167 168 def _magic_docs(self, brief=False, rest=False):
168 169 """Return docstrings from magic functions."""
169 170 mman = self.shell.magics_manager
170 171 docs = mman.lsmagic_docs(brief, missing='No documentation')
171 172
172 173 if rest:
173 174 format_string = '**%s%s**::\n\n%s\n\n'
174 175 else:
175 176 format_string = '%s%s:\n%s\n'
176 177
177 178 return ''.join(
178 179 [format_string % (magic_escapes['line'], fname,
179 180 indent(dedent(fndoc)))
180 181 for fname, fndoc in sorted(docs['line'].items())]
181 182 +
182 183 [format_string % (magic_escapes['cell'], fname,
183 184 indent(dedent(fndoc)))
184 185 for fname, fndoc in sorted(docs['cell'].items())]
185 186 )
186 187
187 188 @line_magic
188 189 def magic(self, parameter_s=''):
189 190 """Print information about the magic function system.
190 191
191 192 Supported formats: -latex, -brief, -rest
192 193 """
193 194
194 195 mode = ''
195 196 try:
196 197 mode = parameter_s.split()[0][1:]
197 198 except IndexError:
198 199 pass
199 200
200 201 brief = (mode == 'brief')
201 202 rest = (mode == 'rest')
202 203 magic_docs = self._magic_docs(brief, rest)
203 204
204 205 if mode == 'latex':
205 206 print(self.format_latex(magic_docs))
206 207 return
207 208 else:
208 209 magic_docs = format_screen(magic_docs)
209 210
210 211 out = ["""
211 212 IPython's 'magic' functions
212 213 ===========================
213 214
214 215 The magic function system provides a series of functions which allow you to
215 216 control the behavior of IPython itself, plus a lot of system-type
216 217 features. There are two kinds of magics, line-oriented and cell-oriented.
217 218
218 219 Line magics are prefixed with the % character and work much like OS
219 220 command-line calls: they get as an argument the rest of the line, where
220 221 arguments are passed without parentheses or quotes. For example, this will
221 222 time the given statement::
222 223
223 224 %timeit range(1000)
224 225
225 226 Cell magics are prefixed with a double %%, and they are functions that get as
226 227 an argument not only the rest of the line, but also the lines below it in a
227 228 separate argument. These magics are called with two arguments: the rest of the
228 229 call line and the body of the cell, consisting of the lines below the first.
229 230 For example::
230 231
231 232 %%timeit x = numpy.random.randn((100, 100))
232 233 numpy.linalg.svd(x)
233 234
234 235 will time the execution of the numpy svd routine, running the assignment of x
235 236 as part of the setup phase, which is not timed.
236 237
237 238 In a line-oriented client (the terminal or Qt console IPython), starting a new
238 239 input with %% will automatically enter cell mode, and IPython will continue
239 240 reading input until a blank line is given. In the notebook, simply type the
240 241 whole cell as one entity, but keep in mind that the %% escape can only be at
241 242 the very start of the cell.
242 243
243 244 NOTE: If you have 'automagic' enabled (via the command line option or with the
244 245 %automagic function), you don't need to type in the % explicitly for line
245 246 magics; cell magics always require an explicit '%%' escape. By default,
246 247 IPython ships with automagic on, so you should only rarely need the % escape.
247 248
248 249 Example: typing '%cd mydir' (without the quotes) changes your working directory
249 250 to 'mydir', if it exists.
250 251
251 252 For a list of the available magic functions, use %lsmagic. For a description
252 253 of any of them, type %magic_name?, e.g. '%cd?'.
253 254
254 255 Currently the magic system has the following functions:""",
255 256 magic_docs,
256 257 "Summary of magic functions (from %slsmagic):" % magic_escapes['line'],
257 258 str(self.lsmagic()),
258 259 ]
259 260 page.page('\n'.join(out))
260 261
261 262
262 263 @line_magic
263 264 def page(self, parameter_s=''):
264 265 """Pretty print the object and display it through a pager.
265 266
266 267 %page [options] OBJECT
267 268
268 269 If no object is given, use _ (last output).
269 270
270 271 Options:
271 272
272 273 -r: page str(object), don't pretty-print it."""
273 274
274 275 # After a function contributed by Olivier Aubert, slightly modified.
275 276
276 277 # Process options/args
277 278 opts, args = self.parse_options(parameter_s, 'r')
278 279 raw = 'r' in opts
279 280
280 281 oname = args and args or '_'
281 282 info = self.shell._ofind(oname)
282 283 if info['found']:
283 284 txt = (raw and str or pformat)( info['obj'] )
284 285 page.page(txt)
285 286 else:
286 287 print('Object `%s` not found' % oname)
287 288
288 289 @line_magic
289 290 def profile(self, parameter_s=''):
290 291 """Print your currently active IPython profile.
291 292
292 293 See Also
293 294 --------
294 295 prun : run code using the Python profiler
295 296 (:meth:`~IPython.core.magics.execution.ExecutionMagics.prun`)
296 297 """
297 298 warn("%profile is now deprecated. Please use get_ipython().profile instead.")
298 299 from IPython.core.application import BaseIPythonApplication
299 300 if BaseIPythonApplication.initialized():
300 301 print(BaseIPythonApplication.instance().profile)
301 302 else:
302 303 error("profile is an application-level value, but you don't appear to be in an IPython application")
303 304
304 305 @line_magic
305 306 def pprint(self, parameter_s=''):
306 307 """Toggle pretty printing on/off."""
307 308 ptformatter = self.shell.display_formatter.formatters['text/plain']
308 309 ptformatter.pprint = bool(1 - ptformatter.pprint)
309 310 print('Pretty printing has been turned',
310 311 ['OFF','ON'][ptformatter.pprint])
311 312
312 313 @line_magic
313 314 def colors(self, parameter_s=''):
314 315 """Switch color scheme for prompts, info system and exception handlers.
315 316
316 317 Currently implemented schemes: NoColor, Linux, LightBG.
317 318
318 319 Color scheme names are not case-sensitive.
319 320
320 321 Examples
321 322 --------
322 323 To get a plain black and white terminal::
323 324
324 325 %colors nocolor
325 326 """
326 327 def color_switch_err(name):
327 328 warn('Error changing %s color schemes.\n%s' %
328 329 (name, sys.exc_info()[1]))
329 330
330 331
331 332 new_scheme = parameter_s.strip()
332 333 if not new_scheme:
333 334 raise UsageError(
334 335 "%colors: you must specify a color scheme. See '%colors?'")
335 336 # local shortcut
336 337 shell = self.shell
337 338
338 339
339 340
340 341 if not shell.colors_force:
341 342 if sys.platform in {'win32', 'cli'}:
342 343 import IPython.utils.rlineimpl as readline
343 344 if not readline.have_readline:
344 345 msg = """\
345 346 Proper color support under MS Windows requires the pyreadline library.
346 347 You can find it at:
347 348 http://ipython.org/pyreadline.html
348 349
349 350 Defaulting color scheme to 'NoColor'"""
350 351 new_scheme = 'NoColor'
351 352 warn(msg)
352 353
353 354 elif not shell.has_readline:
354 355 # Coloured prompts get messed up without readline
355 356 # Will remove this check after switching to prompt_toolkit
356 357 new_scheme = 'NoColor'
357 358
358 359 # Set prompt colors
359 360 try:
360 361 shell.prompt_manager.color_scheme = new_scheme
361 362 except:
362 363 color_switch_err('prompt')
363 364 else:
364 365 shell.colors = \
365 366 shell.prompt_manager.color_scheme_table.active_scheme_name
366 367 # Set exception colors
367 368 try:
368 369 shell.InteractiveTB.set_colors(scheme = new_scheme)
369 370 shell.SyntaxTB.set_colors(scheme = new_scheme)
370 371 except:
371 372 color_switch_err('exception')
372 373
373 374 # Set info (for 'object?') colors
374 375 if shell.color_info:
375 376 try:
376 377 shell.inspector.set_active_scheme(new_scheme)
377 378 except:
378 379 color_switch_err('object inspector')
379 380 else:
380 381 shell.inspector.set_active_scheme('NoColor')
381 382
382 383 @line_magic
383 384 def xmode(self, parameter_s=''):
384 385 """Switch modes for the exception handlers.
385 386
386 387 Valid modes: Plain, Context and Verbose.
387 388
388 389 If called without arguments, acts as a toggle."""
389 390
390 391 def xmode_switch_err(name):
391 392 warn('Error changing %s exception modes.\n%s' %
392 393 (name,sys.exc_info()[1]))
393 394
394 395 shell = self.shell
395 396 new_mode = parameter_s.strip().capitalize()
396 397 try:
397 398 shell.InteractiveTB.set_mode(mode=new_mode)
398 399 print('Exception reporting mode:',shell.InteractiveTB.mode)
399 400 except:
400 401 xmode_switch_err('user')
401 402
402 403 @line_magic
403 404 def quickref(self,arg):
404 405 """ Show a quick reference sheet """
405 406 from IPython.core.usage import quick_reference
406 407 qr = quick_reference + self._magic_docs(brief=True)
407 408 page.page(qr)
408 409
409 410 @line_magic
410 411 def doctest_mode(self, parameter_s=''):
411 412 """Toggle doctest mode on and off.
412 413
413 414 This mode is intended to make IPython behave as much as possible like a
414 415 plain Python shell, from the perspective of how its prompts, exceptions
415 416 and output look. This makes it easy to copy and paste parts of a
416 417 session into doctests. It does so by:
417 418
418 419 - Changing the prompts to the classic ``>>>`` ones.
419 420 - Changing the exception reporting mode to 'Plain'.
420 421 - Disabling pretty-printing of output.
421 422
422 423 Note that IPython also supports the pasting of code snippets that have
423 424 leading '>>>' and '...' prompts in them. This means that you can paste
424 425 doctests from files or docstrings (even if they have leading
425 426 whitespace), and the code will execute correctly. You can then use
426 427 '%history -t' to see the translated history; this will give you the
427 428 input after removal of all the leading prompts and whitespace, which
428 429 can be pasted back into an editor.
429 430
430 431 With these features, you can switch into this mode easily whenever you
431 432 need to do testing and changes to doctests, without having to leave
432 433 your existing IPython session.
433 434 """
434 435
435 436 # Shorthands
436 437 shell = self.shell
437 438 pm = shell.prompt_manager
438 439 meta = shell.meta
439 440 disp_formatter = self.shell.display_formatter
440 441 ptformatter = disp_formatter.formatters['text/plain']
441 442 # dstore is a data store kept in the instance metadata bag to track any
442 443 # changes we make, so we can undo them later.
443 444 dstore = meta.setdefault('doctest_mode',Struct())
444 445 save_dstore = dstore.setdefault
445 446
446 447 # save a few values we'll need to recover later
447 448 mode = save_dstore('mode',False)
448 449 save_dstore('rc_pprint',ptformatter.pprint)
449 450 save_dstore('xmode',shell.InteractiveTB.mode)
450 451 save_dstore('rc_separate_out',shell.separate_out)
451 452 save_dstore('rc_separate_out2',shell.separate_out2)
452 453 save_dstore('rc_prompts_pad_left',pm.justify)
453 454 save_dstore('rc_separate_in',shell.separate_in)
454 455 save_dstore('rc_active_types',disp_formatter.active_types)
455 456 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
456 457
457 458 if not mode:
458 459 # turn on
459 460 pm.in_template = '>>> '
460 461 pm.in2_template = '... '
461 462 pm.out_template = ''
462 463
463 464 # Prompt separators like plain python
464 465 shell.separate_in = ''
465 466 shell.separate_out = ''
466 467 shell.separate_out2 = ''
467 468
468 469 pm.justify = False
469 470
470 471 ptformatter.pprint = False
471 472 disp_formatter.active_types = ['text/plain']
472 473
473 474 shell.magic('xmode Plain')
474 475 else:
475 476 # turn off
476 477 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
477 478
478 479 shell.separate_in = dstore.rc_separate_in
479 480
480 481 shell.separate_out = dstore.rc_separate_out
481 482 shell.separate_out2 = dstore.rc_separate_out2
482 483
483 484 pm.justify = dstore.rc_prompts_pad_left
484 485
485 486 ptformatter.pprint = dstore.rc_pprint
486 487 disp_formatter.active_types = dstore.rc_active_types
487 488
488 489 shell.magic('xmode ' + dstore.xmode)
489 490
490 491 # Store new mode and inform
491 492 dstore.mode = bool(1-int(mode))
492 493 mode_label = ['OFF','ON'][dstore.mode]
493 494 print('Doctest mode is:', mode_label)
494 495
495 496 @line_magic
496 497 def gui(self, parameter_s=''):
497 498 """Enable or disable IPython GUI event loop integration.
498 499
499 500 %gui [GUINAME]
500 501
501 502 This magic replaces IPython's threaded shells that were activated
502 503 using the (pylab/wthread/etc.) command line flags. GUI toolkits
503 504 can now be enabled at runtime and keyboard
504 505 interrupts should work without any problems. The following toolkits
505 506 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
506 507
507 508 %gui wx # enable wxPython event loop integration
508 509 %gui qt4|qt # enable PyQt4 event loop integration
509 510 %gui qt5 # enable PyQt5 event loop integration
510 511 %gui gtk # enable PyGTK event loop integration
511 512 %gui gtk3 # enable Gtk3 event loop integration
512 513 %gui tk # enable Tk event loop integration
513 514 %gui osx # enable Cocoa event loop integration
514 515 # (requires %matplotlib 1.1)
515 516 %gui # disable all event loop integration
516 517
517 518 WARNING: after any of these has been called you can simply create
518 519 an application object, but DO NOT start the event loop yourself, as
519 520 we have already handled that.
520 521 """
521 522 opts, arg = self.parse_options(parameter_s, '')
522 523 if arg=='': arg = None
523 524 try:
524 525 return self.shell.enable_gui(arg)
525 526 except Exception as e:
526 527 # print simple error message, rather than traceback if we can't
527 528 # hook up the GUI
528 529 error(str(e))
529 530
530 531 @skip_doctest
531 532 @line_magic
532 533 def precision(self, s=''):
533 534 """Set floating point precision for pretty printing.
534 535
535 536 Can set either integer precision or a format string.
536 537
537 538 If numpy has been imported and precision is an int,
538 539 numpy display precision will also be set, via ``numpy.set_printoptions``.
539 540
540 541 If no argument is given, defaults will be restored.
541 542
542 543 Examples
543 544 --------
544 545 ::
545 546
546 547 In [1]: from math import pi
547 548
548 549 In [2]: %precision 3
549 550 Out[2]: u'%.3f'
550 551
551 552 In [3]: pi
552 553 Out[3]: 3.142
553 554
554 555 In [4]: %precision %i
555 556 Out[4]: u'%i'
556 557
557 558 In [5]: pi
558 559 Out[5]: 3
559 560
560 561 In [6]: %precision %e
561 562 Out[6]: u'%e'
562 563
563 564 In [7]: pi**10
564 565 Out[7]: 9.364805e+04
565 566
566 567 In [8]: %precision
567 568 Out[8]: u'%r'
568 569
569 570 In [9]: pi**10
570 571 Out[9]: 93648.047476082982
571 572 """
572 573 ptformatter = self.shell.display_formatter.formatters['text/plain']
573 574 ptformatter.float_precision = s
574 575 return ptformatter.float_format
575 576
576 577 @magic_arguments.magic_arguments()
577 578 @magic_arguments.argument(
578 579 '-e', '--export', action='store_true', default=False,
579 580 help='Export IPython history as a notebook. The filename argument '
580 581 'is used to specify the notebook name and format. For example '
581 582 'a filename of notebook.ipynb will result in a notebook name '
582 583 'of "notebook" and a format of "json". Likewise using a ".py" '
583 584 'file extension will write the notebook as a Python script'
584 585 )
585 586 @magic_arguments.argument(
586 587 'filename', type=unicode_type,
587 588 help='Notebook name or filename'
588 589 )
589 590 @line_magic
590 591 def notebook(self, s):
591 592 """Export and convert IPython notebooks.
592 593
593 594 This function can export the current IPython history to a notebook file.
594 595 For example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
595 596 To export the history to "foo.py" do "%notebook -e foo.py".
596 597 """
597 598 args = magic_arguments.parse_argstring(self.notebook, s)
598 599
599 600 from nbformat import write, v4
600 601 args.filename = unquote_filename(args.filename)
601 602 if args.export:
602 603 cells = []
603 604 hist = list(self.shell.history_manager.get_range())
604 605 if(len(hist)<=1):
605 606 raise ValueError('History is empty, cannot export')
606 607 for session, execution_count, source in hist[:-1]:
607 608 cells.append(v4.new_code_cell(
608 609 execution_count=execution_count,
609 610 source=source
610 611 ))
611 612 nb = v4.new_notebook(cells=cells)
612 613 with io.open(args.filename, 'w', encoding='utf-8') as f:
613 614 write(nb, f, version=4)
@@ -1,716 +1,717 b''
1 1 """Implementation of code management magic functions.
2 2 """
3 3 from __future__ import print_function
4 from __future__ import absolute_import
4 5 #-----------------------------------------------------------------------------
5 6 # Copyright (c) 2012 The IPython Development Team.
6 7 #
7 8 # Distributed under the terms of the Modified BSD License.
8 9 #
9 10 # The full license is in the file COPYING.txt, distributed with this software.
10 11 #-----------------------------------------------------------------------------
11 12
12 13 #-----------------------------------------------------------------------------
13 14 # Imports
14 15 #-----------------------------------------------------------------------------
15 16
16 17 # Stdlib
17 18 import inspect
18 19 import io
19 20 import os
20 21 import re
21 22 import sys
22 23 import ast
23 24 from itertools import chain
24 25
25 26 # Our own packages
26 27 from IPython.core.error import TryNext, StdinNotImplementedError, UsageError
27 28 from IPython.core.macro import Macro
28 29 from IPython.core.magic import Magics, magics_class, line_magic
29 30 from IPython.core.oinspect import find_file, find_source_lines
30 31 from IPython.testing.skipdoctest import skip_doctest
31 32 from IPython.utils import py3compat
32 33 from IPython.utils.py3compat import string_types
33 34 from IPython.utils.contexts import preserve_keys
34 35 from IPython.utils.path import get_py_filename, unquote_filename
35 36 from warnings import warn
36 37 from logging import error
37 38 from IPython.utils.text import get_text_list
38 39
39 40 #-----------------------------------------------------------------------------
40 41 # Magic implementation classes
41 42 #-----------------------------------------------------------------------------
42 43
43 44 # Used for exception handling in magic_edit
44 45 class MacroToEdit(ValueError): pass
45 46
46 47 ipython_input_pat = re.compile(r"<ipython\-input\-(\d+)-[a-z\d]+>$")
47 48
48 49 # To match, e.g. 8-10 1:5 :10 3-
49 50 range_re = re.compile(r"""
50 51 (?P<start>\d+)?
51 52 ((?P<sep>[\-:])
52 53 (?P<end>\d+)?)?
53 54 $""", re.VERBOSE)
54 55
55 56
56 57 def extract_code_ranges(ranges_str):
57 58 """Turn a string of range for %%load into 2-tuples of (start, stop)
58 59 ready to use as a slice of the content splitted by lines.
59 60
60 61 Examples
61 62 --------
62 63 list(extract_input_ranges("5-10 2"))
63 64 [(4, 10), (1, 2)]
64 65 """
65 66 for range_str in ranges_str.split():
66 67 rmatch = range_re.match(range_str)
67 68 if not rmatch:
68 69 continue
69 70 sep = rmatch.group("sep")
70 71 start = rmatch.group("start")
71 72 end = rmatch.group("end")
72 73
73 74 if sep == '-':
74 75 start = int(start) - 1 if start else None
75 76 end = int(end) if end else None
76 77 elif sep == ':':
77 78 start = int(start) - 1 if start else None
78 79 end = int(end) - 1 if end else None
79 80 else:
80 81 end = int(start)
81 82 start = int(start) - 1
82 83 yield (start, end)
83 84
84 85
85 86 @skip_doctest
86 87 def extract_symbols(code, symbols):
87 88 """
88 89 Return a tuple (blocks, not_found)
89 90 where ``blocks`` is a list of code fragments
90 91 for each symbol parsed from code, and ``not_found`` are
91 92 symbols not found in the code.
92 93
93 94 For example::
94 95
95 96 >>> code = '''a = 10
96 97
97 98 def b(): return 42
98 99
99 100 class A: pass'''
100 101
101 102 >>> extract_symbols(code, 'A,b,z')
102 103 (["class A: pass", "def b(): return 42"], ['z'])
103 104 """
104 105 symbols = symbols.split(',')
105 106
106 107 # this will raise SyntaxError if code isn't valid Python
107 108 py_code = ast.parse(code)
108 109
109 110 marks = [(getattr(s, 'name', None), s.lineno) for s in py_code.body]
110 111 code = code.split('\n')
111 112
112 113 symbols_lines = {}
113 114
114 115 # we already know the start_lineno of each symbol (marks).
115 116 # To find each end_lineno, we traverse in reverse order until each
116 117 # non-blank line
117 118 end = len(code)
118 119 for name, start in reversed(marks):
119 120 while not code[end - 1].strip():
120 121 end -= 1
121 122 if name:
122 123 symbols_lines[name] = (start - 1, end)
123 124 end = start - 1
124 125
125 126 # Now symbols_lines is a map
126 127 # {'symbol_name': (start_lineno, end_lineno), ...}
127 128
128 129 # fill a list with chunks of codes for each requested symbol
129 130 blocks = []
130 131 not_found = []
131 132 for symbol in symbols:
132 133 if symbol in symbols_lines:
133 134 start, end = symbols_lines[symbol]
134 135 blocks.append('\n'.join(code[start:end]) + '\n')
135 136 else:
136 137 not_found.append(symbol)
137 138
138 139 return blocks, not_found
139 140
140 141
141 142 class InteractivelyDefined(Exception):
142 143 """Exception for interactively defined variable in magic_edit"""
143 144 def __init__(self, index):
144 145 self.index = index
145 146
146 147
147 148 @magics_class
148 149 class CodeMagics(Magics):
149 150 """Magics related to code management (loading, saving, editing, ...)."""
150 151
151 152 def __init__(self, *args, **kwargs):
152 153 self._knowntemps = set()
153 154 super(CodeMagics, self).__init__(*args, **kwargs)
154 155
155 156 @line_magic
156 157 def save(self, parameter_s=''):
157 158 """Save a set of lines or a macro to a given filename.
158 159
159 160 Usage:\\
160 161 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
161 162
162 163 Options:
163 164
164 165 -r: use 'raw' input. By default, the 'processed' history is used,
165 166 so that magics are loaded in their transformed version to valid
166 167 Python. If this option is given, the raw input as typed as the
167 168 command line is used instead.
168 169
169 170 -f: force overwrite. If file exists, %save will prompt for overwrite
170 171 unless -f is given.
171 172
172 173 -a: append to the file instead of overwriting it.
173 174
174 175 This function uses the same syntax as %history for input ranges,
175 176 then saves the lines to the filename you specify.
176 177
177 178 It adds a '.py' extension to the file if you don't do so yourself, and
178 179 it asks for confirmation before overwriting existing files.
179 180
180 181 If `-r` option is used, the default extension is `.ipy`.
181 182 """
182 183
183 184 opts,args = self.parse_options(parameter_s,'fra',mode='list')
184 185 if not args:
185 186 raise UsageError('Missing filename.')
186 187 raw = 'r' in opts
187 188 force = 'f' in opts
188 189 append = 'a' in opts
189 190 mode = 'a' if append else 'w'
190 191 ext = u'.ipy' if raw else u'.py'
191 192 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
192 193 if not fname.endswith((u'.py',u'.ipy')):
193 194 fname += ext
194 195 file_exists = os.path.isfile(fname)
195 196 if file_exists and not force and not append:
196 197 try:
197 198 overwrite = self.shell.ask_yes_no('File `%s` exists. Overwrite (y/[N])? ' % fname, default='n')
198 199 except StdinNotImplementedError:
199 200 print("File `%s` exists. Use `%%save -f %s` to force overwrite" % (fname, parameter_s))
200 201 return
201 202 if not overwrite :
202 203 print('Operation cancelled.')
203 204 return
204 205 try:
205 206 cmds = self.shell.find_user_code(codefrom,raw)
206 207 except (TypeError, ValueError) as e:
207 208 print(e.args[0])
208 209 return
209 210 out = py3compat.cast_unicode(cmds)
210 211 with io.open(fname, mode, encoding="utf-8") as f:
211 212 if not file_exists or not append:
212 213 f.write(u"# coding: utf-8\n")
213 214 f.write(out)
214 215 # make sure we end on a newline
215 216 if not out.endswith(u'\n'):
216 217 f.write(u'\n')
217 218 print('The following commands were written to file `%s`:' % fname)
218 219 print(cmds)
219 220
220 221 @line_magic
221 222 def pastebin(self, parameter_s=''):
222 223 """Upload code to Github's Gist paste bin, returning the URL.
223 224
224 225 Usage:\\
225 226 %pastebin [-d "Custom description"] 1-7
226 227
227 228 The argument can be an input history range, a filename, or the name of a
228 229 string or macro.
229 230
230 231 Options:
231 232
232 233 -d: Pass a custom description for the gist. The default will say
233 234 "Pasted from IPython".
234 235 """
235 236 opts, args = self.parse_options(parameter_s, 'd:')
236 237
237 238 try:
238 239 code = self.shell.find_user_code(args)
239 240 except (ValueError, TypeError) as e:
240 241 print(e.args[0])
241 242 return
242 243
243 244 # Deferred import
244 245 try:
245 246 from urllib.request import urlopen # Py 3
246 247 except ImportError:
247 248 from urllib2 import urlopen
248 249 import json
249 250 post_data = json.dumps({
250 251 "description": opts.get('d', "Pasted from IPython"),
251 252 "public": True,
252 253 "files": {
253 254 "file1.py": {
254 255 "content": code
255 256 }
256 257 }
257 258 }).encode('utf-8')
258 259
259 260 response = urlopen("https://api.github.com/gists", post_data)
260 261 response_data = json.loads(response.read().decode('utf-8'))
261 262 return response_data['html_url']
262 263
263 264 @line_magic
264 265 def loadpy(self, arg_s):
265 266 """Alias of `%load`
266 267
267 268 `%loadpy` has gained some flexibility and dropped the requirement of a `.py`
268 269 extension. So it has been renamed simply into %load. You can look at
269 270 `%load`'s docstring for more info.
270 271 """
271 272 self.load(arg_s)
272 273
273 274 @line_magic
274 275 def load(self, arg_s):
275 276 """Load code into the current frontend.
276 277
277 278 Usage:\\
278 279 %load [options] source
279 280
280 281 where source can be a filename, URL, input history range, macro, or
281 282 element in the user namespace
282 283
283 284 Options:
284 285
285 286 -r <lines>: Specify lines or ranges of lines to load from the source.
286 287 Ranges could be specified as x-y (x..y) or in python-style x:y
287 288 (x..(y-1)). Both limits x and y can be left blank (meaning the
288 289 beginning and end of the file, respectively).
289 290
290 291 -s <symbols>: Specify function or classes to load from python source.
291 292
292 293 -y : Don't ask confirmation for loading source above 200 000 characters.
293 294
294 295 -n : Include the user's namespace when searching for source code.
295 296
296 297 This magic command can either take a local filename, a URL, an history
297 298 range (see %history) or a macro as argument, it will prompt for
298 299 confirmation before loading source with more than 200 000 characters, unless
299 300 -y flag is passed or if the frontend does not support raw_input::
300 301
301 302 %load myscript.py
302 303 %load 7-27
303 304 %load myMacro
304 305 %load http://www.example.com/myscript.py
305 306 %load -r 5-10 myscript.py
306 307 %load -r 10-20,30,40: foo.py
307 308 %load -s MyClass,wonder_function myscript.py
308 309 %load -n MyClass
309 310 %load -n my_module.wonder_function
310 311 """
311 312 opts,args = self.parse_options(arg_s,'yns:r:')
312 313
313 314 if not args:
314 315 raise UsageError('Missing filename, URL, input history range, '
315 316 'macro, or element in the user namespace.')
316 317
317 318 search_ns = 'n' in opts
318 319
319 320 contents = self.shell.find_user_code(args, search_ns=search_ns)
320 321
321 322 if 's' in opts:
322 323 try:
323 324 blocks, not_found = extract_symbols(contents, opts['s'])
324 325 except SyntaxError:
325 326 # non python code
326 327 error("Unable to parse the input as valid Python code")
327 328 return
328 329
329 330 if len(not_found) == 1:
330 331 warn('The symbol `%s` was not found' % not_found[0])
331 332 elif len(not_found) > 1:
332 333 warn('The symbols %s were not found' % get_text_list(not_found,
333 334 wrap_item_with='`')
334 335 )
335 336
336 337 contents = '\n'.join(blocks)
337 338
338 339 if 'r' in opts:
339 340 ranges = opts['r'].replace(',', ' ')
340 341 lines = contents.split('\n')
341 342 slices = extract_code_ranges(ranges)
342 343 contents = [lines[slice(*slc)] for slc in slices]
343 344 contents = '\n'.join(chain.from_iterable(contents))
344 345
345 346 l = len(contents)
346 347
347 348 # 200 000 is ~ 2500 full 80 caracter lines
348 349 # so in average, more than 5000 lines
349 350 if l > 200000 and 'y' not in opts:
350 351 try:
351 352 ans = self.shell.ask_yes_no(("The text you're trying to load seems pretty big"\
352 353 " (%d characters). Continue (y/[N]) ?" % l), default='n' )
353 354 except StdinNotImplementedError:
354 355 #asume yes if raw input not implemented
355 356 ans = True
356 357
357 358 if ans is False :
358 359 print('Operation cancelled.')
359 360 return
360 361
361 362 contents = "# %load {}\n".format(arg_s) + contents
362 363
363 364 self.shell.set_next_input(contents, replace=True)
364 365
365 366 @staticmethod
366 367 def _find_edit_target(shell, args, opts, last_call):
367 368 """Utility method used by magic_edit to find what to edit."""
368 369
369 370 def make_filename(arg):
370 371 "Make a filename from the given args"
371 372 arg = unquote_filename(arg)
372 373 try:
373 374 filename = get_py_filename(arg)
374 375 except IOError:
375 376 # If it ends with .py but doesn't already exist, assume we want
376 377 # a new file.
377 378 if arg.endswith('.py'):
378 379 filename = arg
379 380 else:
380 381 filename = None
381 382 return filename
382 383
383 384 # Set a few locals from the options for convenience:
384 385 opts_prev = 'p' in opts
385 386 opts_raw = 'r' in opts
386 387
387 388 # custom exceptions
388 389 class DataIsObject(Exception): pass
389 390
390 391 # Default line number value
391 392 lineno = opts.get('n',None)
392 393
393 394 if opts_prev:
394 395 args = '_%s' % last_call[0]
395 396 if args not in shell.user_ns:
396 397 args = last_call[1]
397 398
398 399 # by default this is done with temp files, except when the given
399 400 # arg is a filename
400 401 use_temp = True
401 402
402 403 data = ''
403 404
404 405 # First, see if the arguments should be a filename.
405 406 filename = make_filename(args)
406 407 if filename:
407 408 use_temp = False
408 409 elif args:
409 410 # Mode where user specifies ranges of lines, like in %macro.
410 411 data = shell.extract_input_lines(args, opts_raw)
411 412 if not data:
412 413 try:
413 414 # Load the parameter given as a variable. If not a string,
414 415 # process it as an object instead (below)
415 416
416 417 #print '*** args',args,'type',type(args) # dbg
417 418 data = eval(args, shell.user_ns)
418 419 if not isinstance(data, string_types):
419 420 raise DataIsObject
420 421
421 422 except (NameError,SyntaxError):
422 423 # given argument is not a variable, try as a filename
423 424 filename = make_filename(args)
424 425 if filename is None:
425 426 warn("Argument given (%s) can't be found as a variable "
426 427 "or as a filename." % args)
427 428 return (None, None, None)
428 429 use_temp = False
429 430
430 431 except DataIsObject:
431 432 # macros have a special edit function
432 433 if isinstance(data, Macro):
433 434 raise MacroToEdit(data)
434 435
435 436 # For objects, try to edit the file where they are defined
436 437 filename = find_file(data)
437 438 if filename:
438 439 if 'fakemodule' in filename.lower() and \
439 440 inspect.isclass(data):
440 441 # class created by %edit? Try to find source
441 442 # by looking for method definitions instead, the
442 443 # __module__ in those classes is FakeModule.
443 444 attrs = [getattr(data, aname) for aname in dir(data)]
444 445 for attr in attrs:
445 446 if not inspect.ismethod(attr):
446 447 continue
447 448 filename = find_file(attr)
448 449 if filename and \
449 450 'fakemodule' not in filename.lower():
450 451 # change the attribute to be the edit
451 452 # target instead
452 453 data = attr
453 454 break
454 455
455 456 m = ipython_input_pat.match(os.path.basename(filename))
456 457 if m:
457 458 raise InteractivelyDefined(int(m.groups()[0]))
458 459
459 460 datafile = 1
460 461 if filename is None:
461 462 filename = make_filename(args)
462 463 datafile = 1
463 464 if filename is not None:
464 465 # only warn about this if we get a real name
465 466 warn('Could not find file where `%s` is defined.\n'
466 467 'Opening a file named `%s`' % (args, filename))
467 468 # Now, make sure we can actually read the source (if it was
468 469 # in a temp file it's gone by now).
469 470 if datafile:
470 471 if lineno is None:
471 472 lineno = find_source_lines(data)
472 473 if lineno is None:
473 474 filename = make_filename(args)
474 475 if filename is None:
475 476 warn('The file where `%s` was defined '
476 477 'cannot be read or found.' % data)
477 478 return (None, None, None)
478 479 use_temp = False
479 480
480 481 if use_temp:
481 482 filename = shell.mktempfile(data)
482 483 print('IPython will make a temporary file named:',filename)
483 484
484 485 # use last_call to remember the state of the previous call, but don't
485 486 # let it be clobbered by successive '-p' calls.
486 487 try:
487 488 last_call[0] = shell.displayhook.prompt_count
488 489 if not opts_prev:
489 490 last_call[1] = args
490 491 except:
491 492 pass
492 493
493 494
494 495 return filename, lineno, use_temp
495 496
496 497 def _edit_macro(self,mname,macro):
497 498 """open an editor with the macro data in a file"""
498 499 filename = self.shell.mktempfile(macro.value)
499 500 self.shell.hooks.editor(filename)
500 501
501 502 # and make a new macro object, to replace the old one
502 503 with open(filename) as mfile:
503 504 mvalue = mfile.read()
504 505 self.shell.user_ns[mname] = Macro(mvalue)
505 506
506 507 @skip_doctest
507 508 @line_magic
508 509 def edit(self, parameter_s='',last_call=['','']):
509 510 """Bring up an editor and execute the resulting code.
510 511
511 512 Usage:
512 513 %edit [options] [args]
513 514
514 515 %edit runs IPython's editor hook. The default version of this hook is
515 516 set to call the editor specified by your $EDITOR environment variable.
516 517 If this isn't found, it will default to vi under Linux/Unix and to
517 518 notepad under Windows. See the end of this docstring for how to change
518 519 the editor hook.
519 520
520 521 You can also set the value of this editor via the
521 522 ``TerminalInteractiveShell.editor`` option in your configuration file.
522 523 This is useful if you wish to use a different editor from your typical
523 524 default with IPython (and for Windows users who typically don't set
524 525 environment variables).
525 526
526 527 This command allows you to conveniently edit multi-line code right in
527 528 your IPython session.
528 529
529 530 If called without arguments, %edit opens up an empty editor with a
530 531 temporary file and will execute the contents of this file when you
531 532 close it (don't forget to save it!).
532 533
533 534
534 535 Options:
535 536
536 537 -n <number>: open the editor at a specified line number. By default,
537 538 the IPython editor hook uses the unix syntax 'editor +N filename', but
538 539 you can configure this by providing your own modified hook if your
539 540 favorite editor supports line-number specifications with a different
540 541 syntax.
541 542
542 543 -p: this will call the editor with the same data as the previous time
543 544 it was used, regardless of how long ago (in your current session) it
544 545 was.
545 546
546 547 -r: use 'raw' input. This option only applies to input taken from the
547 548 user's history. By default, the 'processed' history is used, so that
548 549 magics are loaded in their transformed version to valid Python. If
549 550 this option is given, the raw input as typed as the command line is
550 551 used instead. When you exit the editor, it will be executed by
551 552 IPython's own processor.
552 553
553 554 -x: do not execute the edited code immediately upon exit. This is
554 555 mainly useful if you are editing programs which need to be called with
555 556 command line arguments, which you can then do using %run.
556 557
557 558
558 559 Arguments:
559 560
560 561 If arguments are given, the following possibilities exist:
561 562
562 563 - If the argument is a filename, IPython will load that into the
563 564 editor. It will execute its contents with execfile() when you exit,
564 565 loading any code in the file into your interactive namespace.
565 566
566 567 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
567 568 The syntax is the same as in the %history magic.
568 569
569 570 - If the argument is a string variable, its contents are loaded
570 571 into the editor. You can thus edit any string which contains
571 572 python code (including the result of previous edits).
572 573
573 574 - If the argument is the name of an object (other than a string),
574 575 IPython will try to locate the file where it was defined and open the
575 576 editor at the point where it is defined. You can use `%edit function`
576 577 to load an editor exactly at the point where 'function' is defined,
577 578 edit it and have the file be executed automatically.
578 579
579 580 - If the object is a macro (see %macro for details), this opens up your
580 581 specified editor with a temporary file containing the macro's data.
581 582 Upon exit, the macro is reloaded with the contents of the file.
582 583
583 584 Note: opening at an exact line is only supported under Unix, and some
584 585 editors (like kedit and gedit up to Gnome 2.8) do not understand the
585 586 '+NUMBER' parameter necessary for this feature. Good editors like
586 587 (X)Emacs, vi, jed, pico and joe all do.
587 588
588 589 After executing your code, %edit will return as output the code you
589 590 typed in the editor (except when it was an existing file). This way
590 591 you can reload the code in further invocations of %edit as a variable,
591 592 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
592 593 the output.
593 594
594 595 Note that %edit is also available through the alias %ed.
595 596
596 597 This is an example of creating a simple function inside the editor and
597 598 then modifying it. First, start up the editor::
598 599
599 600 In [1]: edit
600 601 Editing... done. Executing edited code...
601 602 Out[1]: 'def foo():\\n print "foo() was defined in an editing
602 603 session"\\n'
603 604
604 605 We can then call the function foo()::
605 606
606 607 In [2]: foo()
607 608 foo() was defined in an editing session
608 609
609 610 Now we edit foo. IPython automatically loads the editor with the
610 611 (temporary) file where foo() was previously defined::
611 612
612 613 In [3]: edit foo
613 614 Editing... done. Executing edited code...
614 615
615 616 And if we call foo() again we get the modified version::
616 617
617 618 In [4]: foo()
618 619 foo() has now been changed!
619 620
620 621 Here is an example of how to edit a code snippet successive
621 622 times. First we call the editor::
622 623
623 624 In [5]: edit
624 625 Editing... done. Executing edited code...
625 626 hello
626 627 Out[5]: "print 'hello'\\n"
627 628
628 629 Now we call it again with the previous output (stored in _)::
629 630
630 631 In [6]: edit _
631 632 Editing... done. Executing edited code...
632 633 hello world
633 634 Out[6]: "print 'hello world'\\n"
634 635
635 636 Now we call it with the output #8 (stored in _8, also as Out[8])::
636 637
637 638 In [7]: edit _8
638 639 Editing... done. Executing edited code...
639 640 hello again
640 641 Out[7]: "print 'hello again'\\n"
641 642
642 643
643 644 Changing the default editor hook:
644 645
645 646 If you wish to write your own editor hook, you can put it in a
646 647 configuration file which you load at startup time. The default hook
647 648 is defined in the IPython.core.hooks module, and you can use that as a
648 649 starting example for further modifications. That file also has
649 650 general instructions on how to set a new hook for use once you've
650 651 defined it."""
651 652 opts,args = self.parse_options(parameter_s,'prxn:')
652 653
653 654 try:
654 655 filename, lineno, is_temp = self._find_edit_target(self.shell,
655 656 args, opts, last_call)
656 657 except MacroToEdit as e:
657 658 self._edit_macro(args, e.args[0])
658 659 return
659 660 except InteractivelyDefined as e:
660 661 print("Editing In[%i]" % e.index)
661 662 args = str(e.index)
662 663 filename, lineno, is_temp = self._find_edit_target(self.shell,
663 664 args, opts, last_call)
664 665 if filename is None:
665 666 # nothing was found, warnings have already been issued,
666 667 # just give up.
667 668 return
668 669
669 670 if is_temp:
670 671 self._knowntemps.add(filename)
671 672 elif (filename in self._knowntemps):
672 673 is_temp = True
673 674
674 675
675 676 # do actual editing here
676 677 print('Editing...', end=' ')
677 678 sys.stdout.flush()
678 679 try:
679 680 # Quote filenames that may have spaces in them
680 681 if ' ' in filename:
681 682 filename = "'%s'" % filename
682 683 self.shell.hooks.editor(filename,lineno)
683 684 except TryNext:
684 685 warn('Could not open editor')
685 686 return
686 687
687 688 # XXX TODO: should this be generalized for all string vars?
688 689 # For now, this is special-cased to blocks created by cpaste
689 690 if args.strip() == 'pasted_block':
690 691 with open(filename, 'r') as f:
691 692 self.shell.user_ns['pasted_block'] = f.read()
692 693
693 694 if 'x' in opts: # -x prevents actual execution
694 695 print()
695 696 else:
696 697 print('done. Executing edited code...')
697 698 with preserve_keys(self.shell.user_ns, '__file__'):
698 699 if not is_temp:
699 700 self.shell.user_ns['__file__'] = filename
700 701 if 'r' in opts: # Untranslated IPython code
701 702 with open(filename, 'r') as f:
702 703 source = f.read()
703 704 self.shell.run_cell(source, store_history=False)
704 705 else:
705 706 self.shell.safe_execfile(filename, self.shell.user_ns,
706 707 self.shell.user_ns)
707 708
708 709 if is_temp:
709 710 try:
710 711 return open(filename).read()
711 712 except IOError as msg:
712 713 if msg.filename == filename:
713 714 warn('File not found. Did you forget to save?')
714 715 return
715 716 else:
716 717 self.shell.showtraceback()
@@ -1,159 +1,160 b''
1 1 """Implementation of configuration-related magic functions.
2 2 """
3 3 from __future__ import print_function
4 from __future__ import absolute_import
4 5 #-----------------------------------------------------------------------------
5 6 # Copyright (c) 2012 The IPython Development Team.
6 7 #
7 8 # Distributed under the terms of the Modified BSD License.
8 9 #
9 10 # The full license is in the file COPYING.txt, distributed with this software.
10 11 #-----------------------------------------------------------------------------
11 12
12 13 #-----------------------------------------------------------------------------
13 14 # Imports
14 15 #-----------------------------------------------------------------------------
15 16
16 17 # Stdlib
17 18 import re
18 19
19 20 # Our own packages
20 21 from IPython.core.error import UsageError
21 22 from IPython.core.magic import Magics, magics_class, line_magic
22 23 from logging import error
23 24
24 25 #-----------------------------------------------------------------------------
25 26 # Magic implementation classes
26 27 #-----------------------------------------------------------------------------
27 28
28 29 reg = re.compile('^\w+\.\w+$')
29 30 @magics_class
30 31 class ConfigMagics(Magics):
31 32
32 33 def __init__(self, shell):
33 34 super(ConfigMagics, self).__init__(shell)
34 35 self.configurables = []
35 36
36 37 @line_magic
37 38 def config(self, s):
38 39 """configure IPython
39 40
40 41 %config Class[.trait=value]
41 42
42 43 This magic exposes most of the IPython config system. Any
43 44 Configurable class should be able to be configured with the simple
44 45 line::
45 46
46 47 %config Class.trait=value
47 48
48 49 Where `value` will be resolved in the user's namespace, if it is an
49 50 expression or variable name.
50 51
51 52 Examples
52 53 --------
53 54
54 55 To see what classes are available for config, pass no arguments::
55 56
56 57 In [1]: %config
57 58 Available objects for config:
58 59 TerminalInteractiveShell
59 60 HistoryManager
60 61 PrefilterManager
61 62 AliasManager
62 63 IPCompleter
63 64 PromptManager
64 65 DisplayFormatter
65 66
66 67 To view what is configurable on a given class, just pass the class
67 68 name::
68 69
69 70 In [2]: %config IPCompleter
70 71 IPCompleter options
71 72 -----------------
72 73 IPCompleter.omit__names=<Enum>
73 74 Current: 2
74 75 Choices: (0, 1, 2)
75 76 Instruct the completer to omit private method names
76 77 Specifically, when completing on ``object.<tab>``.
77 78 When 2 [default]: all names that start with '_' will be excluded.
78 79 When 1: all 'magic' names (``__foo__``) will be excluded.
79 80 When 0: nothing will be excluded.
80 81 IPCompleter.merge_completions=<CBool>
81 82 Current: True
82 83 Whether to merge completion results into a single list
83 84 If False, only the completion results from the first non-empty
84 85 completer will be returned.
85 86 IPCompleter.limit_to__all__=<CBool>
86 87 Current: False
87 88 Instruct the completer to use __all__ for the completion
88 89 Specifically, when completing on ``object.<tab>``.
89 90 When True: only those names in obj.__all__ will be included.
90 91 When False [default]: the __all__ attribute is ignored
91 92 IPCompleter.greedy=<CBool>
92 93 Current: False
93 94 Activate greedy completion
94 95 This will enable completion on elements of lists, results of
95 96 function calls, etc., but can be unsafe because the code is
96 97 actually evaluated on TAB.
97 98
98 99 but the real use is in setting values::
99 100
100 101 In [3]: %config IPCompleter.greedy = True
101 102
102 103 and these values are read from the user_ns if they are variables::
103 104
104 105 In [4]: feeling_greedy=False
105 106
106 107 In [5]: %config IPCompleter.greedy = feeling_greedy
107 108
108 109 """
109 110 from traitlets.config.loader import Config
110 111 # some IPython objects are Configurable, but do not yet have
111 112 # any configurable traits. Exclude them from the effects of
112 113 # this magic, as their presence is just noise:
113 114 configurables = [ c for c in self.shell.configurables
114 115 if c.__class__.class_traits(config=True) ]
115 116 classnames = [ c.__class__.__name__ for c in configurables ]
116 117
117 118 line = s.strip()
118 119 if not line:
119 120 # print available configurable names
120 121 print("Available objects for config:")
121 122 for name in classnames:
122 123 print(" ", name)
123 124 return
124 125 elif line in classnames:
125 126 # `%config TerminalInteractiveShell` will print trait info for
126 127 # TerminalInteractiveShell
127 128 c = configurables[classnames.index(line)]
128 129 cls = c.__class__
129 130 help = cls.class_get_help(c)
130 131 # strip leading '--' from cl-args:
131 132 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
132 133 print(help)
133 134 return
134 135 elif reg.match(line):
135 136 cls, attr = line.split('.')
136 137 return getattr(configurables[classnames.index(cls)],attr)
137 138 elif '=' not in line:
138 139 msg = "Invalid config statement: %r, "\
139 140 "should be `Class.trait = value`."
140 141
141 142 ll = line.lower()
142 143 for classname in classnames:
143 144 if ll == classname.lower():
144 145 msg = msg + '\nDid you mean %s (note the case)?' % classname
145 146 break
146 147
147 148 raise UsageError( msg % line)
148 149
149 150 # otherwise, assume we are setting configurables.
150 151 # leave quotes on args when splitting, because we want
151 152 # unquoted args to eval in user_ns
152 153 cfg = Config()
153 154 exec("cfg."+line, locals(), self.shell.user_ns)
154 155
155 156 for configurable in configurables:
156 157 try:
157 158 configurable.update_config(cfg)
158 159 except Exception as e:
159 160 error(e)
@@ -1,1363 +1,1364 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 from __future__ import print_function
8 from __future__ import absolute_import
8 9
9 10 import ast
10 11 import bdb
11 12 import gc
12 13 import itertools
13 14 import os
14 15 import sys
15 16 import time
16 17 import timeit
17 18 from pdb import Restart
18 19
19 20 # cProfile was added in Python2.5
20 21 try:
21 22 import cProfile as profile
22 23 import pstats
23 24 except ImportError:
24 25 # profile isn't bundled by default in Debian for license reasons
25 26 try:
26 27 import profile, pstats
27 28 except ImportError:
28 29 profile = pstats = None
29 30
30 31 from IPython.core import debugger, oinspect
31 32 from IPython.core import magic_arguments
32 33 from IPython.core import page
33 34 from IPython.core.error import UsageError
34 35 from IPython.core.macro import Macro
35 36 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
36 37 line_cell_magic, on_off, needs_local_scope)
37 38 from IPython.testing.skipdoctest import skip_doctest
38 39 from IPython.utils import py3compat
39 40 from IPython.utils.py3compat import builtin_mod, iteritems, PY3
40 41 from IPython.utils.contexts import preserve_keys
41 42 from IPython.utils.capture import capture_output
42 43 from IPython.utils.ipstruct import Struct
43 44 from IPython.utils.module_paths import find_mod
44 45 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
45 46 from IPython.utils.timing import clock, clock2
46 47 from warnings import warn
47 48 from logging import error
48 49
49 50 if PY3:
50 51 from io import StringIO
51 52 else:
52 53 from StringIO import StringIO
53 54
54 55 #-----------------------------------------------------------------------------
55 56 # Magic implementation classes
56 57 #-----------------------------------------------------------------------------
57 58
58 59
59 60 class TimeitResult(object):
60 61 """
61 62 Object returned by the timeit magic with info about the run.
62 63
63 64 Contain the following attributes :
64 65
65 66 loops: (int) number of loop done per measurement
66 67 repeat: (int) number of time the mesurement has been repeated
67 68 best: (float) best execusion time / number
68 69 all_runs: (list of float) execusion time of each run (in s)
69 70 compile_time: (float) time of statement compilation (s)
70 71
71 72 """
72 73
73 74 def __init__(self, loops, repeat, best, worst, all_runs, compile_time, precision):
74 75 self.loops = loops
75 76 self.repeat = repeat
76 77 self.best = best
77 78 self.worst = worst
78 79 self.all_runs = all_runs
79 80 self.compile_time = compile_time
80 81 self._precision = precision
81 82
82 83 def _repr_pretty_(self, p , cycle):
83 84 if self.loops == 1: # No s at "loops" if only one loop
84 85 unic = u"%d loop, best of %d: %s per loop" % (self.loops, self.repeat,
85 86 _format_time(self.best, self._precision))
86 87 else:
87 88 unic = u"%d loops, best of %d: %s per loop" % (self.loops, self.repeat,
88 89 _format_time(self.best, self._precision))
89 90 p.text(u'<TimeitResult : '+unic+u'>')
90 91
91 92
92 93 class TimeitTemplateFiller(ast.NodeTransformer):
93 94 """Fill in the AST template for timing execution.
94 95
95 96 This is quite closely tied to the template definition, which is in
96 97 :meth:`ExecutionMagics.timeit`.
97 98 """
98 99 def __init__(self, ast_setup, ast_stmt):
99 100 self.ast_setup = ast_setup
100 101 self.ast_stmt = ast_stmt
101 102
102 103 def visit_FunctionDef(self, node):
103 104 "Fill in the setup statement"
104 105 self.generic_visit(node)
105 106 if node.name == "inner":
106 107 node.body[:1] = self.ast_setup.body
107 108
108 109 return node
109 110
110 111 def visit_For(self, node):
111 112 "Fill in the statement to be timed"
112 113 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
113 114 node.body = self.ast_stmt.body
114 115 return node
115 116
116 117
117 118 class Timer(timeit.Timer):
118 119 """Timer class that explicitly uses self.inner
119 120
120 121 which is an undocumented implementation detail of CPython,
121 122 not shared by PyPy.
122 123 """
123 124 # Timer.timeit copied from CPython 3.4.2
124 125 def timeit(self, number=timeit.default_number):
125 126 """Time 'number' executions of the main statement.
126 127
127 128 To be precise, this executes the setup statement once, and
128 129 then returns the time it takes to execute the main statement
129 130 a number of times, as a float measured in seconds. The
130 131 argument is the number of times through the loop, defaulting
131 132 to one million. The main statement, the setup statement and
132 133 the timer function to be used are passed to the constructor.
133 134 """
134 135 it = itertools.repeat(None, number)
135 136 gcold = gc.isenabled()
136 137 gc.disable()
137 138 try:
138 139 timing = self.inner(it, self.timer)
139 140 finally:
140 141 if gcold:
141 142 gc.enable()
142 143 return timing
143 144
144 145
145 146 @magics_class
146 147 class ExecutionMagics(Magics):
147 148 """Magics related to code execution, debugging, profiling, etc.
148 149
149 150 """
150 151
151 152 def __init__(self, shell):
152 153 super(ExecutionMagics, self).__init__(shell)
153 154 if profile is None:
154 155 self.prun = self.profile_missing_notice
155 156 # Default execution function used to actually run user code.
156 157 self.default_runner = None
157 158
158 159 def profile_missing_notice(self, *args, **kwargs):
159 160 error("""\
160 161 The profile module could not be found. It has been removed from the standard
161 162 python packages because of its non-free license. To use profiling, install the
162 163 python-profiler package from non-free.""")
163 164
164 165 @skip_doctest
165 166 @line_cell_magic
166 167 def prun(self, parameter_s='', cell=None):
167 168
168 169 """Run a statement through the python code profiler.
169 170
170 171 Usage, in line mode:
171 172 %prun [options] statement
172 173
173 174 Usage, in cell mode:
174 175 %%prun [options] [statement]
175 176 code...
176 177 code...
177 178
178 179 In cell mode, the additional code lines are appended to the (possibly
179 180 empty) statement in the first line. Cell mode allows you to easily
180 181 profile multiline blocks without having to put them in a separate
181 182 function.
182 183
183 184 The given statement (which doesn't require quote marks) is run via the
184 185 python profiler in a manner similar to the profile.run() function.
185 186 Namespaces are internally managed to work correctly; profile.run
186 187 cannot be used in IPython because it makes certain assumptions about
187 188 namespaces which do not hold under IPython.
188 189
189 190 Options:
190 191
191 192 -l <limit>
192 193 you can place restrictions on what or how much of the
193 194 profile gets printed. The limit value can be:
194 195
195 196 * A string: only information for function names containing this string
196 197 is printed.
197 198
198 199 * An integer: only these many lines are printed.
199 200
200 201 * A float (between 0 and 1): this fraction of the report is printed
201 202 (for example, use a limit of 0.4 to see the topmost 40% only).
202 203
203 204 You can combine several limits with repeated use of the option. For
204 205 example, ``-l __init__ -l 5`` will print only the topmost 5 lines of
205 206 information about class constructors.
206 207
207 208 -r
208 209 return the pstats.Stats object generated by the profiling. This
209 210 object has all the information about the profile in it, and you can
210 211 later use it for further analysis or in other functions.
211 212
212 213 -s <key>
213 214 sort profile by given key. You can provide more than one key
214 215 by using the option several times: '-s key1 -s key2 -s key3...'. The
215 216 default sorting key is 'time'.
216 217
217 218 The following is copied verbatim from the profile documentation
218 219 referenced below:
219 220
220 221 When more than one key is provided, additional keys are used as
221 222 secondary criteria when the there is equality in all keys selected
222 223 before them.
223 224
224 225 Abbreviations can be used for any key names, as long as the
225 226 abbreviation is unambiguous. The following are the keys currently
226 227 defined:
227 228
228 229 ============ =====================
229 230 Valid Arg Meaning
230 231 ============ =====================
231 232 "calls" call count
232 233 "cumulative" cumulative time
233 234 "file" file name
234 235 "module" file name
235 236 "pcalls" primitive call count
236 237 "line" line number
237 238 "name" function name
238 239 "nfl" name/file/line
239 240 "stdname" standard name
240 241 "time" internal time
241 242 ============ =====================
242 243
243 244 Note that all sorts on statistics are in descending order (placing
244 245 most time consuming items first), where as name, file, and line number
245 246 searches are in ascending order (i.e., alphabetical). The subtle
246 247 distinction between "nfl" and "stdname" is that the standard name is a
247 248 sort of the name as printed, which means that the embedded line
248 249 numbers get compared in an odd way. For example, lines 3, 20, and 40
249 250 would (if the file names were the same) appear in the string order
250 251 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
251 252 line numbers. In fact, sort_stats("nfl") is the same as
252 253 sort_stats("name", "file", "line").
253 254
254 255 -T <filename>
255 256 save profile results as shown on screen to a text
256 257 file. The profile is still shown on screen.
257 258
258 259 -D <filename>
259 260 save (via dump_stats) profile statistics to given
260 261 filename. This data is in a format understood by the pstats module, and
261 262 is generated by a call to the dump_stats() method of profile
262 263 objects. The profile is still shown on screen.
263 264
264 265 -q
265 266 suppress output to the pager. Best used with -T and/or -D above.
266 267
267 268 If you want to run complete programs under the profiler's control, use
268 269 ``%run -p [prof_opts] filename.py [args to program]`` where prof_opts
269 270 contains profiler specific options as described here.
270 271
271 272 You can read the complete documentation for the profile module with::
272 273
273 274 In [1]: import profile; profile.help()
274 275 """
275 276 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
276 277 list_all=True, posix=False)
277 278 if cell is not None:
278 279 arg_str += '\n' + cell
279 280 arg_str = self.shell.input_splitter.transform_cell(arg_str)
280 281 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
281 282
282 283 def _run_with_profiler(self, code, opts, namespace):
283 284 """
284 285 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
285 286
286 287 Parameters
287 288 ----------
288 289 code : str
289 290 Code to be executed.
290 291 opts : Struct
291 292 Options parsed by `self.parse_options`.
292 293 namespace : dict
293 294 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
294 295
295 296 """
296 297
297 298 # Fill default values for unspecified options:
298 299 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
299 300
300 301 prof = profile.Profile()
301 302 try:
302 303 prof = prof.runctx(code, namespace, namespace)
303 304 sys_exit = ''
304 305 except SystemExit:
305 306 sys_exit = """*** SystemExit exception caught in code being profiled."""
306 307
307 308 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
308 309
309 310 lims = opts.l
310 311 if lims:
311 312 lims = [] # rebuild lims with ints/floats/strings
312 313 for lim in opts.l:
313 314 try:
314 315 lims.append(int(lim))
315 316 except ValueError:
316 317 try:
317 318 lims.append(float(lim))
318 319 except ValueError:
319 320 lims.append(lim)
320 321
321 322 # Trap output.
322 323 stdout_trap = StringIO()
323 324 stats_stream = stats.stream
324 325 try:
325 326 stats.stream = stdout_trap
326 327 stats.print_stats(*lims)
327 328 finally:
328 329 stats.stream = stats_stream
329 330
330 331 output = stdout_trap.getvalue()
331 332 output = output.rstrip()
332 333
333 334 if 'q' not in opts:
334 335 page.page(output)
335 336 print(sys_exit, end=' ')
336 337
337 338 dump_file = opts.D[0]
338 339 text_file = opts.T[0]
339 340 if dump_file:
340 341 dump_file = unquote_filename(dump_file)
341 342 prof.dump_stats(dump_file)
342 343 print('\n*** Profile stats marshalled to file',\
343 344 repr(dump_file)+'.',sys_exit)
344 345 if text_file:
345 346 text_file = unquote_filename(text_file)
346 347 pfile = open(text_file,'w')
347 348 pfile.write(output)
348 349 pfile.close()
349 350 print('\n*** Profile printout saved to text file',\
350 351 repr(text_file)+'.',sys_exit)
351 352
352 353 if 'r' in opts:
353 354 return stats
354 355 else:
355 356 return None
356 357
357 358 @line_magic
358 359 def pdb(self, parameter_s=''):
359 360 """Control the automatic calling of the pdb interactive debugger.
360 361
361 362 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
362 363 argument it works as a toggle.
363 364
364 365 When an exception is triggered, IPython can optionally call the
365 366 interactive pdb debugger after the traceback printout. %pdb toggles
366 367 this feature on and off.
367 368
368 369 The initial state of this feature is set in your configuration
369 370 file (the option is ``InteractiveShell.pdb``).
370 371
371 372 If you want to just activate the debugger AFTER an exception has fired,
372 373 without having to type '%pdb on' and rerunning your code, you can use
373 374 the %debug magic."""
374 375
375 376 par = parameter_s.strip().lower()
376 377
377 378 if par:
378 379 try:
379 380 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
380 381 except KeyError:
381 382 print ('Incorrect argument. Use on/1, off/0, '
382 383 'or nothing for a toggle.')
383 384 return
384 385 else:
385 386 # toggle
386 387 new_pdb = not self.shell.call_pdb
387 388
388 389 # set on the shell
389 390 self.shell.call_pdb = new_pdb
390 391 print('Automatic pdb calling has been turned',on_off(new_pdb))
391 392
392 393 @skip_doctest
393 394 @magic_arguments.magic_arguments()
394 395 @magic_arguments.argument('--breakpoint', '-b', metavar='FILE:LINE',
395 396 help="""
396 397 Set break point at LINE in FILE.
397 398 """
398 399 )
399 400 @magic_arguments.argument('statement', nargs='*',
400 401 help="""
401 402 Code to run in debugger.
402 403 You can omit this in cell magic mode.
403 404 """
404 405 )
405 406 @line_cell_magic
406 407 def debug(self, line='', cell=None):
407 408 """Activate the interactive debugger.
408 409
409 410 This magic command support two ways of activating debugger.
410 411 One is to activate debugger before executing code. This way, you
411 412 can set a break point, to step through the code from the point.
412 413 You can use this mode by giving statements to execute and optionally
413 414 a breakpoint.
414 415
415 416 The other one is to activate debugger in post-mortem mode. You can
416 417 activate this mode simply running %debug without any argument.
417 418 If an exception has just occurred, this lets you inspect its stack
418 419 frames interactively. Note that this will always work only on the last
419 420 traceback that occurred, so you must call this quickly after an
420 421 exception that you wish to inspect has fired, because if another one
421 422 occurs, it clobbers the previous one.
422 423
423 424 If you want IPython to automatically do this on every exception, see
424 425 the %pdb magic for more details.
425 426 """
426 427 args = magic_arguments.parse_argstring(self.debug, line)
427 428
428 429 if not (args.breakpoint or args.statement or cell):
429 430 self._debug_post_mortem()
430 431 else:
431 432 code = "\n".join(args.statement)
432 433 if cell:
433 434 code += "\n" + cell
434 435 self._debug_exec(code, args.breakpoint)
435 436
436 437 def _debug_post_mortem(self):
437 438 self.shell.debugger(force=True)
438 439
439 440 def _debug_exec(self, code, breakpoint):
440 441 if breakpoint:
441 442 (filename, bp_line) = breakpoint.split(':', 1)
442 443 bp_line = int(bp_line)
443 444 else:
444 445 (filename, bp_line) = (None, None)
445 446 self._run_with_debugger(code, self.shell.user_ns, filename, bp_line)
446 447
447 448 @line_magic
448 449 def tb(self, s):
449 450 """Print the last traceback with the currently active exception mode.
450 451
451 452 See %xmode for changing exception reporting modes."""
452 453 self.shell.showtraceback()
453 454
454 455 @skip_doctest
455 456 @line_magic
456 457 def run(self, parameter_s='', runner=None,
457 458 file_finder=get_py_filename):
458 459 """Run the named file inside IPython as a program.
459 460
460 461 Usage::
461 462
462 463 %run [-n -i -e -G]
463 464 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
464 465 ( -m mod | file ) [args]
465 466
466 467 Parameters after the filename are passed as command-line arguments to
467 468 the program (put in sys.argv). Then, control returns to IPython's
468 469 prompt.
469 470
470 471 This is similar to running at a system prompt ``python file args``,
471 472 but with the advantage of giving you IPython's tracebacks, and of
472 473 loading all variables into your interactive namespace for further use
473 474 (unless -p is used, see below).
474 475
475 476 The file is executed in a namespace initially consisting only of
476 477 ``__name__=='__main__'`` and sys.argv constructed as indicated. It thus
477 478 sees its environment as if it were being run as a stand-alone program
478 479 (except for sharing global objects such as previously imported
479 480 modules). But after execution, the IPython interactive namespace gets
480 481 updated with all variables defined in the program (except for __name__
481 482 and sys.argv). This allows for very convenient loading of code for
482 483 interactive work, while giving each program a 'clean sheet' to run in.
483 484
484 485 Arguments are expanded using shell-like glob match. Patterns
485 486 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
486 487 tilde '~' will be expanded into user's home directory. Unlike
487 488 real shells, quotation does not suppress expansions. Use
488 489 *two* back slashes (e.g. ``\\\\*``) to suppress expansions.
489 490 To completely disable these expansions, you can use -G flag.
490 491
491 492 Options:
492 493
493 494 -n
494 495 __name__ is NOT set to '__main__', but to the running file's name
495 496 without extension (as python does under import). This allows running
496 497 scripts and reloading the definitions in them without calling code
497 498 protected by an ``if __name__ == "__main__"`` clause.
498 499
499 500 -i
500 501 run the file in IPython's namespace instead of an empty one. This
501 502 is useful if you are experimenting with code written in a text editor
502 503 which depends on variables defined interactively.
503 504
504 505 -e
505 506 ignore sys.exit() calls or SystemExit exceptions in the script
506 507 being run. This is particularly useful if IPython is being used to
507 508 run unittests, which always exit with a sys.exit() call. In such
508 509 cases you are interested in the output of the test results, not in
509 510 seeing a traceback of the unittest module.
510 511
511 512 -t
512 513 print timing information at the end of the run. IPython will give
513 514 you an estimated CPU time consumption for your script, which under
514 515 Unix uses the resource module to avoid the wraparound problems of
515 516 time.clock(). Under Unix, an estimate of time spent on system tasks
516 517 is also given (for Windows platforms this is reported as 0.0).
517 518
518 519 If -t is given, an additional ``-N<N>`` option can be given, where <N>
519 520 must be an integer indicating how many times you want the script to
520 521 run. The final timing report will include total and per run results.
521 522
522 523 For example (testing the script uniq_stable.py)::
523 524
524 525 In [1]: run -t uniq_stable
525 526
526 527 IPython CPU timings (estimated):
527 528 User : 0.19597 s.
528 529 System: 0.0 s.
529 530
530 531 In [2]: run -t -N5 uniq_stable
531 532
532 533 IPython CPU timings (estimated):
533 534 Total runs performed: 5
534 535 Times : Total Per run
535 536 User : 0.910862 s, 0.1821724 s.
536 537 System: 0.0 s, 0.0 s.
537 538
538 539 -d
539 540 run your program under the control of pdb, the Python debugger.
540 541 This allows you to execute your program step by step, watch variables,
541 542 etc. Internally, what IPython does is similar to calling::
542 543
543 544 pdb.run('execfile("YOURFILENAME")')
544 545
545 546 with a breakpoint set on line 1 of your file. You can change the line
546 547 number for this automatic breakpoint to be <N> by using the -bN option
547 548 (where N must be an integer). For example::
548 549
549 550 %run -d -b40 myscript
550 551
551 552 will set the first breakpoint at line 40 in myscript.py. Note that
552 553 the first breakpoint must be set on a line which actually does
553 554 something (not a comment or docstring) for it to stop execution.
554 555
555 556 Or you can specify a breakpoint in a different file::
556 557
557 558 %run -d -b myotherfile.py:20 myscript
558 559
559 560 When the pdb debugger starts, you will see a (Pdb) prompt. You must
560 561 first enter 'c' (without quotes) to start execution up to the first
561 562 breakpoint.
562 563
563 564 Entering 'help' gives information about the use of the debugger. You
564 565 can easily see pdb's full documentation with "import pdb;pdb.help()"
565 566 at a prompt.
566 567
567 568 -p
568 569 run program under the control of the Python profiler module (which
569 570 prints a detailed report of execution times, function calls, etc).
570 571
571 572 You can pass other options after -p which affect the behavior of the
572 573 profiler itself. See the docs for %prun for details.
573 574
574 575 In this mode, the program's variables do NOT propagate back to the
575 576 IPython interactive namespace (because they remain in the namespace
576 577 where the profiler executes them).
577 578
578 579 Internally this triggers a call to %prun, see its documentation for
579 580 details on the options available specifically for profiling.
580 581
581 582 There is one special usage for which the text above doesn't apply:
582 583 if the filename ends with .ipy[nb], the file is run as ipython script,
583 584 just as if the commands were written on IPython prompt.
584 585
585 586 -m
586 587 specify module name to load instead of script path. Similar to
587 588 the -m option for the python interpreter. Use this option last if you
588 589 want to combine with other %run options. Unlike the python interpreter
589 590 only source modules are allowed no .pyc or .pyo files.
590 591 For example::
591 592
592 593 %run -m example
593 594
594 595 will run the example module.
595 596
596 597 -G
597 598 disable shell-like glob expansion of arguments.
598 599
599 600 """
600 601
601 602 # get arguments and set sys.argv for program to be run.
602 603 opts, arg_lst = self.parse_options(parameter_s,
603 604 'nidtN:b:pD:l:rs:T:em:G',
604 605 mode='list', list_all=1)
605 606 if "m" in opts:
606 607 modulename = opts["m"][0]
607 608 modpath = find_mod(modulename)
608 609 if modpath is None:
609 610 warn('%r is not a valid modulename on sys.path'%modulename)
610 611 return
611 612 arg_lst = [modpath] + arg_lst
612 613 try:
613 614 filename = file_finder(arg_lst[0])
614 615 except IndexError:
615 616 warn('you must provide at least a filename.')
616 617 print('\n%run:\n', oinspect.getdoc(self.run))
617 618 return
618 619 except IOError as e:
619 620 try:
620 621 msg = str(e)
621 622 except UnicodeError:
622 623 msg = e.message
623 624 error(msg)
624 625 return
625 626
626 627 if filename.lower().endswith(('.ipy', '.ipynb')):
627 628 with preserve_keys(self.shell.user_ns, '__file__'):
628 629 self.shell.user_ns['__file__'] = filename
629 630 self.shell.safe_execfile_ipy(filename)
630 631 return
631 632
632 633 # Control the response to exit() calls made by the script being run
633 634 exit_ignore = 'e' in opts
634 635
635 636 # Make sure that the running script gets a proper sys.argv as if it
636 637 # were run from a system shell.
637 638 save_argv = sys.argv # save it for later restoring
638 639
639 640 if 'G' in opts:
640 641 args = arg_lst[1:]
641 642 else:
642 643 # tilde and glob expansion
643 644 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
644 645
645 646 sys.argv = [filename] + args # put in the proper filename
646 647 # protect sys.argv from potential unicode strings on Python 2:
647 648 if not py3compat.PY3:
648 649 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
649 650
650 651 if 'i' in opts:
651 652 # Run in user's interactive namespace
652 653 prog_ns = self.shell.user_ns
653 654 __name__save = self.shell.user_ns['__name__']
654 655 prog_ns['__name__'] = '__main__'
655 656 main_mod = self.shell.user_module
656 657
657 658 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
658 659 # set the __file__ global in the script's namespace
659 660 # TK: Is this necessary in interactive mode?
660 661 prog_ns['__file__'] = filename
661 662 else:
662 663 # Run in a fresh, empty namespace
663 664 if 'n' in opts:
664 665 name = os.path.splitext(os.path.basename(filename))[0]
665 666 else:
666 667 name = '__main__'
667 668
668 669 # The shell MUST hold a reference to prog_ns so after %run
669 670 # exits, the python deletion mechanism doesn't zero it out
670 671 # (leaving dangling references). See interactiveshell for details
671 672 main_mod = self.shell.new_main_mod(filename, name)
672 673 prog_ns = main_mod.__dict__
673 674
674 675 # pickle fix. See interactiveshell for an explanation. But we need to
675 676 # make sure that, if we overwrite __main__, we replace it at the end
676 677 main_mod_name = prog_ns['__name__']
677 678
678 679 if main_mod_name == '__main__':
679 680 restore_main = sys.modules['__main__']
680 681 else:
681 682 restore_main = False
682 683
683 684 # This needs to be undone at the end to prevent holding references to
684 685 # every single object ever created.
685 686 sys.modules[main_mod_name] = main_mod
686 687
687 688 if 'p' in opts or 'd' in opts:
688 689 if 'm' in opts:
689 690 code = 'run_module(modulename, prog_ns)'
690 691 code_ns = {
691 692 'run_module': self.shell.safe_run_module,
692 693 'prog_ns': prog_ns,
693 694 'modulename': modulename,
694 695 }
695 696 else:
696 697 if 'd' in opts:
697 698 # allow exceptions to raise in debug mode
698 699 code = 'execfile(filename, prog_ns, raise_exceptions=True)'
699 700 else:
700 701 code = 'execfile(filename, prog_ns)'
701 702 code_ns = {
702 703 'execfile': self.shell.safe_execfile,
703 704 'prog_ns': prog_ns,
704 705 'filename': get_py_filename(filename),
705 706 }
706 707
707 708 try:
708 709 stats = None
709 710 with self.shell.readline_no_record:
710 711 if 'p' in opts:
711 712 stats = self._run_with_profiler(code, opts, code_ns)
712 713 else:
713 714 if 'd' in opts:
714 715 bp_file, bp_line = parse_breakpoint(
715 716 opts.get('b', ['1'])[0], filename)
716 717 self._run_with_debugger(
717 718 code, code_ns, filename, bp_line, bp_file)
718 719 else:
719 720 if 'm' in opts:
720 721 def run():
721 722 self.shell.safe_run_module(modulename, prog_ns)
722 723 else:
723 724 if runner is None:
724 725 runner = self.default_runner
725 726 if runner is None:
726 727 runner = self.shell.safe_execfile
727 728
728 729 def run():
729 730 runner(filename, prog_ns, prog_ns,
730 731 exit_ignore=exit_ignore)
731 732
732 733 if 't' in opts:
733 734 # timed execution
734 735 try:
735 736 nruns = int(opts['N'][0])
736 737 if nruns < 1:
737 738 error('Number of runs must be >=1')
738 739 return
739 740 except (KeyError):
740 741 nruns = 1
741 742 self._run_with_timing(run, nruns)
742 743 else:
743 744 # regular execution
744 745 run()
745 746
746 747 if 'i' in opts:
747 748 self.shell.user_ns['__name__'] = __name__save
748 749 else:
749 750 # update IPython interactive namespace
750 751
751 752 # Some forms of read errors on the file may mean the
752 753 # __name__ key was never set; using pop we don't have to
753 754 # worry about a possible KeyError.
754 755 prog_ns.pop('__name__', None)
755 756
756 757 with preserve_keys(self.shell.user_ns, '__file__'):
757 758 self.shell.user_ns.update(prog_ns)
758 759 finally:
759 760 # It's a bit of a mystery why, but __builtins__ can change from
760 761 # being a module to becoming a dict missing some key data after
761 762 # %run. As best I can see, this is NOT something IPython is doing
762 763 # at all, and similar problems have been reported before:
763 764 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
764 765 # Since this seems to be done by the interpreter itself, the best
765 766 # we can do is to at least restore __builtins__ for the user on
766 767 # exit.
767 768 self.shell.user_ns['__builtins__'] = builtin_mod
768 769
769 770 # Ensure key global structures are restored
770 771 sys.argv = save_argv
771 772 if restore_main:
772 773 sys.modules['__main__'] = restore_main
773 774 else:
774 775 # Remove from sys.modules the reference to main_mod we'd
775 776 # added. Otherwise it will trap references to objects
776 777 # contained therein.
777 778 del sys.modules[main_mod_name]
778 779
779 780 return stats
780 781
781 782 def _run_with_debugger(self, code, code_ns, filename=None,
782 783 bp_line=None, bp_file=None):
783 784 """
784 785 Run `code` in debugger with a break point.
785 786
786 787 Parameters
787 788 ----------
788 789 code : str
789 790 Code to execute.
790 791 code_ns : dict
791 792 A namespace in which `code` is executed.
792 793 filename : str
793 794 `code` is ran as if it is in `filename`.
794 795 bp_line : int, optional
795 796 Line number of the break point.
796 797 bp_file : str, optional
797 798 Path to the file in which break point is specified.
798 799 `filename` is used if not given.
799 800
800 801 Raises
801 802 ------
802 803 UsageError
803 804 If the break point given by `bp_line` is not valid.
804 805
805 806 """
806 807 deb = debugger.Pdb(self.shell.colors)
807 808 # reset Breakpoint state, which is moronically kept
808 809 # in a class
809 810 bdb.Breakpoint.next = 1
810 811 bdb.Breakpoint.bplist = {}
811 812 bdb.Breakpoint.bpbynumber = [None]
812 813 if bp_line is not None:
813 814 # Set an initial breakpoint to stop execution
814 815 maxtries = 10
815 816 bp_file = bp_file or filename
816 817 checkline = deb.checkline(bp_file, bp_line)
817 818 if not checkline:
818 819 for bp in range(bp_line + 1, bp_line + maxtries + 1):
819 820 if deb.checkline(bp_file, bp):
820 821 break
821 822 else:
822 823 msg = ("\nI failed to find a valid line to set "
823 824 "a breakpoint\n"
824 825 "after trying up to line: %s.\n"
825 826 "Please set a valid breakpoint manually "
826 827 "with the -b option." % bp)
827 828 raise UsageError(msg)
828 829 # if we find a good linenumber, set the breakpoint
829 830 deb.do_break('%s:%s' % (bp_file, bp_line))
830 831
831 832 if filename:
832 833 # Mimic Pdb._runscript(...)
833 834 deb._wait_for_mainpyfile = True
834 835 deb.mainpyfile = deb.canonic(filename)
835 836
836 837 # Start file run
837 838 print("NOTE: Enter 'c' at the %s prompt to continue execution." % deb.prompt)
838 839 try:
839 840 if filename:
840 841 # save filename so it can be used by methods on the deb object
841 842 deb._exec_filename = filename
842 843 while True:
843 844 try:
844 845 deb.run(code, code_ns)
845 846 except Restart:
846 847 print("Restarting")
847 848 if filename:
848 849 deb._wait_for_mainpyfile = True
849 850 deb.mainpyfile = deb.canonic(filename)
850 851 continue
851 852 else:
852 853 break
853 854
854 855
855 856 except:
856 857 etype, value, tb = sys.exc_info()
857 858 # Skip three frames in the traceback: the %run one,
858 859 # one inside bdb.py, and the command-line typed by the
859 860 # user (run by exec in pdb itself).
860 861 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
861 862
862 863 @staticmethod
863 864 def _run_with_timing(run, nruns):
864 865 """
865 866 Run function `run` and print timing information.
866 867
867 868 Parameters
868 869 ----------
869 870 run : callable
870 871 Any callable object which takes no argument.
871 872 nruns : int
872 873 Number of times to execute `run`.
873 874
874 875 """
875 876 twall0 = time.time()
876 877 if nruns == 1:
877 878 t0 = clock2()
878 879 run()
879 880 t1 = clock2()
880 881 t_usr = t1[0] - t0[0]
881 882 t_sys = t1[1] - t0[1]
882 883 print("\nIPython CPU timings (estimated):")
883 884 print(" User : %10.2f s." % t_usr)
884 885 print(" System : %10.2f s." % t_sys)
885 886 else:
886 887 runs = range(nruns)
887 888 t0 = clock2()
888 889 for nr in runs:
889 890 run()
890 891 t1 = clock2()
891 892 t_usr = t1[0] - t0[0]
892 893 t_sys = t1[1] - t0[1]
893 894 print("\nIPython CPU timings (estimated):")
894 895 print("Total runs performed:", nruns)
895 896 print(" Times : %10s %10s" % ('Total', 'Per run'))
896 897 print(" User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns))
897 898 print(" System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns))
898 899 twall1 = time.time()
899 900 print("Wall time: %10.2f s." % (twall1 - twall0))
900 901
901 902 @skip_doctest
902 903 @line_cell_magic
903 904 def timeit(self, line='', cell=None):
904 905 """Time execution of a Python statement or expression
905 906
906 907 Usage, in line mode:
907 908 %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
908 909 or in cell mode:
909 910 %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
910 911 code
911 912 code...
912 913
913 914 Time execution of a Python statement or expression using the timeit
914 915 module. This function can be used both as a line and cell magic:
915 916
916 917 - In line mode you can time a single-line statement (though multiple
917 918 ones can be chained with using semicolons).
918 919
919 920 - In cell mode, the statement in the first line is used as setup code
920 921 (executed but not timed) and the body of the cell is timed. The cell
921 922 body has access to any variables created in the setup code.
922 923
923 924 Options:
924 925 -n<N>: execute the given statement <N> times in a loop. If this value
925 926 is not given, a fitting value is chosen.
926 927
927 928 -r<R>: repeat the loop iteration <R> times and take the best result.
928 929 Default: 3
929 930
930 931 -t: use time.time to measure the time, which is the default on Unix.
931 932 This function measures wall time.
932 933
933 934 -c: use time.clock to measure the time, which is the default on
934 935 Windows and measures wall time. On Unix, resource.getrusage is used
935 936 instead and returns the CPU user time.
936 937
937 938 -p<P>: use a precision of <P> digits to display the timing result.
938 939 Default: 3
939 940
940 941 -q: Quiet, do not print result.
941 942
942 943 -o: return a TimeitResult that can be stored in a variable to inspect
943 944 the result in more details.
944 945
945 946
946 947 Examples
947 948 --------
948 949 ::
949 950
950 951 In [1]: %timeit pass
951 952 10000000 loops, best of 3: 53.3 ns per loop
952 953
953 954 In [2]: u = None
954 955
955 956 In [3]: %timeit u is None
956 957 10000000 loops, best of 3: 184 ns per loop
957 958
958 959 In [4]: %timeit -r 4 u == None
959 960 1000000 loops, best of 4: 242 ns per loop
960 961
961 962 In [5]: import time
962 963
963 964 In [6]: %timeit -n1 time.sleep(2)
964 965 1 loop, best of 3: 2 s per loop
965 966
966 967
967 968 The times reported by %timeit will be slightly higher than those
968 969 reported by the timeit.py script when variables are accessed. This is
969 970 due to the fact that %timeit executes the statement in the namespace
970 971 of the shell, compared with timeit.py, which uses a single setup
971 972 statement to import function or create variables. Generally, the bias
972 973 does not matter as long as results from timeit.py are not mixed with
973 974 those from %timeit."""
974 975
975 976 opts, stmt = self.parse_options(line,'n:r:tcp:qo',
976 977 posix=False, strict=False)
977 978 if stmt == "" and cell is None:
978 979 return
979 980
980 981 timefunc = timeit.default_timer
981 982 number = int(getattr(opts, "n", 0))
982 983 repeat = int(getattr(opts, "r", timeit.default_repeat))
983 984 precision = int(getattr(opts, "p", 3))
984 985 quiet = 'q' in opts
985 986 return_result = 'o' in opts
986 987 if hasattr(opts, "t"):
987 988 timefunc = time.time
988 989 if hasattr(opts, "c"):
989 990 timefunc = clock
990 991
991 992 timer = Timer(timer=timefunc)
992 993 # this code has tight coupling to the inner workings of timeit.Timer,
993 994 # but is there a better way to achieve that the code stmt has access
994 995 # to the shell namespace?
995 996 transform = self.shell.input_splitter.transform_cell
996 997
997 998 if cell is None:
998 999 # called as line magic
999 1000 ast_setup = self.shell.compile.ast_parse("pass")
1000 1001 ast_stmt = self.shell.compile.ast_parse(transform(stmt))
1001 1002 else:
1002 1003 ast_setup = self.shell.compile.ast_parse(transform(stmt))
1003 1004 ast_stmt = self.shell.compile.ast_parse(transform(cell))
1004 1005
1005 1006 ast_setup = self.shell.transform_ast(ast_setup)
1006 1007 ast_stmt = self.shell.transform_ast(ast_stmt)
1007 1008
1008 1009 # This codestring is taken from timeit.template - we fill it in as an
1009 1010 # AST, so that we can apply our AST transformations to the user code
1010 1011 # without affecting the timing code.
1011 1012 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
1012 1013 ' setup\n'
1013 1014 ' _t0 = _timer()\n'
1014 1015 ' for _i in _it:\n'
1015 1016 ' stmt\n'
1016 1017 ' _t1 = _timer()\n'
1017 1018 ' return _t1 - _t0\n')
1018 1019
1019 1020 timeit_ast = TimeitTemplateFiller(ast_setup, ast_stmt).visit(timeit_ast_template)
1020 1021 timeit_ast = ast.fix_missing_locations(timeit_ast)
1021 1022
1022 1023 # Track compilation time so it can be reported if too long
1023 1024 # Minimum time above which compilation time will be reported
1024 1025 tc_min = 0.1
1025 1026
1026 1027 t0 = clock()
1027 1028 code = self.shell.compile(timeit_ast, "<magic-timeit>", "exec")
1028 1029 tc = clock()-t0
1029 1030
1030 1031 ns = {}
1031 1032 exec(code, self.shell.user_ns, ns)
1032 1033 timer.inner = ns["inner"]
1033 1034
1034 1035 # This is used to check if there is a huge difference between the
1035 1036 # best and worst timings.
1036 1037 # Issue: https://github.com/ipython/ipython/issues/6471
1037 1038 worst_tuning = 0
1038 1039 if number == 0:
1039 1040 # determine number so that 0.2 <= total time < 2.0
1040 1041 number = 1
1041 1042 for _ in range(1, 10):
1042 1043 time_number = timer.timeit(number)
1043 1044 worst_tuning = max(worst_tuning, time_number / number)
1044 1045 if time_number >= 0.2:
1045 1046 break
1046 1047 number *= 10
1047 1048 all_runs = timer.repeat(repeat, number)
1048 1049 best = min(all_runs) / number
1049 1050
1050 1051 worst = max(all_runs) / number
1051 1052 if worst_tuning:
1052 1053 worst = max(worst, worst_tuning)
1053 1054
1054 1055 if not quiet :
1055 1056 # Check best timing is greater than zero to avoid a
1056 1057 # ZeroDivisionError.
1057 1058 # In cases where the slowest timing is lesser than a micosecond
1058 1059 # we assume that it does not really matter if the fastest
1059 1060 # timing is 4 times faster than the slowest timing or not.
1060 1061 if worst > 4 * best and best > 0 and worst > 1e-6:
1061 1062 print("The slowest run took %0.2f times longer than the "
1062 1063 "fastest. This could mean that an intermediate result "
1063 1064 "is being cached." % (worst / best))
1064 1065 if number == 1: # No s at "loops" if only one loop
1065 1066 print(u"%d loop, best of %d: %s per loop" % (number, repeat,
1066 1067 _format_time(best, precision)))
1067 1068 else:
1068 1069 print(u"%d loops, best of %d: %s per loop" % (number, repeat,
1069 1070 _format_time(best, precision)))
1070 1071 if tc > tc_min:
1071 1072 print("Compiler time: %.2f s" % tc)
1072 1073 if return_result:
1073 1074 return TimeitResult(number, repeat, best, worst, all_runs, tc, precision)
1074 1075
1075 1076 @skip_doctest
1076 1077 @needs_local_scope
1077 1078 @line_cell_magic
1078 1079 def time(self,line='', cell=None, local_ns=None):
1079 1080 """Time execution of a Python statement or expression.
1080 1081
1081 1082 The CPU and wall clock times are printed, and the value of the
1082 1083 expression (if any) is returned. Note that under Win32, system time
1083 1084 is always reported as 0, since it can not be measured.
1084 1085
1085 1086 This function can be used both as a line and cell magic:
1086 1087
1087 1088 - In line mode you can time a single-line statement (though multiple
1088 1089 ones can be chained with using semicolons).
1089 1090
1090 1091 - In cell mode, you can time the cell body (a directly
1091 1092 following statement raises an error).
1092 1093
1093 1094 This function provides very basic timing functionality. Use the timeit
1094 1095 magic for more control over the measurement.
1095 1096
1096 1097 Examples
1097 1098 --------
1098 1099 ::
1099 1100
1100 1101 In [1]: %time 2**128
1101 1102 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1102 1103 Wall time: 0.00
1103 1104 Out[1]: 340282366920938463463374607431768211456L
1104 1105
1105 1106 In [2]: n = 1000000
1106 1107
1107 1108 In [3]: %time sum(range(n))
1108 1109 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
1109 1110 Wall time: 1.37
1110 1111 Out[3]: 499999500000L
1111 1112
1112 1113 In [4]: %time print 'hello world'
1113 1114 hello world
1114 1115 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1115 1116 Wall time: 0.00
1116 1117
1117 1118 Note that the time needed by Python to compile the given expression
1118 1119 will be reported if it is more than 0.1s. In this example, the
1119 1120 actual exponentiation is done by Python at compilation time, so while
1120 1121 the expression can take a noticeable amount of time to compute, that
1121 1122 time is purely due to the compilation:
1122 1123
1123 1124 In [5]: %time 3**9999;
1124 1125 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1125 1126 Wall time: 0.00 s
1126 1127
1127 1128 In [6]: %time 3**999999;
1128 1129 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
1129 1130 Wall time: 0.00 s
1130 1131 Compiler : 0.78 s
1131 1132 """
1132 1133
1133 1134 # fail immediately if the given expression can't be compiled
1134 1135
1135 1136 if line and cell:
1136 1137 raise UsageError("Can't use statement directly after '%%time'!")
1137 1138
1138 1139 if cell:
1139 1140 expr = self.shell.input_transformer_manager.transform_cell(cell)
1140 1141 else:
1141 1142 expr = self.shell.input_transformer_manager.transform_cell(line)
1142 1143
1143 1144 # Minimum time above which parse time will be reported
1144 1145 tp_min = 0.1
1145 1146
1146 1147 t0 = clock()
1147 1148 expr_ast = self.shell.compile.ast_parse(expr)
1148 1149 tp = clock()-t0
1149 1150
1150 1151 # Apply AST transformations
1151 1152 expr_ast = self.shell.transform_ast(expr_ast)
1152 1153
1153 1154 # Minimum time above which compilation time will be reported
1154 1155 tc_min = 0.1
1155 1156
1156 1157 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
1157 1158 mode = 'eval'
1158 1159 source = '<timed eval>'
1159 1160 expr_ast = ast.Expression(expr_ast.body[0].value)
1160 1161 else:
1161 1162 mode = 'exec'
1162 1163 source = '<timed exec>'
1163 1164 t0 = clock()
1164 1165 code = self.shell.compile(expr_ast, source, mode)
1165 1166 tc = clock()-t0
1166 1167
1167 1168 # skew measurement as little as possible
1168 1169 glob = self.shell.user_ns
1169 1170 wtime = time.time
1170 1171 # time execution
1171 1172 wall_st = wtime()
1172 1173 if mode=='eval':
1173 1174 st = clock2()
1174 1175 out = eval(code, glob, local_ns)
1175 1176 end = clock2()
1176 1177 else:
1177 1178 st = clock2()
1178 1179 exec(code, glob, local_ns)
1179 1180 end = clock2()
1180 1181 out = None
1181 1182 wall_end = wtime()
1182 1183 # Compute actual times and report
1183 1184 wall_time = wall_end-wall_st
1184 1185 cpu_user = end[0]-st[0]
1185 1186 cpu_sys = end[1]-st[1]
1186 1187 cpu_tot = cpu_user+cpu_sys
1187 1188 # On windows cpu_sys is always zero, so no new information to the next print
1188 1189 if sys.platform != 'win32':
1189 1190 print("CPU times: user %s, sys: %s, total: %s" % \
1190 1191 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot)))
1191 1192 print("Wall time: %s" % _format_time(wall_time))
1192 1193 if tc > tc_min:
1193 1194 print("Compiler : %s" % _format_time(tc))
1194 1195 if tp > tp_min:
1195 1196 print("Parser : %s" % _format_time(tp))
1196 1197 return out
1197 1198
1198 1199 @skip_doctest
1199 1200 @line_magic
1200 1201 def macro(self, parameter_s=''):
1201 1202 """Define a macro for future re-execution. It accepts ranges of history,
1202 1203 filenames or string objects.
1203 1204
1204 1205 Usage:\\
1205 1206 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1206 1207
1207 1208 Options:
1208 1209
1209 1210 -r: use 'raw' input. By default, the 'processed' history is used,
1210 1211 so that magics are loaded in their transformed version to valid
1211 1212 Python. If this option is given, the raw input as typed at the
1212 1213 command line is used instead.
1213 1214
1214 1215 -q: quiet macro definition. By default, a tag line is printed
1215 1216 to indicate the macro has been created, and then the contents of
1216 1217 the macro are printed. If this option is given, then no printout
1217 1218 is produced once the macro is created.
1218 1219
1219 1220 This will define a global variable called `name` which is a string
1220 1221 made of joining the slices and lines you specify (n1,n2,... numbers
1221 1222 above) from your input history into a single string. This variable
1222 1223 acts like an automatic function which re-executes those lines as if
1223 1224 you had typed them. You just type 'name' at the prompt and the code
1224 1225 executes.
1225 1226
1226 1227 The syntax for indicating input ranges is described in %history.
1227 1228
1228 1229 Note: as a 'hidden' feature, you can also use traditional python slice
1229 1230 notation, where N:M means numbers N through M-1.
1230 1231
1231 1232 For example, if your history contains (print using %hist -n )::
1232 1233
1233 1234 44: x=1
1234 1235 45: y=3
1235 1236 46: z=x+y
1236 1237 47: print x
1237 1238 48: a=5
1238 1239 49: print 'x',x,'y',y
1239 1240
1240 1241 you can create a macro with lines 44 through 47 (included) and line 49
1241 1242 called my_macro with::
1242 1243
1243 1244 In [55]: %macro my_macro 44-47 49
1244 1245
1245 1246 Now, typing `my_macro` (without quotes) will re-execute all this code
1246 1247 in one pass.
1247 1248
1248 1249 You don't need to give the line-numbers in order, and any given line
1249 1250 number can appear multiple times. You can assemble macros with any
1250 1251 lines from your input history in any order.
1251 1252
1252 1253 The macro is a simple object which holds its value in an attribute,
1253 1254 but IPython's display system checks for macros and executes them as
1254 1255 code instead of printing them when you type their name.
1255 1256
1256 1257 You can view a macro's contents by explicitly printing it with::
1257 1258
1258 1259 print macro_name
1259 1260
1260 1261 """
1261 1262 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1262 1263 if not args: # List existing macros
1263 1264 return sorted(k for k,v in iteritems(self.shell.user_ns) if\
1264 1265 isinstance(v, Macro))
1265 1266 if len(args) == 1:
1266 1267 raise UsageError(
1267 1268 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1268 1269 name, codefrom = args[0], " ".join(args[1:])
1269 1270
1270 1271 #print 'rng',ranges # dbg
1271 1272 try:
1272 1273 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1273 1274 except (ValueError, TypeError) as e:
1274 1275 print(e.args[0])
1275 1276 return
1276 1277 macro = Macro(lines)
1277 1278 self.shell.define_macro(name, macro)
1278 1279 if not ( 'q' in opts) :
1279 1280 print('Macro `%s` created. To execute, type its name (without quotes).' % name)
1280 1281 print('=== Macro contents: ===')
1281 1282 print(macro, end=' ')
1282 1283
1283 1284 @magic_arguments.magic_arguments()
1284 1285 @magic_arguments.argument('output', type=str, default='', nargs='?',
1285 1286 help="""The name of the variable in which to store output.
1286 1287 This is a utils.io.CapturedIO object with stdout/err attributes
1287 1288 for the text of the captured output.
1288 1289
1289 1290 CapturedOutput also has a show() method for displaying the output,
1290 1291 and __call__ as well, so you can use that to quickly display the
1291 1292 output.
1292 1293
1293 1294 If unspecified, captured output is discarded.
1294 1295 """
1295 1296 )
1296 1297 @magic_arguments.argument('--no-stderr', action="store_true",
1297 1298 help="""Don't capture stderr."""
1298 1299 )
1299 1300 @magic_arguments.argument('--no-stdout', action="store_true",
1300 1301 help="""Don't capture stdout."""
1301 1302 )
1302 1303 @magic_arguments.argument('--no-display', action="store_true",
1303 1304 help="""Don't capture IPython's rich display."""
1304 1305 )
1305 1306 @cell_magic
1306 1307 def capture(self, line, cell):
1307 1308 """run the cell, capturing stdout, stderr, and IPython's rich display() calls."""
1308 1309 args = magic_arguments.parse_argstring(self.capture, line)
1309 1310 out = not args.no_stdout
1310 1311 err = not args.no_stderr
1311 1312 disp = not args.no_display
1312 1313 with capture_output(out, err, disp) as io:
1313 1314 self.shell.run_cell(cell)
1314 1315 if args.output:
1315 1316 self.shell.user_ns[args.output] = io
1316 1317
1317 1318 def parse_breakpoint(text, current_file):
1318 1319 '''Returns (file, line) for file:line and (current_file, line) for line'''
1319 1320 colon = text.find(':')
1320 1321 if colon == -1:
1321 1322 return current_file, int(text)
1322 1323 else:
1323 1324 return text[:colon], int(text[colon+1:])
1324 1325
1325 1326 def _format_time(timespan, precision=3):
1326 1327 """Formats the timespan in a human readable form"""
1327 1328 import math
1328 1329
1329 1330 if timespan >= 60.0:
1330 1331 # we have more than a minute, format that in a human readable form
1331 1332 # Idea from http://snipplr.com/view/5713/
1332 1333 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1333 1334 time = []
1334 1335 leftover = timespan
1335 1336 for suffix, length in parts:
1336 1337 value = int(leftover / length)
1337 1338 if value > 0:
1338 1339 leftover = leftover % length
1339 1340 time.append(u'%s%s' % (str(value), suffix))
1340 1341 if leftover < 1:
1341 1342 break
1342 1343 return " ".join(time)
1343 1344
1344 1345
1345 1346 # Unfortunately the unicode 'micro' symbol can cause problems in
1346 1347 # certain terminals.
1347 1348 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1348 1349 # Try to prevent crashes by being more secure than it needs to
1349 1350 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1350 1351 units = [u"s", u"ms",u'us',"ns"] # the save value
1351 1352 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1352 1353 try:
1353 1354 u'\xb5'.encode(sys.stdout.encoding)
1354 1355 units = [u"s", u"ms",u'\xb5s',"ns"]
1355 1356 except:
1356 1357 pass
1357 1358 scaling = [1, 1e3, 1e6, 1e9]
1358 1359
1359 1360 if timespan > 0.0:
1360 1361 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1361 1362 else:
1362 1363 order = 3
1363 1364 return u"%.*g %s" % (precision, timespan * scaling[order], units[order])
General Comments 0
You need to be logged in to leave comments. Login now