##// END OF EJS Templates
Fix a few more test failures from magic API changes.
Fernando Perez -
Show More
@@ -1,3730 +1,3730 b''
1 1 """Magic functions for InteractiveShell.
2 2 """
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and
6 6 # Copyright (C) 2001 Fernando Perez <fperez@colorado.edu>
7 7 # Copyright (C) 2008 The IPython Development Team
8 8
9 9 # Distributed under the terms of the BSD License. The full license is in
10 10 # the file COPYING, distributed as part of this software.
11 11 #-----------------------------------------------------------------------------
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15
16 16 import __builtin__ as builtin_mod
17 17 import bdb
18 18 import gc
19 19 import inspect
20 20 import io
21 21 import json
22 22 import os
23 23 import re
24 24 import sys
25 25 import time
26 26 from StringIO import StringIO
27 27 from pprint import pformat
28 28 from urllib2 import urlopen
29 29
30 30 # cProfile was added in Python2.5
31 31 try:
32 32 import cProfile as profile
33 33 import pstats
34 34 except ImportError:
35 35 # profile isn't bundled by default in Debian for license reasons
36 36 try:
37 37 import profile, pstats
38 38 except ImportError:
39 39 profile = pstats = None
40 40
41 41 from IPython.config.application import Application
42 42 from IPython.core import debugger, oinspect
43 43 from IPython.core import magic_arguments, page
44 44 from IPython.core.error import UsageError, StdinNotImplementedError, TryNext
45 45 from IPython.core.macro import Macro
46 46 from IPython.core.magic import (Bunch, Magics, compress_dhist,
47 47 on_off, needs_local_scope,
48 48 register_magics, line_magic, cell_magic)
49 49 from IPython.core.prefilter import ESC_MAGIC
50 50 from IPython.testing.skipdoctest import skip_doctest
51 51 from IPython.utils import openpy
52 52 from IPython.utils import py3compat
53 53 from IPython.utils.encoding import DEFAULT_ENCODING
54 54 from IPython.utils.io import file_read, nlprint
55 55 from IPython.utils.ipstruct import Struct
56 56 from IPython.utils.module_paths import find_mod
57 57 from IPython.utils.path import get_py_filename, unquote_filename
58 58 from IPython.utils.process import abbrev_cwd
59 59 from IPython.utils.terminal import set_term_title
60 60 from IPython.utils.text import format_screen
61 61 from IPython.utils.timing import clock, clock2
62 62 from IPython.utils.warn import warn, error
63 63
64 64 #-----------------------------------------------------------------------------
65 65 # Magic implementation classes
66 66 #-----------------------------------------------------------------------------
67 67
68 68 @register_magics
69 69 class UserMagics(Magics):
70 70 """Placeholder for user-defined magics to be added at runtime.
71 71
72 72 All magics are eventually merged into a single namespace at runtime, but we
73 73 use this class to isolate the magics defined dynamically by the user into
74 74 their own class.
75 75 """
76 76
77 77
78 78 @register_magics
79 79 class BasicMagics(Magics):
80 80 """Magics that provide central IPython functionality.
81 81
82 82 These are various magics that don't fit into specific categories but that
83 83 are all part of the base 'IPython experience'."""
84 84
85 85 def _lsmagic(self):
86 86 mesc = ESC_MAGIC
87 87 cesc = mesc*2
88 88 mman = self.shell.magics_manager
89 89 magics = mman.lsmagic()
90 90 out = ['Available line magics:',
91 91 mesc + (' '+mesc).join(magics['line']),
92 92 '',
93 93 'Available cell magics:',
94 94 cesc + (' '+cesc).join(magics['cell']),
95 95 '',
96 96 mman.auto_status()]
97 97 return '\n'.join(out)
98 98
99 99 @line_magic
100 100 def lsmagic(self, parameter_s=''):
101 101 """List currently available magic functions."""
102 102 print self._lsmagic()
103 103
104 104 @line_magic
105 105 def magic(self, parameter_s=''):
106 106 """Print information about the magic function system.
107 107
108 108 Supported formats: -latex, -brief, -rest
109 109 """
110 110
111 111 mode = ''
112 112 try:
113 113 mode = parameter_s.split()[0][1:]
114 114 if mode == 'rest':
115 115 rest_docs = []
116 116 except:
117 117 pass
118 118
119 119 magic_docs = []
120 120 escapes = dict(line=ESC_MAGIC, cell=ESC_MAGIC*2)
121 121 magics = self.shell.magics_manager.magics
122 122
123 123 for mtype in ('line', 'cell'):
124 124 escape = escapes[mtype]
125 125 for fname, fn in magics[mtype].iteritems():
126 126
127 127 if mode == 'brief':
128 128 # only first line
129 129 if fn.__doc__:
130 130 fndoc = fn.__doc__.split('\n',1)[0]
131 131 else:
132 132 fndoc = 'No documentation'
133 133 else:
134 134 if fn.__doc__:
135 135 fndoc = fn.__doc__.rstrip()
136 136 else:
137 137 fndoc = 'No documentation'
138 138
139 139 if mode == 'rest':
140 140 rest_docs.append('**%s%s**::\n\n\t%s\n\n' %
141 141 (escape, fname, fndoc))
142 142 else:
143 143 magic_docs.append('%s%s:\n\t%s\n' %
144 144 (escape, fname, fndoc))
145 145
146 146 magic_docs = ''.join(magic_docs)
147 147
148 148 if mode == 'rest':
149 149 return "".join(rest_docs)
150 150
151 151 if mode == 'latex':
152 152 print self.format_latex(magic_docs)
153 153 return
154 154 else:
155 155 magic_docs = format_screen(magic_docs)
156 156 if mode == 'brief':
157 157 return magic_docs
158 158
159 159 out = ["""
160 160 IPython's 'magic' functions
161 161 ===========================
162 162
163 163 The magic function system provides a series of functions which allow you to
164 164 control the behavior of IPython itself, plus a lot of system-type
165 165 features. All these functions are prefixed with a % character, but parameters
166 166 are given without parentheses or quotes.
167 167
168 168 NOTE: If you have 'automagic' enabled (via the command line option or with the
169 169 %automagic function), you don't need to type in the % explicitly. By default,
170 170 IPython ships with automagic on, so you should only rarely need the % escape.
171 171
172 172 Example: typing '%cd mydir' (without the quotes) changes you working directory
173 173 to 'mydir', if it exists.
174 174
175 175 For a list of the available magic functions, use %lsmagic. For a description
176 176 of any of them, type %magic_name?, e.g. '%cd?'.
177 177
178 178 Currently the magic system has the following functions:""",
179 179 magic_docs,
180 180 "Summary of magic functions (from %slsmagic):",
181 181 self._lsmagic(),
182 182 ]
183 183 page.page('\n'.join(out))
184 184
185 185
186 186 @line_magic
187 187 def page(self, parameter_s=''):
188 188 """Pretty print the object and display it through a pager.
189 189
190 190 %page [options] OBJECT
191 191
192 192 If no object is given, use _ (last output).
193 193
194 194 Options:
195 195
196 196 -r: page str(object), don't pretty-print it."""
197 197
198 198 # After a function contributed by Olivier Aubert, slightly modified.
199 199
200 200 # Process options/args
201 201 opts, args = self.parse_options(parameter_s, 'r')
202 202 raw = 'r' in opts
203 203
204 204 oname = args and args or '_'
205 205 info = self._ofind(oname)
206 206 if info['found']:
207 207 txt = (raw and str or pformat)( info['obj'] )
208 208 page.page(txt)
209 209 else:
210 210 print 'Object `%s` not found' % oname
211 211
212 212 @line_magic
213 213 def profile(self, parameter_s=''):
214 214 """Print your currently active IPython profile."""
215 215 from IPython.core.application import BaseIPythonApplication
216 216 if BaseIPythonApplication.initialized():
217 217 print BaseIPythonApplication.instance().profile
218 218 else:
219 219 error("profile is an application-level value, but you don't appear to be in an IPython application")
220 220
221 221 @line_magic
222 222 def pprint(self, parameter_s=''):
223 223 """Toggle pretty printing on/off."""
224 224 ptformatter = self.shell.display_formatter.formatters['text/plain']
225 225 ptformatter.pprint = bool(1 - ptformatter.pprint)
226 226 print 'Pretty printing has been turned', \
227 227 ['OFF','ON'][ptformatter.pprint]
228 228
229 229 @line_magic
230 230 def colors(self, parameter_s=''):
231 231 """Switch color scheme for prompts, info system and exception handlers.
232 232
233 233 Currently implemented schemes: NoColor, Linux, LightBG.
234 234
235 235 Color scheme names are not case-sensitive.
236 236
237 237 Examples
238 238 --------
239 239 To get a plain black and white terminal::
240 240
241 241 %colors nocolor
242 242 """
243 243 def color_switch_err(name):
244 244 warn('Error changing %s color schemes.\n%s' %
245 245 (name,sys.exc_info()[1]))
246 246
247 247
248 248 new_scheme = parameter_s.strip()
249 249 if not new_scheme:
250 250 raise UsageError(
251 251 "%colors: you must specify a color scheme. See '%colors?'")
252 252 return
253 253 # local shortcut
254 254 shell = self.shell
255 255
256 256 import IPython.utils.rlineimpl as readline
257 257
258 258 if not shell.colors_force and \
259 259 not readline.have_readline and sys.platform == "win32":
260 260 msg = """\
261 261 Proper color support under MS Windows requires the pyreadline library.
262 262 You can find it at:
263 263 http://ipython.org/pyreadline.html
264 264 Gary's readline needs the ctypes module, from:
265 265 http://starship.python.net/crew/theller/ctypes
266 266 (Note that ctypes is already part of Python versions 2.5 and newer).
267 267
268 268 Defaulting color scheme to 'NoColor'"""
269 269 new_scheme = 'NoColor'
270 270 warn(msg)
271 271
272 272 # readline option is 0
273 273 if not shell.colors_force and not shell.has_readline:
274 274 new_scheme = 'NoColor'
275 275
276 276 # Set prompt colors
277 277 try:
278 278 shell.prompt_manager.color_scheme = new_scheme
279 279 except:
280 280 color_switch_err('prompt')
281 281 else:
282 282 shell.colors = \
283 283 shell.prompt_manager.color_scheme_table.active_scheme_name
284 284 # Set exception colors
285 285 try:
286 286 shell.InteractiveTB.set_colors(scheme = new_scheme)
287 287 shell.SyntaxTB.set_colors(scheme = new_scheme)
288 288 except:
289 289 color_switch_err('exception')
290 290
291 291 # Set info (for 'object?') colors
292 292 if shell.color_info:
293 293 try:
294 294 shell.inspector.set_active_scheme(new_scheme)
295 295 except:
296 296 color_switch_err('object inspector')
297 297 else:
298 298 shell.inspector.set_active_scheme('NoColor')
299 299
300 300 @line_magic
301 301 def xmode(self, parameter_s=''):
302 302 """Switch modes for the exception handlers.
303 303
304 304 Valid modes: Plain, Context and Verbose.
305 305
306 306 If called without arguments, acts as a toggle."""
307 307
308 308 def xmode_switch_err(name):
309 309 warn('Error changing %s exception modes.\n%s' %
310 310 (name,sys.exc_info()[1]))
311 311
312 312 shell = self.shell
313 313 new_mode = parameter_s.strip().capitalize()
314 314 try:
315 315 shell.InteractiveTB.set_mode(mode=new_mode)
316 316 print 'Exception reporting mode:',shell.InteractiveTB.mode
317 317 except:
318 318 xmode_switch_err('user')
319 319
320 320 @line_magic
321 321 def quickref(self,arg):
322 322 """ Show a quick reference sheet """
323 323 from IPython.core.usage import quick_reference
324 324 qr = quick_reference + self.magic('-brief')
325 325 page.page(qr)
326 326
327 327 @line_magic
328 328 def doctest_mode(self, parameter_s=''):
329 329 """Toggle doctest mode on and off.
330 330
331 331 This mode is intended to make IPython behave as much as possible like a
332 332 plain Python shell, from the perspective of how its prompts, exceptions
333 333 and output look. This makes it easy to copy and paste parts of a
334 334 session into doctests. It does so by:
335 335
336 336 - Changing the prompts to the classic ``>>>`` ones.
337 337 - Changing the exception reporting mode to 'Plain'.
338 338 - Disabling pretty-printing of output.
339 339
340 340 Note that IPython also supports the pasting of code snippets that have
341 341 leading '>>>' and '...' prompts in them. This means that you can paste
342 342 doctests from files or docstrings (even if they have leading
343 343 whitespace), and the code will execute correctly. You can then use
344 344 '%history -t' to see the translated history; this will give you the
345 345 input after removal of all the leading prompts and whitespace, which
346 346 can be pasted back into an editor.
347 347
348 348 With these features, you can switch into this mode easily whenever you
349 349 need to do testing and changes to doctests, without having to leave
350 350 your existing IPython session.
351 351 """
352 352
353 353 # Shorthands
354 354 shell = self.shell
355 355 pm = shell.prompt_manager
356 356 meta = shell.meta
357 357 disp_formatter = self.shell.display_formatter
358 358 ptformatter = disp_formatter.formatters['text/plain']
359 359 # dstore is a data store kept in the instance metadata bag to track any
360 360 # changes we make, so we can undo them later.
361 361 dstore = meta.setdefault('doctest_mode',Struct())
362 362 save_dstore = dstore.setdefault
363 363
364 364 # save a few values we'll need to recover later
365 365 mode = save_dstore('mode',False)
366 366 save_dstore('rc_pprint',ptformatter.pprint)
367 367 save_dstore('xmode',shell.InteractiveTB.mode)
368 368 save_dstore('rc_separate_out',shell.separate_out)
369 369 save_dstore('rc_separate_out2',shell.separate_out2)
370 370 save_dstore('rc_prompts_pad_left',pm.justify)
371 371 save_dstore('rc_separate_in',shell.separate_in)
372 372 save_dstore('rc_plain_text_only',disp_formatter.plain_text_only)
373 373 save_dstore('prompt_templates',(pm.in_template, pm.in2_template, pm.out_template))
374 374
375 375 if mode == False:
376 376 # turn on
377 377 pm.in_template = '>>> '
378 378 pm.in2_template = '... '
379 379 pm.out_template = ''
380 380
381 381 # Prompt separators like plain python
382 382 shell.separate_in = ''
383 383 shell.separate_out = ''
384 384 shell.separate_out2 = ''
385 385
386 386 pm.justify = False
387 387
388 388 ptformatter.pprint = False
389 389 disp_formatter.plain_text_only = True
390 390
391 391 shell.magic('xmode Plain')
392 392 else:
393 393 # turn off
394 394 pm.in_template, pm.in2_template, pm.out_template = dstore.prompt_templates
395 395
396 396 shell.separate_in = dstore.rc_separate_in
397 397
398 398 shell.separate_out = dstore.rc_separate_out
399 399 shell.separate_out2 = dstore.rc_separate_out2
400 400
401 401 pm.justify = dstore.rc_prompts_pad_left
402 402
403 403 ptformatter.pprint = dstore.rc_pprint
404 404 disp_formatter.plain_text_only = dstore.rc_plain_text_only
405 405
406 406 shell.magic('xmode ' + dstore.xmode)
407 407
408 408 # Store new mode and inform
409 409 dstore.mode = bool(1-int(mode))
410 410 mode_label = ['OFF','ON'][dstore.mode]
411 411 print 'Doctest mode is:', mode_label
412 412
413 413 @line_magic
414 414 def gui(self, parameter_s=''):
415 415 """Enable or disable IPython GUI event loop integration.
416 416
417 417 %gui [GUINAME]
418 418
419 419 This magic replaces IPython's threaded shells that were activated
420 420 using the (pylab/wthread/etc.) command line flags. GUI toolkits
421 421 can now be enabled at runtime and keyboard
422 422 interrupts should work without any problems. The following toolkits
423 423 are supported: wxPython, PyQt4, PyGTK, Tk and Cocoa (OSX)::
424 424
425 425 %gui wx # enable wxPython event loop integration
426 426 %gui qt4|qt # enable PyQt4 event loop integration
427 427 %gui gtk # enable PyGTK event loop integration
428 428 %gui gtk3 # enable Gtk3 event loop integration
429 429 %gui tk # enable Tk event loop integration
430 430 %gui OSX # enable Cocoa event loop integration
431 431 # (requires %matplotlib 1.1)
432 432 %gui # disable all event loop integration
433 433
434 434 WARNING: after any of these has been called you can simply create
435 435 an application object, but DO NOT start the event loop yourself, as
436 436 we have already handled that.
437 437 """
438 438 opts, arg = self.parse_options(parameter_s, '')
439 439 if arg=='': arg = None
440 440 try:
441 441 return self.enable_gui(arg)
442 442 except Exception as e:
443 443 # print simple error message, rather than traceback if we can't
444 444 # hook up the GUI
445 445 error(str(e))
446 446
447 447 @skip_doctest
448 448 @line_magic
449 449 def precision(self, s=''):
450 450 """Set floating point precision for pretty printing.
451 451
452 452 Can set either integer precision or a format string.
453 453
454 454 If numpy has been imported and precision is an int,
455 455 numpy display precision will also be set, via ``numpy.set_printoptions``.
456 456
457 457 If no argument is given, defaults will be restored.
458 458
459 459 Examples
460 460 --------
461 461 ::
462 462
463 463 In [1]: from math import pi
464 464
465 465 In [2]: %precision 3
466 466 Out[2]: u'%.3f'
467 467
468 468 In [3]: pi
469 469 Out[3]: 3.142
470 470
471 471 In [4]: %precision %i
472 472 Out[4]: u'%i'
473 473
474 474 In [5]: pi
475 475 Out[5]: 3
476 476
477 477 In [6]: %precision %e
478 478 Out[6]: u'%e'
479 479
480 480 In [7]: pi**10
481 481 Out[7]: 9.364805e+04
482 482
483 483 In [8]: %precision
484 484 Out[8]: u'%r'
485 485
486 486 In [9]: pi**10
487 487 Out[9]: 93648.047476082982
488 488 """
489 489 ptformatter = self.shell.display_formatter.formatters['text/plain']
490 490 ptformatter.float_precision = s
491 491 return ptformatter.float_format
492 492
493 493 @magic_arguments.magic_arguments()
494 494 @magic_arguments.argument(
495 495 '-e', '--export', action='store_true', default=False,
496 496 help='Export IPython history as a notebook. The filename argument '
497 497 'is used to specify the notebook name and format. For example '
498 498 'a filename of notebook.ipynb will result in a notebook name '
499 499 'of "notebook" and a format of "xml". Likewise using a ".json" '
500 500 'or ".py" file extension will write the notebook in the json '
501 501 'or py formats.'
502 502 )
503 503 @magic_arguments.argument(
504 504 '-f', '--format',
505 505 help='Convert an existing IPython notebook to a new format. This option '
506 506 'specifies the new format and can have the values: xml, json, py. '
507 507 'The target filename is chosen automatically based on the new '
508 508 'format. The filename argument gives the name of the source file.'
509 509 )
510 510 @magic_arguments.argument(
511 511 'filename', type=unicode,
512 512 help='Notebook name or filename'
513 513 )
514 514 @line_magic
515 515 def notebook(self, s):
516 516 """Export and convert IPython notebooks.
517 517
518 518 This function can export the current IPython history to a notebook file
519 519 or can convert an existing notebook file into a different format. For
520 520 example, to export the history to "foo.ipynb" do "%notebook -e foo.ipynb".
521 521 To export the history to "foo.py" do "%notebook -e foo.py". To convert
522 522 "foo.ipynb" to "foo.json" do "%notebook -f json foo.ipynb". Possible
523 523 formats include (json/ipynb, py).
524 524 """
525 525 args = magic_arguments.parse_argstring(self.notebook, s)
526 526
527 527 from IPython.nbformat import current
528 528 args.filename = unquote_filename(args.filename)
529 529 if args.export:
530 530 fname, name, format = current.parse_filename(args.filename)
531 531 cells = []
532 532 hist = list(self.shell.history_manager.get_range())
533 533 for session, prompt_number, input in hist[:-1]:
534 534 cells.append(current.new_code_cell(prompt_number=prompt_number,
535 535 input=input))
536 536 worksheet = current.new_worksheet(cells=cells)
537 537 nb = current.new_notebook(name=name,worksheets=[worksheet])
538 538 with io.open(fname, 'w', encoding='utf-8') as f:
539 539 current.write(nb, f, format);
540 540 elif args.format is not None:
541 541 old_fname, old_name, old_format = current.parse_filename(args.filename)
542 542 new_format = args.format
543 543 if new_format == u'xml':
544 544 raise ValueError('Notebooks cannot be written as xml.')
545 545 elif new_format == u'ipynb' or new_format == u'json':
546 546 new_fname = old_name + u'.ipynb'
547 547 new_format = u'json'
548 548 elif new_format == u'py':
549 549 new_fname = old_name + u'.py'
550 550 else:
551 551 raise ValueError('Invalid notebook format: %s' % new_format)
552 552 with io.open(old_fname, 'r', encoding='utf-8') as f:
553 553 nb = current.read(f, old_format)
554 554 with io.open(new_fname, 'w', encoding='utf-8') as f:
555 555 current.write(nb, f, new_format)
556 556
557 557
558 558 # Used for exception handling in magic_edit
559 559 class MacroToEdit(ValueError): pass
560 560
561 561
562 562 @register_magics
563 563 class CodeMagics(Magics):
564 564 """Magics related to code management (loading, saving, editing, ...)."""
565 565
566 566 @line_magic
567 567 def save(self, parameter_s=''):
568 568 """Save a set of lines or a macro to a given filename.
569 569
570 570 Usage:\\
571 571 %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ...
572 572
573 573 Options:
574 574
575 575 -r: use 'raw' input. By default, the 'processed' history is used,
576 576 so that magics are loaded in their transformed version to valid
577 577 Python. If this option is given, the raw input as typed as the
578 578 command line is used instead.
579 579
580 580 This function uses the same syntax as %history for input ranges,
581 581 then saves the lines to the filename you specify.
582 582
583 583 It adds a '.py' extension to the file if you don't do so yourself, and
584 584 it asks for confirmation before overwriting existing files."""
585 585
586 586 opts,args = self.parse_options(parameter_s,'r',mode='list')
587 587 fname, codefrom = unquote_filename(args[0]), " ".join(args[1:])
588 588 if not fname.endswith('.py'):
589 589 fname += '.py'
590 590 if os.path.isfile(fname):
591 591 ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname)
592 592 if ans.lower() not in ['y','yes']:
593 593 print 'Operation cancelled.'
594 594 return
595 595 try:
596 596 cmds = self.shell.find_user_code(codefrom, 'r' in opts)
597 597 except (TypeError, ValueError) as e:
598 598 print e.args[0]
599 599 return
600 600 with io.open(fname,'w', encoding="utf-8") as f:
601 601 f.write(u"# coding: utf-8\n")
602 602 f.write(py3compat.cast_unicode(cmds))
603 603 print 'The following commands were written to file `%s`:' % fname
604 604 print cmds
605 605
606 606 @line_magic
607 607 def pastebin(self, parameter_s=''):
608 608 """Upload code to Github's Gist paste bin, returning the URL.
609 609
610 610 Usage:\\
611 611 %pastebin [-d "Custom description"] 1-7
612 612
613 613 The argument can be an input history range, a filename, or the name of a
614 614 string or macro.
615 615
616 616 Options:
617 617
618 618 -d: Pass a custom description for the gist. The default will say
619 619 "Pasted from IPython".
620 620 """
621 621 opts, args = self.parse_options(parameter_s, 'd:')
622 622
623 623 try:
624 624 code = self.shell.find_user_code(args)
625 625 except (ValueError, TypeError) as e:
626 626 print e.args[0]
627 627 return
628 628
629 629 post_data = json.dumps({
630 630 "description": opts.get('d', "Pasted from IPython"),
631 631 "public": True,
632 632 "files": {
633 633 "file1.py": {
634 634 "content": code
635 635 }
636 636 }
637 637 }).encode('utf-8')
638 638
639 639 response = urlopen("https://api.github.com/gists", post_data)
640 640 response_data = json.loads(response.read().decode('utf-8'))
641 641 return response_data['html_url']
642 642
643 643 @line_magic
644 644 def loadpy(self, arg_s):
645 645 """Load a .py python script into the GUI console.
646 646
647 647 This magic command can either take a local filename or a url::
648 648
649 649 %loadpy myscript.py
650 650 %loadpy http://www.example.com/myscript.py
651 651 """
652 652 arg_s = unquote_filename(arg_s)
653 653 remote_url = arg_s.startswith(('http://', 'https://'))
654 654 local_url = not remote_url
655 655 if local_url and not arg_s.endswith('.py'):
656 656 # Local files must be .py; for remote URLs it's possible that the
657 657 # fetch URL doesn't have a .py in it (many servers have an opaque
658 658 # URL, such as scipy-central.org).
659 659 raise ValueError('%%loadpy only works with .py files: %s' % arg_s)
660 660
661 661 # openpy takes care of finding the source encoding (per PEP 263)
662 662 if remote_url:
663 663 contents = openpy.read_py_url(arg_s, skip_encoding_cookie=True)
664 664 else:
665 665 contents = openpy.read_py_file(arg_s, skip_encoding_cookie=True)
666 666
667 667 self.set_next_input(contents)
668 668
669 669 def _find_edit_target(self, args, opts, last_call):
670 670 """Utility method used by magic_edit to find what to edit."""
671 671
672 672 def make_filename(arg):
673 673 "Make a filename from the given args"
674 674 arg = unquote_filename(arg)
675 675 try:
676 676 filename = get_py_filename(arg)
677 677 except IOError:
678 678 # If it ends with .py but doesn't already exist, assume we want
679 679 # a new file.
680 680 if arg.endswith('.py'):
681 681 filename = arg
682 682 else:
683 683 filename = None
684 684 return filename
685 685
686 686 # Set a few locals from the options for convenience:
687 687 opts_prev = 'p' in opts
688 688 opts_raw = 'r' in opts
689 689
690 690 # custom exceptions
691 691 class DataIsObject(Exception): pass
692 692
693 693 # Default line number value
694 694 lineno = opts.get('n',None)
695 695
696 696 if opts_prev:
697 697 args = '_%s' % last_call[0]
698 698 if not self.shell.user_ns.has_key(args):
699 699 args = last_call[1]
700 700
701 701 # use last_call to remember the state of the previous call, but don't
702 702 # let it be clobbered by successive '-p' calls.
703 703 try:
704 704 last_call[0] = self.shell.displayhook.prompt_count
705 705 if not opts_prev:
706 706 last_call[1] = args
707 707 except:
708 708 pass
709 709
710 710 # by default this is done with temp files, except when the given
711 711 # arg is a filename
712 712 use_temp = True
713 713
714 714 data = ''
715 715
716 716 # First, see if the arguments should be a filename.
717 717 filename = make_filename(args)
718 718 if filename:
719 719 use_temp = False
720 720 elif args:
721 721 # Mode where user specifies ranges of lines, like in %macro.
722 722 data = self.shell.extract_input_lines(args, opts_raw)
723 723 if not data:
724 724 try:
725 725 # Load the parameter given as a variable. If not a string,
726 726 # process it as an object instead (below)
727 727
728 728 #print '*** args',args,'type',type(args) # dbg
729 729 data = eval(args, self.shell.user_ns)
730 730 if not isinstance(data, basestring):
731 731 raise DataIsObject
732 732
733 733 except (NameError,SyntaxError):
734 734 # given argument is not a variable, try as a filename
735 735 filename = make_filename(args)
736 736 if filename is None:
737 737 warn("Argument given (%s) can't be found as a variable "
738 738 "or as a filename." % args)
739 739 return
740 740 use_temp = False
741 741
742 742 except DataIsObject:
743 743 # macros have a special edit function
744 744 if isinstance(data, Macro):
745 745 raise MacroToEdit(data)
746 746
747 747 # For objects, try to edit the file where they are defined
748 748 try:
749 749 filename = inspect.getabsfile(data)
750 750 if 'fakemodule' in filename.lower() and inspect.isclass(data):
751 751 # class created by %edit? Try to find source
752 752 # by looking for method definitions instead, the
753 753 # __module__ in those classes is FakeModule.
754 754 attrs = [getattr(data, aname) for aname in dir(data)]
755 755 for attr in attrs:
756 756 if not inspect.ismethod(attr):
757 757 continue
758 758 filename = inspect.getabsfile(attr)
759 759 if filename and 'fakemodule' not in filename.lower():
760 760 # change the attribute to be the edit target instead
761 761 data = attr
762 762 break
763 763
764 764 datafile = 1
765 765 except TypeError:
766 766 filename = make_filename(args)
767 767 datafile = 1
768 768 warn('Could not find file where `%s` is defined.\n'
769 769 'Opening a file named `%s`' % (args,filename))
770 770 # Now, make sure we can actually read the source (if it was in
771 771 # a temp file it's gone by now).
772 772 if datafile:
773 773 try:
774 774 if lineno is None:
775 775 lineno = inspect.getsourcelines(data)[1]
776 776 except IOError:
777 777 filename = make_filename(args)
778 778 if filename is None:
779 779 warn('The file `%s` where `%s` was defined cannot '
780 780 'be read.' % (filename,data))
781 781 return
782 782 use_temp = False
783 783
784 784 if use_temp:
785 785 filename = self.shell.mktempfile(data)
786 786 print 'IPython will make a temporary file named:',filename
787 787
788 788 return filename, lineno, use_temp
789 789
790 790 def _edit_macro(self,mname,macro):
791 791 """open an editor with the macro data in a file"""
792 792 filename = self.shell.mktempfile(macro.value)
793 793 self.shell.hooks.editor(filename)
794 794
795 795 # and make a new macro object, to replace the old one
796 796 mfile = open(filename)
797 797 mvalue = mfile.read()
798 798 mfile.close()
799 799 self.shell.user_ns[mname] = Macro(mvalue)
800 800
801 801 @line_magic
802 802 def ed(self, parameter_s=''):
803 803 """Alias to %edit."""
804 804 return self.magic_edit(parameter_s)
805 805
806 806 @skip_doctest
807 807 @line_magic
808 808 def edit(self, parameter_s='',last_call=['','']):
809 809 """Bring up an editor and execute the resulting code.
810 810
811 811 Usage:
812 812 %edit [options] [args]
813 813
814 814 %edit runs IPython's editor hook. The default version of this hook is
815 815 set to call the editor specified by your $EDITOR environment variable.
816 816 If this isn't found, it will default to vi under Linux/Unix and to
817 817 notepad under Windows. See the end of this docstring for how to change
818 818 the editor hook.
819 819
820 820 You can also set the value of this editor via the
821 821 ``TerminalInteractiveShell.editor`` option in your configuration file.
822 822 This is useful if you wish to use a different editor from your typical
823 823 default with IPython (and for Windows users who typically don't set
824 824 environment variables).
825 825
826 826 This command allows you to conveniently edit multi-line code right in
827 827 your IPython session.
828 828
829 829 If called without arguments, %edit opens up an empty editor with a
830 830 temporary file and will execute the contents of this file when you
831 831 close it (don't forget to save it!).
832 832
833 833
834 834 Options:
835 835
836 836 -n <number>: open the editor at a specified line number. By default,
837 837 the IPython editor hook uses the unix syntax 'editor +N filename', but
838 838 you can configure this by providing your own modified hook if your
839 839 favorite editor supports line-number specifications with a different
840 840 syntax.
841 841
842 842 -p: this will call the editor with the same data as the previous time
843 843 it was used, regardless of how long ago (in your current session) it
844 844 was.
845 845
846 846 -r: use 'raw' input. This option only applies to input taken from the
847 847 user's history. By default, the 'processed' history is used, so that
848 848 magics are loaded in their transformed version to valid Python. If
849 849 this option is given, the raw input as typed as the command line is
850 850 used instead. When you exit the editor, it will be executed by
851 851 IPython's own processor.
852 852
853 853 -x: do not execute the edited code immediately upon exit. This is
854 854 mainly useful if you are editing programs which need to be called with
855 855 command line arguments, which you can then do using %run.
856 856
857 857
858 858 Arguments:
859 859
860 860 If arguments are given, the following possibilities exist:
861 861
862 862 - If the argument is a filename, IPython will load that into the
863 863 editor. It will execute its contents with execfile() when you exit,
864 864 loading any code in the file into your interactive namespace.
865 865
866 866 - The arguments are ranges of input history, e.g. "7 ~1/4-6".
867 867 The syntax is the same as in the %history magic.
868 868
869 869 - If the argument is a string variable, its contents are loaded
870 870 into the editor. You can thus edit any string which contains
871 871 python code (including the result of previous edits).
872 872
873 873 - If the argument is the name of an object (other than a string),
874 874 IPython will try to locate the file where it was defined and open the
875 875 editor at the point where it is defined. You can use `%edit function`
876 876 to load an editor exactly at the point where 'function' is defined,
877 877 edit it and have the file be executed automatically.
878 878
879 879 - If the object is a macro (see %macro for details), this opens up your
880 880 specified editor with a temporary file containing the macro's data.
881 881 Upon exit, the macro is reloaded with the contents of the file.
882 882
883 883 Note: opening at an exact line is only supported under Unix, and some
884 884 editors (like kedit and gedit up to Gnome 2.8) do not understand the
885 885 '+NUMBER' parameter necessary for this feature. Good editors like
886 886 (X)Emacs, vi, jed, pico and joe all do.
887 887
888 888 After executing your code, %edit will return as output the code you
889 889 typed in the editor (except when it was an existing file). This way
890 890 you can reload the code in further invocations of %edit as a variable,
891 891 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
892 892 the output.
893 893
894 894 Note that %edit is also available through the alias %ed.
895 895
896 896 This is an example of creating a simple function inside the editor and
897 897 then modifying it. First, start up the editor::
898 898
899 899 In [1]: ed
900 900 Editing... done. Executing edited code...
901 901 Out[1]: 'def foo():\\n print "foo() was defined in an editing
902 902 session"\\n'
903 903
904 904 We can then call the function foo()::
905 905
906 906 In [2]: foo()
907 907 foo() was defined in an editing session
908 908
909 909 Now we edit foo. IPython automatically loads the editor with the
910 910 (temporary) file where foo() was previously defined::
911 911
912 912 In [3]: ed foo
913 913 Editing... done. Executing edited code...
914 914
915 915 And if we call foo() again we get the modified version::
916 916
917 917 In [4]: foo()
918 918 foo() has now been changed!
919 919
920 920 Here is an example of how to edit a code snippet successive
921 921 times. First we call the editor::
922 922
923 923 In [5]: ed
924 924 Editing... done. Executing edited code...
925 925 hello
926 926 Out[5]: "print 'hello'\\n"
927 927
928 928 Now we call it again with the previous output (stored in _)::
929 929
930 930 In [6]: ed _
931 931 Editing... done. Executing edited code...
932 932 hello world
933 933 Out[6]: "print 'hello world'\\n"
934 934
935 935 Now we call it with the output #8 (stored in _8, also as Out[8])::
936 936
937 937 In [7]: ed _8
938 938 Editing... done. Executing edited code...
939 939 hello again
940 940 Out[7]: "print 'hello again'\\n"
941 941
942 942
943 943 Changing the default editor hook:
944 944
945 945 If you wish to write your own editor hook, you can put it in a
946 946 configuration file which you load at startup time. The default hook
947 947 is defined in the IPython.core.hooks module, and you can use that as a
948 948 starting example for further modifications. That file also has
949 949 general instructions on how to set a new hook for use once you've
950 950 defined it."""
951 951 opts,args = self.parse_options(parameter_s,'prxn:')
952 952
953 953 try:
954 954 filename, lineno, is_temp = self._find_edit_target(args, opts, last_call)
955 955 except MacroToEdit as e:
956 956 self._edit_macro(args, e.args[0])
957 957 return
958 958
959 959 # do actual editing here
960 960 print 'Editing...',
961 961 sys.stdout.flush()
962 962 try:
963 963 # Quote filenames that may have spaces in them
964 964 if ' ' in filename:
965 965 filename = "'%s'" % filename
966 966 self.shell.hooks.editor(filename,lineno)
967 967 except TryNext:
968 968 warn('Could not open editor')
969 969 return
970 970
971 971 # XXX TODO: should this be generalized for all string vars?
972 972 # For now, this is special-cased to blocks created by cpaste
973 973 if args.strip() == 'pasted_block':
974 974 self.shell.user_ns['pasted_block'] = file_read(filename)
975 975
976 976 if 'x' in opts: # -x prevents actual execution
977 977 print
978 978 else:
979 979 print 'done. Executing edited code...'
980 980 if 'r' in opts: # Untranslated IPython code
981 981 self.shell.run_cell(file_read(filename),
982 982 store_history=False)
983 983 else:
984 984 self.shell.safe_execfile(filename, self.shell.user_ns,
985 985 self.shell.user_ns)
986 986
987 987 if is_temp:
988 988 try:
989 989 return open(filename).read()
990 990 except IOError,msg:
991 991 if msg.filename == filename:
992 992 warn('File not found. Did you forget to save?')
993 993 return
994 994 else:
995 995 self.shell.showtraceback()
996 996
997 997
998 998 @register_magics
999 999 class ConfigMagics(Magics):
1000 1000
1001 1001 def __init__(self, shell):
1002 1002 super(ConfigMagics, self).__init__(shell)
1003 1003 self.configurables = []
1004 1004
1005 1005 @line_magic
1006 1006 def config(self, s):
1007 1007 """configure IPython
1008 1008
1009 1009 %config Class[.trait=value]
1010 1010
1011 1011 This magic exposes most of the IPython config system. Any
1012 1012 Configurable class should be able to be configured with the simple
1013 1013 line::
1014 1014
1015 1015 %config Class.trait=value
1016 1016
1017 1017 Where `value` will be resolved in the user's namespace, if it is an
1018 1018 expression or variable name.
1019 1019
1020 1020 Examples
1021 1021 --------
1022 1022
1023 1023 To see what classes are available for config, pass no arguments::
1024 1024
1025 1025 In [1]: %config
1026 1026 Available objects for config:
1027 1027 TerminalInteractiveShell
1028 1028 HistoryManager
1029 1029 PrefilterManager
1030 1030 AliasManager
1031 1031 IPCompleter
1032 1032 PromptManager
1033 1033 DisplayFormatter
1034 1034
1035 1035 To view what is configurable on a given class, just pass the class
1036 1036 name::
1037 1037
1038 1038 In [2]: %config IPCompleter
1039 1039 IPCompleter options
1040 1040 -----------------
1041 1041 IPCompleter.omit__names=<Enum>
1042 1042 Current: 2
1043 1043 Choices: (0, 1, 2)
1044 1044 Instruct the completer to omit private method names
1045 1045 Specifically, when completing on ``object.<tab>``.
1046 1046 When 2 [default]: all names that start with '_' will be excluded.
1047 1047 When 1: all 'magic' names (``__foo__``) will be excluded.
1048 1048 When 0: nothing will be excluded.
1049 1049 IPCompleter.merge_completions=<CBool>
1050 1050 Current: True
1051 1051 Whether to merge completion results into a single list
1052 1052 If False, only the completion results from the first non-empty completer
1053 1053 will be returned.
1054 1054 IPCompleter.limit_to__all__=<CBool>
1055 1055 Current: False
1056 1056 Instruct the completer to use __all__ for the completion
1057 1057 Specifically, when completing on ``object.<tab>``.
1058 1058 When True: only those names in obj.__all__ will be included.
1059 1059 When False [default]: the __all__ attribute is ignored
1060 1060 IPCompleter.greedy=<CBool>
1061 1061 Current: False
1062 1062 Activate greedy completion
1063 1063 This will enable completion on elements of lists, results of function calls,
1064 1064 etc., but can be unsafe because the code is actually evaluated on TAB.
1065 1065
1066 1066 but the real use is in setting values::
1067 1067
1068 1068 In [3]: %config IPCompleter.greedy = True
1069 1069
1070 1070 and these values are read from the user_ns if they are variables::
1071 1071
1072 1072 In [4]: feeling_greedy=False
1073 1073
1074 1074 In [5]: %config IPCompleter.greedy = feeling_greedy
1075 1075
1076 1076 """
1077 1077 from IPython.config.loader import Config
1078 1078 # some IPython objects are Configurable, but do not yet have
1079 1079 # any configurable traits. Exclude them from the effects of
1080 1080 # this magic, as their presence is just noise:
1081 1081 configurables = [ c for c in self.shell.configurables
1082 1082 if c.__class__.class_traits(config=True) ]
1083 1083 classnames = [ c.__class__.__name__ for c in configurables ]
1084 1084
1085 1085 line = s.strip()
1086 1086 if not line:
1087 1087 # print available configurable names
1088 1088 print "Available objects for config:"
1089 1089 for name in classnames:
1090 1090 print " ", name
1091 1091 return
1092 1092 elif line in classnames:
1093 1093 # `%config TerminalInteractiveShell` will print trait info for
1094 1094 # TerminalInteractiveShell
1095 1095 c = configurables[classnames.index(line)]
1096 1096 cls = c.__class__
1097 1097 help = cls.class_get_help(c)
1098 1098 # strip leading '--' from cl-args:
1099 1099 help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
1100 1100 print help
1101 1101 return
1102 1102 elif '=' not in line:
1103 1103 raise UsageError("Invalid config statement: %r, should be Class.trait = value" % line)
1104 1104
1105 1105
1106 1106 # otherwise, assume we are setting configurables.
1107 1107 # leave quotes on args when splitting, because we want
1108 1108 # unquoted args to eval in user_ns
1109 1109 cfg = Config()
1110 1110 exec "cfg."+line in locals(), self.shell.user_ns
1111 1111
1112 1112 for configurable in configurables:
1113 1113 try:
1114 1114 configurable.update_config(cfg)
1115 1115 except Exception as e:
1116 1116 error(e)
1117 1117
1118 1118
1119 1119 @register_magics
1120 1120 class NamespaceMagics(Magics):
1121 1121 """Magics to manage various aspects of the user's namespace.
1122 1122
1123 1123 These include listing variables, introspecting into them, etc.
1124 1124 """
1125 1125
1126 1126 @line_magic
1127 1127 def pinfo(self, parameter_s='', namespaces=None):
1128 1128 """Provide detailed information about an object.
1129 1129
1130 1130 '%pinfo object' is just a synonym for object? or ?object."""
1131 1131
1132 1132 #print 'pinfo par: <%s>' % parameter_s # dbg
1133 1133
1134 1134
1135 1135 # detail_level: 0 -> obj? , 1 -> obj??
1136 1136 detail_level = 0
1137 1137 # We need to detect if we got called as 'pinfo pinfo foo', which can
1138 1138 # happen if the user types 'pinfo foo?' at the cmd line.
1139 1139 pinfo,qmark1,oname,qmark2 = \
1140 1140 re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups()
1141 1141 if pinfo or qmark1 or qmark2:
1142 1142 detail_level = 1
1143 1143 if "*" in oname:
1144 1144 self.psearch(oname)
1145 1145 else:
1146 1146 self.shell._inspect('pinfo', oname, detail_level=detail_level,
1147 1147 namespaces=namespaces)
1148 1148
1149 1149 @line_magic
1150 1150 def pinfo2(self, parameter_s='', namespaces=None):
1151 1151 """Provide extra detailed information about an object.
1152 1152
1153 1153 '%pinfo2 object' is just a synonym for object?? or ??object."""
1154 1154 self.shell._inspect('pinfo', parameter_s, detail_level=1,
1155 1155 namespaces=namespaces)
1156 1156
1157 1157 @skip_doctest
1158 1158 @line_magic
1159 1159 def pdef(self, parameter_s='', namespaces=None):
1160 1160 """Print the definition header for any callable object.
1161 1161
1162 1162 If the object is a class, print the constructor information.
1163 1163
1164 1164 Examples
1165 1165 --------
1166 1166 ::
1167 1167
1168 1168 In [3]: %pdef urllib.urlopen
1169 1169 urllib.urlopen(url, data=None, proxies=None)
1170 1170 """
1171 1171 self._inspect('pdef',parameter_s, namespaces)
1172 1172
1173 1173 @line_magic
1174 1174 def pdoc(self, parameter_s='', namespaces=None):
1175 1175 """Print the docstring for an object.
1176 1176
1177 1177 If the given object is a class, it will print both the class and the
1178 1178 constructor docstrings."""
1179 1179 self._inspect('pdoc',parameter_s, namespaces)
1180 1180
1181 1181 @line_magic
1182 1182 def psource(self, parameter_s='', namespaces=None):
1183 1183 """Print (or run through pager) the source code for an object."""
1184 1184 self._inspect('psource',parameter_s, namespaces)
1185 1185
1186 1186 @line_magic
1187 1187 def pfile(self, parameter_s=''):
1188 1188 """Print (or run through pager) the file where an object is defined.
1189 1189
1190 1190 The file opens at the line where the object definition begins. IPython
1191 1191 will honor the environment variable PAGER if set, and otherwise will
1192 1192 do its best to print the file in a convenient form.
1193 1193
1194 1194 If the given argument is not an object currently defined, IPython will
1195 1195 try to interpret it as a filename (automatically adding a .py extension
1196 1196 if needed). You can thus use %pfile as a syntax highlighting code
1197 1197 viewer."""
1198 1198
1199 1199 # first interpret argument as an object name
1200 1200 out = self._inspect('pfile',parameter_s)
1201 1201 # if not, try the input as a filename
1202 1202 if out == 'not found':
1203 1203 try:
1204 1204 filename = get_py_filename(parameter_s)
1205 1205 except IOError,msg:
1206 1206 print msg
1207 1207 return
1208 1208 page.page(self.shell.inspector.format(open(filename).read()))
1209 1209
1210 1210 @line_magic
1211 1211 def psearch(self, parameter_s=''):
1212 1212 """Search for object in namespaces by wildcard.
1213 1213
1214 1214 %psearch [options] PATTERN [OBJECT TYPE]
1215 1215
1216 1216 Note: ? can be used as a synonym for %psearch, at the beginning or at
1217 1217 the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the
1218 1218 rest of the command line must be unchanged (options come first), so
1219 1219 for example the following forms are equivalent
1220 1220
1221 1221 %psearch -i a* function
1222 1222 -i a* function?
1223 1223 ?-i a* function
1224 1224
1225 1225 Arguments:
1226 1226
1227 1227 PATTERN
1228 1228
1229 1229 where PATTERN is a string containing * as a wildcard similar to its
1230 1230 use in a shell. The pattern is matched in all namespaces on the
1231 1231 search path. By default objects starting with a single _ are not
1232 1232 matched, many IPython generated objects have a single
1233 1233 underscore. The default is case insensitive matching. Matching is
1234 1234 also done on the attributes of objects and not only on the objects
1235 1235 in a module.
1236 1236
1237 1237 [OBJECT TYPE]
1238 1238
1239 1239 Is the name of a python type from the types module. The name is
1240 1240 given in lowercase without the ending type, ex. StringType is
1241 1241 written string. By adding a type here only objects matching the
1242 1242 given type are matched. Using all here makes the pattern match all
1243 1243 types (this is the default).
1244 1244
1245 1245 Options:
1246 1246
1247 1247 -a: makes the pattern match even objects whose names start with a
1248 1248 single underscore. These names are normally omitted from the
1249 1249 search.
1250 1250
1251 1251 -i/-c: make the pattern case insensitive/sensitive. If neither of
1252 1252 these options are given, the default is read from your configuration
1253 1253 file, with the option ``InteractiveShell.wildcards_case_sensitive``.
1254 1254 If this option is not specified in your configuration file, IPython's
1255 1255 internal default is to do a case sensitive search.
1256 1256
1257 1257 -e/-s NAMESPACE: exclude/search a given namespace. The pattern you
1258 1258 specify can be searched in any of the following namespaces:
1259 1259 'builtin', 'user', 'user_global','internal', 'alias', where
1260 1260 'builtin' and 'user' are the search defaults. Note that you should
1261 1261 not use quotes when specifying namespaces.
1262 1262
1263 1263 'Builtin' contains the python module builtin, 'user' contains all
1264 1264 user data, 'alias' only contain the shell aliases and no python
1265 1265 objects, 'internal' contains objects used by IPython. The
1266 1266 'user_global' namespace is only used by embedded IPython instances,
1267 1267 and it contains module-level globals. You can add namespaces to the
1268 1268 search with -s or exclude them with -e (these options can be given
1269 1269 more than once).
1270 1270
1271 1271 Examples
1272 1272 --------
1273 1273 ::
1274 1274
1275 1275 %psearch a* -> objects beginning with an a
1276 1276 %psearch -e builtin a* -> objects NOT in the builtin space starting in a
1277 1277 %psearch a* function -> all functions beginning with an a
1278 1278 %psearch re.e* -> objects beginning with an e in module re
1279 1279 %psearch r*.e* -> objects that start with e in modules starting in r
1280 1280 %psearch r*.* string -> all strings in modules beginning with r
1281 1281
1282 1282 Case sensitive search::
1283 1283
1284 1284 %psearch -c a* list all object beginning with lower case a
1285 1285
1286 1286 Show objects beginning with a single _::
1287 1287
1288 1288 %psearch -a _* list objects beginning with a single underscore"""
1289 1289 try:
1290 1290 parameter_s.encode('ascii')
1291 1291 except UnicodeEncodeError:
1292 1292 print 'Python identifiers can only contain ascii characters.'
1293 1293 return
1294 1294
1295 1295 # default namespaces to be searched
1296 1296 def_search = ['user_local', 'user_global', 'builtin']
1297 1297
1298 1298 # Process options/args
1299 1299 opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True)
1300 1300 opt = opts.get
1301 1301 shell = self.shell
1302 1302 psearch = shell.inspector.psearch
1303 1303
1304 1304 # select case options
1305 1305 if opts.has_key('i'):
1306 1306 ignore_case = True
1307 1307 elif opts.has_key('c'):
1308 1308 ignore_case = False
1309 1309 else:
1310 1310 ignore_case = not shell.wildcards_case_sensitive
1311 1311
1312 1312 # Build list of namespaces to search from user options
1313 1313 def_search.extend(opt('s',[]))
1314 1314 ns_exclude = ns_exclude=opt('e',[])
1315 1315 ns_search = [nm for nm in def_search if nm not in ns_exclude]
1316 1316
1317 1317 # Call the actual search
1318 1318 try:
1319 1319 psearch(args,shell.ns_table,ns_search,
1320 1320 show_all=opt('a'),ignore_case=ignore_case)
1321 1321 except:
1322 1322 shell.showtraceback()
1323 1323
1324 1324 @skip_doctest
1325 1325 @line_magic
1326 1326 def who_ls(self, parameter_s=''):
1327 1327 """Return a sorted list of all interactive variables.
1328 1328
1329 1329 If arguments are given, only variables of types matching these
1330 1330 arguments are returned.
1331 1331
1332 1332 Examples
1333 1333 --------
1334 1334
1335 1335 Define two variables and list them with who_ls::
1336 1336
1337 1337 In [1]: alpha = 123
1338 1338
1339 1339 In [2]: beta = 'test'
1340 1340
1341 1341 In [3]: %who_ls
1342 1342 Out[3]: ['alpha', 'beta']
1343 1343
1344 1344 In [4]: %who_ls int
1345 1345 Out[4]: ['alpha']
1346 1346
1347 1347 In [5]: %who_ls str
1348 1348 Out[5]: ['beta']
1349 1349 """
1350 1350
1351 1351 user_ns = self.shell.user_ns
1352 1352 user_ns_hidden = self.shell.user_ns_hidden
1353 1353 out = [ i for i in user_ns
1354 1354 if not i.startswith('_') \
1355 1355 and not i in user_ns_hidden ]
1356 1356
1357 1357 typelist = parameter_s.split()
1358 1358 if typelist:
1359 1359 typeset = set(typelist)
1360 1360 out = [i for i in out if type(user_ns[i]).__name__ in typeset]
1361 1361
1362 1362 out.sort()
1363 1363 return out
1364 1364
1365 1365 @skip_doctest
1366 1366 @line_magic
1367 1367 def who(self, parameter_s=''):
1368 1368 """Print all interactive variables, with some minimal formatting.
1369 1369
1370 1370 If any arguments are given, only variables whose type matches one of
1371 1371 these are printed. For example::
1372 1372
1373 1373 %who function str
1374 1374
1375 1375 will only list functions and strings, excluding all other types of
1376 1376 variables. To find the proper type names, simply use type(var) at a
1377 1377 command line to see how python prints type names. For example:
1378 1378
1379 1379 ::
1380 1380
1381 1381 In [1]: type('hello')\\
1382 1382 Out[1]: <type 'str'>
1383 1383
1384 1384 indicates that the type name for strings is 'str'.
1385 1385
1386 1386 ``%who`` always excludes executed names loaded through your configuration
1387 1387 file and things which are internal to IPython.
1388 1388
1389 1389 This is deliberate, as typically you may load many modules and the
1390 1390 purpose of %who is to show you only what you've manually defined.
1391 1391
1392 1392 Examples
1393 1393 --------
1394 1394
1395 1395 Define two variables and list them with who::
1396 1396
1397 1397 In [1]: alpha = 123
1398 1398
1399 1399 In [2]: beta = 'test'
1400 1400
1401 1401 In [3]: %who
1402 1402 alpha beta
1403 1403
1404 1404 In [4]: %who int
1405 1405 alpha
1406 1406
1407 1407 In [5]: %who str
1408 1408 beta
1409 1409 """
1410 1410
1411 1411 varlist = self.who_ls(parameter_s)
1412 1412 if not varlist:
1413 1413 if parameter_s:
1414 1414 print 'No variables match your requested type.'
1415 1415 else:
1416 1416 print 'Interactive namespace is empty.'
1417 1417 return
1418 1418
1419 1419 # if we have variables, move on...
1420 1420 count = 0
1421 1421 for i in varlist:
1422 1422 print i+'\t',
1423 1423 count += 1
1424 1424 if count > 8:
1425 1425 count = 0
1426 1426 print
1427 1427 print
1428 1428
1429 1429 @skip_doctest
1430 1430 @line_magic
1431 1431 def whos(self, parameter_s=''):
1432 1432 """Like %who, but gives some extra information about each variable.
1433 1433
1434 1434 The same type filtering of %who can be applied here.
1435 1435
1436 1436 For all variables, the type is printed. Additionally it prints:
1437 1437
1438 1438 - For {},[],(): their length.
1439 1439
1440 1440 - For numpy arrays, a summary with shape, number of
1441 1441 elements, typecode and size in memory.
1442 1442
1443 1443 - Everything else: a string representation, snipping their middle if
1444 1444 too long.
1445 1445
1446 1446 Examples
1447 1447 --------
1448 1448
1449 1449 Define two variables and list them with whos::
1450 1450
1451 1451 In [1]: alpha = 123
1452 1452
1453 1453 In [2]: beta = 'test'
1454 1454
1455 1455 In [3]: %whos
1456 1456 Variable Type Data/Info
1457 1457 --------------------------------
1458 1458 alpha int 123
1459 1459 beta str test
1460 1460 """
1461 1461
1462 1462 varnames = self.who_ls(parameter_s)
1463 1463 if not varnames:
1464 1464 if parameter_s:
1465 1465 print 'No variables match your requested type.'
1466 1466 else:
1467 1467 print 'Interactive namespace is empty.'
1468 1468 return
1469 1469
1470 1470 # if we have variables, move on...
1471 1471
1472 1472 # for these types, show len() instead of data:
1473 1473 seq_types = ['dict', 'list', 'tuple']
1474 1474
1475 1475 # for numpy arrays, display summary info
1476 1476 ndarray_type = None
1477 1477 if 'numpy' in sys.modules:
1478 1478 try:
1479 1479 from numpy import ndarray
1480 1480 except ImportError:
1481 1481 pass
1482 1482 else:
1483 1483 ndarray_type = ndarray.__name__
1484 1484
1485 1485 # Find all variable names and types so we can figure out column sizes
1486 1486 def get_vars(i):
1487 1487 return self.shell.user_ns[i]
1488 1488
1489 1489 # some types are well known and can be shorter
1490 1490 abbrevs = {'IPython.core.macro.Macro' : 'Macro'}
1491 1491 def type_name(v):
1492 1492 tn = type(v).__name__
1493 1493 return abbrevs.get(tn,tn)
1494 1494
1495 1495 varlist = map(get_vars,varnames)
1496 1496
1497 1497 typelist = []
1498 1498 for vv in varlist:
1499 1499 tt = type_name(vv)
1500 1500
1501 1501 if tt=='instance':
1502 1502 typelist.append( abbrevs.get(str(vv.__class__),
1503 1503 str(vv.__class__)))
1504 1504 else:
1505 1505 typelist.append(tt)
1506 1506
1507 1507 # column labels and # of spaces as separator
1508 1508 varlabel = 'Variable'
1509 1509 typelabel = 'Type'
1510 1510 datalabel = 'Data/Info'
1511 1511 colsep = 3
1512 1512 # variable format strings
1513 1513 vformat = "{0:<{varwidth}}{1:<{typewidth}}"
1514 1514 aformat = "%s: %s elems, type `%s`, %s bytes"
1515 1515 # find the size of the columns to format the output nicely
1516 1516 varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep
1517 1517 typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep
1518 1518 # table header
1519 1519 print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \
1520 1520 ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1)
1521 1521 # and the table itself
1522 1522 kb = 1024
1523 1523 Mb = 1048576 # kb**2
1524 1524 for vname,var,vtype in zip(varnames,varlist,typelist):
1525 1525 print vformat.format(vname, vtype, varwidth=varwidth, typewidth=typewidth),
1526 1526 if vtype in seq_types:
1527 1527 print "n="+str(len(var))
1528 1528 elif vtype == ndarray_type:
1529 1529 vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1]
1530 1530 if vtype==ndarray_type:
1531 1531 # numpy
1532 1532 vsize = var.size
1533 1533 vbytes = vsize*var.itemsize
1534 1534 vdtype = var.dtype
1535 1535
1536 1536 if vbytes < 100000:
1537 1537 print aformat % (vshape,vsize,vdtype,vbytes)
1538 1538 else:
1539 1539 print aformat % (vshape,vsize,vdtype,vbytes),
1540 1540 if vbytes < Mb:
1541 1541 print '(%s kb)' % (vbytes/kb,)
1542 1542 else:
1543 1543 print '(%s Mb)' % (vbytes/Mb,)
1544 1544 else:
1545 1545 try:
1546 1546 vstr = str(var)
1547 1547 except UnicodeEncodeError:
1548 1548 vstr = unicode(var).encode(DEFAULT_ENCODING,
1549 1549 'backslashreplace')
1550 1550 except:
1551 1551 vstr = "<object with id %d (str() failed)>" % id(var)
1552 1552 vstr = vstr.replace('\n','\\n')
1553 1553 if len(vstr) < 50:
1554 1554 print vstr
1555 1555 else:
1556 1556 print vstr[:25] + "<...>" + vstr[-25:]
1557 1557
1558 1558 @line_magic
1559 1559 def reset(self, parameter_s=''):
1560 1560 """Resets the namespace by removing all names defined by the user, if
1561 1561 called without arguments, or by removing some types of objects, such
1562 1562 as everything currently in IPython's In[] and Out[] containers (see
1563 1563 the parameters for details).
1564 1564
1565 1565 Parameters
1566 1566 ----------
1567 1567 -f : force reset without asking for confirmation.
1568 1568
1569 1569 -s : 'Soft' reset: Only clears your namespace, leaving history intact.
1570 1570 References to objects may be kept. By default (without this option),
1571 1571 we do a 'hard' reset, giving you a new session and removing all
1572 1572 references to objects from the current session.
1573 1573
1574 1574 in : reset input history
1575 1575
1576 1576 out : reset output history
1577 1577
1578 1578 dhist : reset directory history
1579 1579
1580 1580 array : reset only variables that are NumPy arrays
1581 1581
1582 1582 See Also
1583 1583 --------
1584 1584 magic_reset_selective : invoked as ``%reset_selective``
1585 1585
1586 1586 Examples
1587 1587 --------
1588 1588 ::
1589 1589
1590 1590 In [6]: a = 1
1591 1591
1592 1592 In [7]: a
1593 1593 Out[7]: 1
1594 1594
1595 1595 In [8]: 'a' in _ip.user_ns
1596 1596 Out[8]: True
1597 1597
1598 1598 In [9]: %reset -f
1599 1599
1600 1600 In [1]: 'a' in _ip.user_ns
1601 1601 Out[1]: False
1602 1602
1603 1603 In [2]: %reset -f in
1604 1604 Flushing input history
1605 1605
1606 1606 In [3]: %reset -f dhist in
1607 1607 Flushing directory history
1608 1608 Flushing input history
1609 1609
1610 1610 Notes
1611 1611 -----
1612 1612 Calling this magic from clients that do not implement standard input,
1613 1613 such as the ipython notebook interface, will reset the namespace
1614 1614 without confirmation.
1615 1615 """
1616 1616 opts, args = self.parse_options(parameter_s,'sf', mode='list')
1617 1617 if 'f' in opts:
1618 1618 ans = True
1619 1619 else:
1620 1620 try:
1621 1621 ans = self.shell.ask_yes_no(
1622 1622 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ", default='n')
1623 1623 except StdinNotImplementedError:
1624 1624 ans = True
1625 1625 if not ans:
1626 1626 print 'Nothing done.'
1627 1627 return
1628 1628
1629 1629 if 's' in opts: # Soft reset
1630 1630 user_ns = self.shell.user_ns
1631 1631 for i in self.magic_who_ls():
1632 1632 del(user_ns[i])
1633 1633 elif len(args) == 0: # Hard reset
1634 1634 self.shell.reset(new_session = False)
1635 1635
1636 1636 # reset in/out/dhist/array: previously extensinions/clearcmd.py
1637 1637 ip = self.shell
1638 1638 user_ns = self.shell.user_ns # local lookup, heavily used
1639 1639
1640 1640 for target in args:
1641 1641 target = target.lower() # make matches case insensitive
1642 1642 if target == 'out':
1643 1643 print "Flushing output cache (%d entries)" % len(user_ns['_oh'])
1644 1644 self.shell.displayhook.flush()
1645 1645
1646 1646 elif target == 'in':
1647 1647 print "Flushing input history"
1648 1648 pc = self.shell.displayhook.prompt_count + 1
1649 1649 for n in range(1, pc):
1650 1650 key = '_i'+repr(n)
1651 1651 user_ns.pop(key,None)
1652 1652 user_ns.update(dict(_i=u'',_ii=u'',_iii=u''))
1653 1653 hm = ip.history_manager
1654 1654 # don't delete these, as %save and %macro depending on the length
1655 1655 # of these lists to be preserved
1656 1656 hm.input_hist_parsed[:] = [''] * pc
1657 1657 hm.input_hist_raw[:] = [''] * pc
1658 1658 # hm has internal machinery for _i,_ii,_iii, clear it out
1659 1659 hm._i = hm._ii = hm._iii = hm._i00 = u''
1660 1660
1661 1661 elif target == 'array':
1662 1662 # Support cleaning up numpy arrays
1663 1663 try:
1664 1664 from numpy import ndarray
1665 1665 # This must be done with items and not iteritems because we're
1666 1666 # going to modify the dict in-place.
1667 1667 for x,val in user_ns.items():
1668 1668 if isinstance(val,ndarray):
1669 1669 del user_ns[x]
1670 1670 except ImportError:
1671 1671 print "reset array only works if Numpy is available."
1672 1672
1673 1673 elif target == 'dhist':
1674 1674 print "Flushing directory history"
1675 1675 del user_ns['_dh'][:]
1676 1676
1677 1677 else:
1678 1678 print "Don't know how to reset ",
1679 1679 print target + ", please run `%reset?` for details"
1680 1680
1681 1681 gc.collect()
1682 1682
1683 1683 @line_magic
1684 1684 def reset_selective(self, parameter_s=''):
1685 1685 """Resets the namespace by removing names defined by the user.
1686 1686
1687 1687 Input/Output history are left around in case you need them.
1688 1688
1689 1689 %reset_selective [-f] regex
1690 1690
1691 1691 No action is taken if regex is not included
1692 1692
1693 1693 Options
1694 1694 -f : force reset without asking for confirmation.
1695 1695
1696 1696 See Also
1697 1697 --------
1698 1698 magic_reset : invoked as ``%reset``
1699 1699
1700 1700 Examples
1701 1701 --------
1702 1702
1703 1703 We first fully reset the namespace so your output looks identical to
1704 1704 this example for pedagogical reasons; in practice you do not need a
1705 1705 full reset::
1706 1706
1707 1707 In [1]: %reset -f
1708 1708
1709 1709 Now, with a clean namespace we can make a few variables and use
1710 1710 ``%reset_selective`` to only delete names that match our regexp::
1711 1711
1712 1712 In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8
1713 1713
1714 1714 In [3]: who_ls
1715 1715 Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c']
1716 1716
1717 1717 In [4]: %reset_selective -f b[2-3]m
1718 1718
1719 1719 In [5]: who_ls
1720 1720 Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1721 1721
1722 1722 In [6]: %reset_selective -f d
1723 1723
1724 1724 In [7]: who_ls
1725 1725 Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c']
1726 1726
1727 1727 In [8]: %reset_selective -f c
1728 1728
1729 1729 In [9]: who_ls
1730 1730 Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m']
1731 1731
1732 1732 In [10]: %reset_selective -f b
1733 1733
1734 1734 In [11]: who_ls
1735 1735 Out[11]: ['a']
1736 1736
1737 1737 Notes
1738 1738 -----
1739 1739 Calling this magic from clients that do not implement standard input,
1740 1740 such as the ipython notebook interface, will reset the namespace
1741 1741 without confirmation.
1742 1742 """
1743 1743
1744 1744 opts, regex = self.parse_options(parameter_s,'f')
1745 1745
1746 1746 if opts.has_key('f'):
1747 1747 ans = True
1748 1748 else:
1749 1749 try:
1750 1750 ans = self.shell.ask_yes_no(
1751 1751 "Once deleted, variables cannot be recovered. Proceed (y/[n])? ",
1752 1752 default='n')
1753 1753 except StdinNotImplementedError:
1754 1754 ans = True
1755 1755 if not ans:
1756 1756 print 'Nothing done.'
1757 1757 return
1758 1758 user_ns = self.shell.user_ns
1759 1759 if not regex:
1760 1760 print 'No regex pattern specified. Nothing done.'
1761 1761 return
1762 1762 else:
1763 1763 try:
1764 1764 m = re.compile(regex)
1765 1765 except TypeError:
1766 1766 raise TypeError('regex must be a string or compiled pattern')
1767 1767 for i in self.magic_who_ls():
1768 1768 if m.search(i):
1769 1769 del(user_ns[i])
1770 1770
1771 1771 @line_magic
1772 1772 def xdel(self, parameter_s=''):
1773 1773 """Delete a variable, trying to clear it from anywhere that
1774 1774 IPython's machinery has references to it. By default, this uses
1775 1775 the identity of the named object in the user namespace to remove
1776 1776 references held under other names. The object is also removed
1777 1777 from the output history.
1778 1778
1779 1779 Options
1780 1780 -n : Delete the specified name from all namespaces, without
1781 1781 checking their identity.
1782 1782 """
1783 1783 opts, varname = self.parse_options(parameter_s,'n')
1784 1784 try:
1785 1785 self.shell.del_var(varname, ('n' in opts))
1786 1786 except (NameError, ValueError) as e:
1787 1787 print type(e).__name__ +": "+ str(e)
1788 1788
1789 1789
1790 1790 @register_magics
1791 1791 class ExecutionMagics(Magics):
1792 1792 """Magics related to code execution, debugging, profiling, etc.
1793 1793
1794 1794 """
1795 1795
1796 1796 def __init__(self, shell):
1797 1797 super(ExecutionMagics, self).__init__(shell)
1798 1798 if profile is None:
1799 1799 self.prun = self.profile_missing_notice
1800 1800 # Default execution function used to actually run user code.
1801 1801 self.default_runner = None
1802 1802
1803 1803 def profile_missing_notice(self, *args, **kwargs):
1804 1804 error("""\
1805 1805 The profile module could not be found. It has been removed from the standard
1806 1806 python packages because of its non-free license. To use profiling, install the
1807 1807 python-profiler package from non-free.""")
1808 1808
1809 1809 @skip_doctest
1810 1810 @line_magic
1811 1811 def prun(self, parameter_s='',user_mode=1,
1812 1812 opts=None,arg_lst=None,prog_ns=None):
1813 1813
1814 1814 """Run a statement through the python code profiler.
1815 1815
1816 1816 Usage:
1817 1817 %prun [options] statement
1818 1818
1819 1819 The given statement (which doesn't require quote marks) is run via the
1820 1820 python profiler in a manner similar to the profile.run() function.
1821 1821 Namespaces are internally managed to work correctly; profile.run
1822 1822 cannot be used in IPython because it makes certain assumptions about
1823 1823 namespaces which do not hold under IPython.
1824 1824
1825 1825 Options:
1826 1826
1827 1827 -l <limit>: you can place restrictions on what or how much of the
1828 1828 profile gets printed. The limit value can be:
1829 1829
1830 1830 * A string: only information for function names containing this string
1831 1831 is printed.
1832 1832
1833 1833 * An integer: only these many lines are printed.
1834 1834
1835 1835 * A float (between 0 and 1): this fraction of the report is printed
1836 1836 (for example, use a limit of 0.4 to see the topmost 40% only).
1837 1837
1838 1838 You can combine several limits with repeated use of the option. For
1839 1839 example, '-l __init__ -l 5' will print only the topmost 5 lines of
1840 1840 information about class constructors.
1841 1841
1842 1842 -r: return the pstats.Stats object generated by the profiling. This
1843 1843 object has all the information about the profile in it, and you can
1844 1844 later use it for further analysis or in other functions.
1845 1845
1846 1846 -s <key>: sort profile by given key. You can provide more than one key
1847 1847 by using the option several times: '-s key1 -s key2 -s key3...'. The
1848 1848 default sorting key is 'time'.
1849 1849
1850 1850 The following is copied verbatim from the profile documentation
1851 1851 referenced below:
1852 1852
1853 1853 When more than one key is provided, additional keys are used as
1854 1854 secondary criteria when the there is equality in all keys selected
1855 1855 before them.
1856 1856
1857 1857 Abbreviations can be used for any key names, as long as the
1858 1858 abbreviation is unambiguous. The following are the keys currently
1859 1859 defined:
1860 1860
1861 1861 Valid Arg Meaning
1862 1862 "calls" call count
1863 1863 "cumulative" cumulative time
1864 1864 "file" file name
1865 1865 "module" file name
1866 1866 "pcalls" primitive call count
1867 1867 "line" line number
1868 1868 "name" function name
1869 1869 "nfl" name/file/line
1870 1870 "stdname" standard name
1871 1871 "time" internal time
1872 1872
1873 1873 Note that all sorts on statistics are in descending order (placing
1874 1874 most time consuming items first), where as name, file, and line number
1875 1875 searches are in ascending order (i.e., alphabetical). The subtle
1876 1876 distinction between "nfl" and "stdname" is that the standard name is a
1877 1877 sort of the name as printed, which means that the embedded line
1878 1878 numbers get compared in an odd way. For example, lines 3, 20, and 40
1879 1879 would (if the file names were the same) appear in the string order
1880 1880 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
1881 1881 line numbers. In fact, sort_stats("nfl") is the same as
1882 1882 sort_stats("name", "file", "line").
1883 1883
1884 1884 -T <filename>: save profile results as shown on screen to a text
1885 1885 file. The profile is still shown on screen.
1886 1886
1887 1887 -D <filename>: save (via dump_stats) profile statistics to given
1888 1888 filename. This data is in a format understood by the pstats module, and
1889 1889 is generated by a call to the dump_stats() method of profile
1890 1890 objects. The profile is still shown on screen.
1891 1891
1892 1892 -q: suppress output to the pager. Best used with -T and/or -D above.
1893 1893
1894 1894 If you want to run complete programs under the profiler's control, use
1895 1895 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
1896 1896 contains profiler specific options as described here.
1897 1897
1898 1898 You can read the complete documentation for the profile module with::
1899 1899
1900 1900 In [1]: import profile; profile.help()
1901 1901 """
1902 1902
1903 1903 opts_def = Struct(D=[''],l=[],s=['time'],T=[''])
1904 1904
1905 1905 if user_mode: # regular user call
1906 1906 opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:q',
1907 1907 list_all=1, posix=False)
1908 1908 namespace = self.shell.user_ns
1909 1909 else: # called to run a program by %run -p
1910 1910 try:
1911 1911 filename = get_py_filename(arg_lst[0])
1912 1912 except IOError as e:
1913 1913 try:
1914 1914 msg = str(e)
1915 1915 except UnicodeError:
1916 1916 msg = e.message
1917 1917 error(msg)
1918 1918 return
1919 1919
1920 1920 arg_str = 'execfile(filename,prog_ns)'
1921 1921 namespace = {
1922 1922 'execfile': self.shell.safe_execfile,
1923 1923 'prog_ns': prog_ns,
1924 1924 'filename': filename
1925 1925 }
1926 1926
1927 1927 opts.merge(opts_def)
1928 1928
1929 1929 prof = profile.Profile()
1930 1930 try:
1931 1931 prof = prof.runctx(arg_str,namespace,namespace)
1932 1932 sys_exit = ''
1933 1933 except SystemExit:
1934 1934 sys_exit = """*** SystemExit exception caught in code being profiled."""
1935 1935
1936 1936 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
1937 1937
1938 1938 lims = opts.l
1939 1939 if lims:
1940 1940 lims = [] # rebuild lims with ints/floats/strings
1941 1941 for lim in opts.l:
1942 1942 try:
1943 1943 lims.append(int(lim))
1944 1944 except ValueError:
1945 1945 try:
1946 1946 lims.append(float(lim))
1947 1947 except ValueError:
1948 1948 lims.append(lim)
1949 1949
1950 1950 # Trap output.
1951 1951 stdout_trap = StringIO()
1952 1952
1953 1953 if hasattr(stats,'stream'):
1954 1954 # In newer versions of python, the stats object has a 'stream'
1955 1955 # attribute to write into.
1956 1956 stats.stream = stdout_trap
1957 1957 stats.print_stats(*lims)
1958 1958 else:
1959 1959 # For older versions, we manually redirect stdout during printing
1960 1960 sys_stdout = sys.stdout
1961 1961 try:
1962 1962 sys.stdout = stdout_trap
1963 1963 stats.print_stats(*lims)
1964 1964 finally:
1965 1965 sys.stdout = sys_stdout
1966 1966
1967 1967 output = stdout_trap.getvalue()
1968 1968 output = output.rstrip()
1969 1969
1970 1970 if 'q' not in opts:
1971 1971 page.page(output)
1972 1972 print sys_exit,
1973 1973
1974 1974 dump_file = opts.D[0]
1975 1975 text_file = opts.T[0]
1976 1976 if dump_file:
1977 1977 dump_file = unquote_filename(dump_file)
1978 1978 prof.dump_stats(dump_file)
1979 1979 print '\n*** Profile stats marshalled to file',\
1980 1980 `dump_file`+'.',sys_exit
1981 1981 if text_file:
1982 1982 text_file = unquote_filename(text_file)
1983 1983 pfile = open(text_file,'w')
1984 1984 pfile.write(output)
1985 1985 pfile.close()
1986 1986 print '\n*** Profile printout saved to text file',\
1987 1987 `text_file`+'.',sys_exit
1988 1988
1989 1989 if opts.has_key('r'):
1990 1990 return stats
1991 1991 else:
1992 1992 return None
1993 1993
1994 1994 @line_magic
1995 1995 def pdb(self, parameter_s=''):
1996 1996 """Control the automatic calling of the pdb interactive debugger.
1997 1997
1998 1998 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
1999 1999 argument it works as a toggle.
2000 2000
2001 2001 When an exception is triggered, IPython can optionally call the
2002 2002 interactive pdb debugger after the traceback printout. %pdb toggles
2003 2003 this feature on and off.
2004 2004
2005 2005 The initial state of this feature is set in your configuration
2006 2006 file (the option is ``InteractiveShell.pdb``).
2007 2007
2008 2008 If you want to just activate the debugger AFTER an exception has fired,
2009 2009 without having to type '%pdb on' and rerunning your code, you can use
2010 2010 the %debug magic."""
2011 2011
2012 2012 par = parameter_s.strip().lower()
2013 2013
2014 2014 if par:
2015 2015 try:
2016 2016 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
2017 2017 except KeyError:
2018 2018 print ('Incorrect argument. Use on/1, off/0, '
2019 2019 'or nothing for a toggle.')
2020 2020 return
2021 2021 else:
2022 2022 # toggle
2023 2023 new_pdb = not self.shell.call_pdb
2024 2024
2025 2025 # set on the shell
2026 2026 self.shell.call_pdb = new_pdb
2027 2027 print 'Automatic pdb calling has been turned',on_off(new_pdb)
2028 2028
2029 2029 @line_magic
2030 2030 def debug(self, parameter_s=''):
2031 2031 """Activate the interactive debugger in post-mortem mode.
2032 2032
2033 2033 If an exception has just occurred, this lets you inspect its stack
2034 2034 frames interactively. Note that this will always work only on the last
2035 2035 traceback that occurred, so you must call this quickly after an
2036 2036 exception that you wish to inspect has fired, because if another one
2037 2037 occurs, it clobbers the previous one.
2038 2038
2039 2039 If you want IPython to automatically do this on every exception, see
2040 2040 the %pdb magic for more details.
2041 2041 """
2042 2042 self.shell.debugger(force=True)
2043 2043
2044 2044 @line_magic
2045 2045 def tb(self, s):
2046 2046 """Print the last traceback with the currently active exception mode.
2047 2047
2048 2048 See %xmode for changing exception reporting modes."""
2049 2049 self.shell.showtraceback()
2050 2050
2051 2051 @skip_doctest
2052 2052 @line_magic
2053 2053 def run(self, parameter_s='', runner=None,
2054 2054 file_finder=get_py_filename):
2055 2055 """Run the named file inside IPython as a program.
2056 2056
2057 2057 Usage:\\
2058 2058 %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args]
2059 2059
2060 2060 Parameters after the filename are passed as command-line arguments to
2061 2061 the program (put in sys.argv). Then, control returns to IPython's
2062 2062 prompt.
2063 2063
2064 2064 This is similar to running at a system prompt:\\
2065 2065 $ python file args\\
2066 2066 but with the advantage of giving you IPython's tracebacks, and of
2067 2067 loading all variables into your interactive namespace for further use
2068 2068 (unless -p is used, see below).
2069 2069
2070 2070 The file is executed in a namespace initially consisting only of
2071 2071 __name__=='__main__' and sys.argv constructed as indicated. It thus
2072 2072 sees its environment as if it were being run as a stand-alone program
2073 2073 (except for sharing global objects such as previously imported
2074 2074 modules). But after execution, the IPython interactive namespace gets
2075 2075 updated with all variables defined in the program (except for __name__
2076 2076 and sys.argv). This allows for very convenient loading of code for
2077 2077 interactive work, while giving each program a 'clean sheet' to run in.
2078 2078
2079 2079 Options:
2080 2080
2081 2081 -n: __name__ is NOT set to '__main__', but to the running file's name
2082 2082 without extension (as python does under import). This allows running
2083 2083 scripts and reloading the definitions in them without calling code
2084 2084 protected by an ' if __name__ == "__main__" ' clause.
2085 2085
2086 2086 -i: run the file in IPython's namespace instead of an empty one. This
2087 2087 is useful if you are experimenting with code written in a text editor
2088 2088 which depends on variables defined interactively.
2089 2089
2090 2090 -e: ignore sys.exit() calls or SystemExit exceptions in the script
2091 2091 being run. This is particularly useful if IPython is being used to
2092 2092 run unittests, which always exit with a sys.exit() call. In such
2093 2093 cases you are interested in the output of the test results, not in
2094 2094 seeing a traceback of the unittest module.
2095 2095
2096 2096 -t: print timing information at the end of the run. IPython will give
2097 2097 you an estimated CPU time consumption for your script, which under
2098 2098 Unix uses the resource module to avoid the wraparound problems of
2099 2099 time.clock(). Under Unix, an estimate of time spent on system tasks
2100 2100 is also given (for Windows platforms this is reported as 0.0).
2101 2101
2102 2102 If -t is given, an additional -N<N> option can be given, where <N>
2103 2103 must be an integer indicating how many times you want the script to
2104 2104 run. The final timing report will include total and per run results.
2105 2105
2106 2106 For example (testing the script uniq_stable.py)::
2107 2107
2108 2108 In [1]: run -t uniq_stable
2109 2109
2110 2110 IPython CPU timings (estimated):\\
2111 2111 User : 0.19597 s.\\
2112 2112 System: 0.0 s.\\
2113 2113
2114 2114 In [2]: run -t -N5 uniq_stable
2115 2115
2116 2116 IPython CPU timings (estimated):\\
2117 2117 Total runs performed: 5\\
2118 2118 Times : Total Per run\\
2119 2119 User : 0.910862 s, 0.1821724 s.\\
2120 2120 System: 0.0 s, 0.0 s.
2121 2121
2122 2122 -d: run your program under the control of pdb, the Python debugger.
2123 2123 This allows you to execute your program step by step, watch variables,
2124 2124 etc. Internally, what IPython does is similar to calling:
2125 2125
2126 2126 pdb.run('execfile("YOURFILENAME")')
2127 2127
2128 2128 with a breakpoint set on line 1 of your file. You can change the line
2129 2129 number for this automatic breakpoint to be <N> by using the -bN option
2130 2130 (where N must be an integer). For example::
2131 2131
2132 2132 %run -d -b40 myscript
2133 2133
2134 2134 will set the first breakpoint at line 40 in myscript.py. Note that
2135 2135 the first breakpoint must be set on a line which actually does
2136 2136 something (not a comment or docstring) for it to stop execution.
2137 2137
2138 2138 When the pdb debugger starts, you will see a (Pdb) prompt. You must
2139 2139 first enter 'c' (without quotes) to start execution up to the first
2140 2140 breakpoint.
2141 2141
2142 2142 Entering 'help' gives information about the use of the debugger. You
2143 2143 can easily see pdb's full documentation with "import pdb;pdb.help()"
2144 2144 at a prompt.
2145 2145
2146 2146 -p: run program under the control of the Python profiler module (which
2147 2147 prints a detailed report of execution times, function calls, etc).
2148 2148
2149 2149 You can pass other options after -p which affect the behavior of the
2150 2150 profiler itself. See the docs for %prun for details.
2151 2151
2152 2152 In this mode, the program's variables do NOT propagate back to the
2153 2153 IPython interactive namespace (because they remain in the namespace
2154 2154 where the profiler executes them).
2155 2155
2156 2156 Internally this triggers a call to %prun, see its documentation for
2157 2157 details on the options available specifically for profiling.
2158 2158
2159 2159 There is one special usage for which the text above doesn't apply:
2160 2160 if the filename ends with .ipy, the file is run as ipython script,
2161 2161 just as if the commands were written on IPython prompt.
2162 2162
2163 2163 -m: specify module name to load instead of script path. Similar to
2164 2164 the -m option for the python interpreter. Use this option last if you
2165 2165 want to combine with other %run options. Unlike the python interpreter
2166 2166 only source modules are allowed no .pyc or .pyo files.
2167 2167 For example::
2168 2168
2169 2169 %run -m example
2170 2170
2171 2171 will run the example module.
2172 2172
2173 2173 """
2174 2174
2175 2175 # get arguments and set sys.argv for program to be run.
2176 2176 opts, arg_lst = self.parse_options(parameter_s, 'nidtN:b:pD:l:rs:T:em:',
2177 2177 mode='list', list_all=1)
2178 2178 if "m" in opts:
2179 2179 modulename = opts["m"][0]
2180 2180 modpath = find_mod(modulename)
2181 2181 if modpath is None:
2182 2182 warn('%r is not a valid modulename on sys.path'%modulename)
2183 2183 return
2184 2184 arg_lst = [modpath] + arg_lst
2185 2185 try:
2186 2186 filename = file_finder(arg_lst[0])
2187 2187 except IndexError:
2188 2188 warn('you must provide at least a filename.')
2189 2189 print '\n%run:\n', oinspect.getdoc(self.magic_run)
2190 2190 return
2191 2191 except IOError as e:
2192 2192 try:
2193 2193 msg = str(e)
2194 2194 except UnicodeError:
2195 2195 msg = e.message
2196 2196 error(msg)
2197 2197 return
2198 2198
2199 2199 if filename.lower().endswith('.ipy'):
2200 2200 self.shell.safe_execfile_ipy(filename)
2201 2201 return
2202 2202
2203 2203 # Control the response to exit() calls made by the script being run
2204 2204 exit_ignore = 'e' in opts
2205 2205
2206 2206 # Make sure that the running script gets a proper sys.argv as if it
2207 2207 # were run from a system shell.
2208 2208 save_argv = sys.argv # save it for later restoring
2209 2209
2210 2210 # simulate shell expansion on arguments, at least tilde expansion
2211 2211 args = [ os.path.expanduser(a) for a in arg_lst[1:] ]
2212 2212
2213 2213 sys.argv = [filename] + args # put in the proper filename
2214 2214 # protect sys.argv from potential unicode strings on Python 2:
2215 2215 if not py3compat.PY3:
2216 2216 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
2217 2217
2218 2218 if 'i' in opts:
2219 2219 # Run in user's interactive namespace
2220 2220 prog_ns = self.shell.user_ns
2221 2221 __name__save = self.shell.user_ns['__name__']
2222 2222 prog_ns['__name__'] = '__main__'
2223 2223 main_mod = self.shell.new_main_mod(prog_ns)
2224 2224 else:
2225 2225 # Run in a fresh, empty namespace
2226 2226 if 'n' in opts:
2227 2227 name = os.path.splitext(os.path.basename(filename))[0]
2228 2228 else:
2229 2229 name = '__main__'
2230 2230
2231 2231 main_mod = self.shell.new_main_mod()
2232 2232 prog_ns = main_mod.__dict__
2233 2233 prog_ns['__name__'] = name
2234 2234
2235 2235 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
2236 2236 # set the __file__ global in the script's namespace
2237 2237 prog_ns['__file__'] = filename
2238 2238
2239 2239 # pickle fix. See interactiveshell for an explanation. But we need to make sure
2240 2240 # that, if we overwrite __main__, we replace it at the end
2241 2241 main_mod_name = prog_ns['__name__']
2242 2242
2243 2243 if main_mod_name == '__main__':
2244 2244 restore_main = sys.modules['__main__']
2245 2245 else:
2246 2246 restore_main = False
2247 2247
2248 2248 # This needs to be undone at the end to prevent holding references to
2249 2249 # every single object ever created.
2250 2250 sys.modules[main_mod_name] = main_mod
2251 2251
2252 2252 try:
2253 2253 stats = None
2254 2254 with self.shell.readline_no_record:
2255 2255 if 'p' in opts:
2256 2256 stats = self.prun('', 0, opts, arg_lst, prog_ns)
2257 2257 else:
2258 2258 if 'd' in opts:
2259 2259 deb = debugger.Pdb(self.shell.colors)
2260 2260 # reset Breakpoint state, which is moronically kept
2261 2261 # in a class
2262 2262 bdb.Breakpoint.next = 1
2263 2263 bdb.Breakpoint.bplist = {}
2264 2264 bdb.Breakpoint.bpbynumber = [None]
2265 2265 # Set an initial breakpoint to stop execution
2266 2266 maxtries = 10
2267 2267 bp = int(opts.get('b', [1])[0])
2268 2268 checkline = deb.checkline(filename, bp)
2269 2269 if not checkline:
2270 2270 for bp in range(bp + 1, bp + maxtries + 1):
2271 2271 if deb.checkline(filename, bp):
2272 2272 break
2273 2273 else:
2274 2274 msg = ("\nI failed to find a valid line to set "
2275 2275 "a breakpoint\n"
2276 2276 "after trying up to line: %s.\n"
2277 2277 "Please set a valid breakpoint manually "
2278 2278 "with the -b option." % bp)
2279 2279 error(msg)
2280 2280 return
2281 2281 # if we find a good linenumber, set the breakpoint
2282 2282 deb.do_break('%s:%s' % (filename, bp))
2283 2283 # Start file run
2284 2284 print "NOTE: Enter 'c' at the",
2285 2285 print "%s prompt to start your script." % deb.prompt
2286 2286 ns = {'execfile': py3compat.execfile, 'prog_ns': prog_ns}
2287 2287 try:
2288 2288 deb.run('execfile("%s", prog_ns)' % filename, ns)
2289 2289
2290 2290 except:
2291 2291 etype, value, tb = sys.exc_info()
2292 2292 # Skip three frames in the traceback: the %run one,
2293 2293 # one inside bdb.py, and the command-line typed by the
2294 2294 # user (run by exec in pdb itself).
2295 2295 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
2296 2296 else:
2297 2297 if runner is None:
2298 2298 runner = self.default_runner
2299 2299 if runner is None:
2300 2300 runner = self.shell.safe_execfile
2301 2301 if 't' in opts:
2302 2302 # timed execution
2303 2303 try:
2304 2304 nruns = int(opts['N'][0])
2305 2305 if nruns < 1:
2306 2306 error('Number of runs must be >=1')
2307 2307 return
2308 2308 except (KeyError):
2309 2309 nruns = 1
2310 2310 twall0 = time.time()
2311 2311 if nruns == 1:
2312 2312 t0 = clock2()
2313 2313 runner(filename, prog_ns, prog_ns,
2314 2314 exit_ignore=exit_ignore)
2315 2315 t1 = clock2()
2316 2316 t_usr = t1[0] - t0[0]
2317 2317 t_sys = t1[1] - t0[1]
2318 2318 print "\nIPython CPU timings (estimated):"
2319 2319 print " User : %10.2f s." % t_usr
2320 2320 print " System : %10.2f s." % t_sys
2321 2321 else:
2322 2322 runs = range(nruns)
2323 2323 t0 = clock2()
2324 2324 for nr in runs:
2325 2325 runner(filename, prog_ns, prog_ns,
2326 2326 exit_ignore=exit_ignore)
2327 2327 t1 = clock2()
2328 2328 t_usr = t1[0] - t0[0]
2329 2329 t_sys = t1[1] - t0[1]
2330 2330 print "\nIPython CPU timings (estimated):"
2331 2331 print "Total runs performed:", nruns
2332 2332 print " Times : %10.2f %10.2f" % ('Total', 'Per run')
2333 2333 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
2334 2334 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
2335 2335 twall1 = time.time()
2336 2336 print "Wall time: %10.2f s." % (twall1 - twall0)
2337 2337
2338 2338 else:
2339 2339 # regular execution
2340 2340 runner(filename, prog_ns, prog_ns, exit_ignore=exit_ignore)
2341 2341
2342 2342 if 'i' in opts:
2343 2343 self.shell.user_ns['__name__'] = __name__save
2344 2344 else:
2345 2345 # The shell MUST hold a reference to prog_ns so after %run
2346 2346 # exits, the python deletion mechanism doesn't zero it out
2347 2347 # (leaving dangling references).
2348 2348 self.shell.cache_main_mod(prog_ns, filename)
2349 2349 # update IPython interactive namespace
2350 2350
2351 2351 # Some forms of read errors on the file may mean the
2352 2352 # __name__ key was never set; using pop we don't have to
2353 2353 # worry about a possible KeyError.
2354 2354 prog_ns.pop('__name__', None)
2355 2355
2356 2356 self.shell.user_ns.update(prog_ns)
2357 2357 finally:
2358 2358 # It's a bit of a mystery why, but __builtins__ can change from
2359 2359 # being a module to becoming a dict missing some key data after
2360 2360 # %run. As best I can see, this is NOT something IPython is doing
2361 2361 # at all, and similar problems have been reported before:
2362 2362 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
2363 2363 # Since this seems to be done by the interpreter itself, the best
2364 2364 # we can do is to at least restore __builtins__ for the user on
2365 2365 # exit.
2366 2366 self.shell.user_ns['__builtins__'] = builtin_mod
2367 2367
2368 2368 # Ensure key global structures are restored
2369 2369 sys.argv = save_argv
2370 2370 if restore_main:
2371 2371 sys.modules['__main__'] = restore_main
2372 2372 else:
2373 2373 # Remove from sys.modules the reference to main_mod we'd
2374 2374 # added. Otherwise it will trap references to objects
2375 2375 # contained therein.
2376 2376 del sys.modules[main_mod_name]
2377 2377
2378 2378 return stats
2379 2379
2380 2380 @skip_doctest
2381 2381 @line_magic
2382 2382 def timeit(self, parameter_s=''):
2383 2383 """Time execution of a Python statement or expression
2384 2384
2385 2385 Usage:\\
2386 2386 %timeit [-n<N> -r<R> [-t|-c]] statement
2387 2387
2388 2388 Time execution of a Python statement or expression using the timeit
2389 2389 module.
2390 2390
2391 2391 Options:
2392 2392 -n<N>: execute the given statement <N> times in a loop. If this value
2393 2393 is not given, a fitting value is chosen.
2394 2394
2395 2395 -r<R>: repeat the loop iteration <R> times and take the best result.
2396 2396 Default: 3
2397 2397
2398 2398 -t: use time.time to measure the time, which is the default on Unix.
2399 2399 This function measures wall time.
2400 2400
2401 2401 -c: use time.clock to measure the time, which is the default on
2402 2402 Windows and measures wall time. On Unix, resource.getrusage is used
2403 2403 instead and returns the CPU user time.
2404 2404
2405 2405 -p<P>: use a precision of <P> digits to display the timing result.
2406 2406 Default: 3
2407 2407
2408 2408
2409 2409 Examples
2410 2410 --------
2411 2411 ::
2412 2412
2413 2413 In [1]: %timeit pass
2414 2414 10000000 loops, best of 3: 53.3 ns per loop
2415 2415
2416 2416 In [2]: u = None
2417 2417
2418 2418 In [3]: %timeit u is None
2419 2419 10000000 loops, best of 3: 184 ns per loop
2420 2420
2421 2421 In [4]: %timeit -r 4 u == None
2422 2422 1000000 loops, best of 4: 242 ns per loop
2423 2423
2424 2424 In [5]: import time
2425 2425
2426 2426 In [6]: %timeit -n1 time.sleep(2)
2427 2427 1 loops, best of 3: 2 s per loop
2428 2428
2429 2429
2430 2430 The times reported by %timeit will be slightly higher than those
2431 2431 reported by the timeit.py script when variables are accessed. This is
2432 2432 due to the fact that %timeit executes the statement in the namespace
2433 2433 of the shell, compared with timeit.py, which uses a single setup
2434 2434 statement to import function or create variables. Generally, the bias
2435 2435 does not matter as long as results from timeit.py are not mixed with
2436 2436 those from %timeit."""
2437 2437
2438 2438 import timeit
2439 2439 import math
2440 2440
2441 2441 # XXX: Unfortunately the unicode 'micro' symbol can cause problems in
2442 2442 # certain terminals. Until we figure out a robust way of
2443 2443 # auto-detecting if the terminal can deal with it, use plain 'us' for
2444 2444 # microseconds. I am really NOT happy about disabling the proper
2445 2445 # 'micro' prefix, but crashing is worse... If anyone knows what the
2446 2446 # right solution for this is, I'm all ears...
2447 2447 #
2448 2448 # Note: using
2449 2449 #
2450 2450 # s = u'\xb5'
2451 2451 # s.encode(sys.getdefaultencoding())
2452 2452 #
2453 2453 # is not sufficient, as I've seen terminals where that fails but
2454 2454 # print s
2455 2455 #
2456 2456 # succeeds
2457 2457 #
2458 2458 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
2459 2459
2460 2460 #units = [u"s", u"ms",u'\xb5',"ns"]
2461 2461 units = [u"s", u"ms",u'us',"ns"]
2462 2462
2463 2463 scaling = [1, 1e3, 1e6, 1e9]
2464 2464
2465 2465 opts, stmt = self.parse_options(parameter_s,'n:r:tcp:',
2466 2466 posix=False, strict=False)
2467 2467 if stmt == "":
2468 2468 return
2469 2469 timefunc = timeit.default_timer
2470 2470 number = int(getattr(opts, "n", 0))
2471 2471 repeat = int(getattr(opts, "r", timeit.default_repeat))
2472 2472 precision = int(getattr(opts, "p", 3))
2473 2473 if hasattr(opts, "t"):
2474 2474 timefunc = time.time
2475 2475 if hasattr(opts, "c"):
2476 2476 timefunc = clock
2477 2477
2478 2478 timer = timeit.Timer(timer=timefunc)
2479 2479 # this code has tight coupling to the inner workings of timeit.Timer,
2480 2480 # but is there a better way to achieve that the code stmt has access
2481 2481 # to the shell namespace?
2482 2482
2483 2483 src = timeit.template % {'stmt': timeit.reindent(stmt, 8),
2484 2484 'setup': "pass"}
2485 2485 # Track compilation time so it can be reported if too long
2486 2486 # Minimum time above which compilation time will be reported
2487 2487 tc_min = 0.1
2488 2488
2489 2489 t0 = clock()
2490 2490 code = compile(src, "<magic-timeit>", "exec")
2491 2491 tc = clock()-t0
2492 2492
2493 2493 ns = {}
2494 2494 exec code in self.shell.user_ns, ns
2495 2495 timer.inner = ns["inner"]
2496 2496
2497 2497 if number == 0:
2498 2498 # determine number so that 0.2 <= total time < 2.0
2499 2499 number = 1
2500 2500 for i in range(1, 10):
2501 2501 if timer.timeit(number) >= 0.2:
2502 2502 break
2503 2503 number *= 10
2504 2504
2505 2505 best = min(timer.repeat(repeat, number)) / number
2506 2506
2507 2507 if best > 0.0 and best < 1000.0:
2508 2508 order = min(-int(math.floor(math.log10(best)) // 3), 3)
2509 2509 elif best >= 1000.0:
2510 2510 order = 0
2511 2511 else:
2512 2512 order = 3
2513 2513 print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat,
2514 2514 precision,
2515 2515 best * scaling[order],
2516 2516 units[order])
2517 2517 if tc > tc_min:
2518 2518 print "Compiler time: %.2f s" % tc
2519 2519
2520 2520 @cell_magic('timeit')
2521 2521 def cell_timeit(self, line, cell):
2522 2522 """Time execution of a Python cell."""
2523 2523 raise NotImplementedError
2524 2524
2525 2525 @skip_doctest
2526 2526 @needs_local_scope
2527 2527 @line_magic
2528 2528 def time(self,parameter_s, user_locals):
2529 2529 """Time execution of a Python statement or expression.
2530 2530
2531 2531 The CPU and wall clock times are printed, and the value of the
2532 2532 expression (if any) is returned. Note that under Win32, system time
2533 2533 is always reported as 0, since it can not be measured.
2534 2534
2535 2535 This function provides very basic timing functionality. In Python
2536 2536 2.3, the timeit module offers more control and sophistication, so this
2537 2537 could be rewritten to use it (patches welcome).
2538 2538
2539 2539 Examples
2540 2540 --------
2541 2541 ::
2542 2542
2543 2543 In [1]: time 2**128
2544 2544 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2545 2545 Wall time: 0.00
2546 2546 Out[1]: 340282366920938463463374607431768211456L
2547 2547
2548 2548 In [2]: n = 1000000
2549 2549
2550 2550 In [3]: time sum(range(n))
2551 2551 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
2552 2552 Wall time: 1.37
2553 2553 Out[3]: 499999500000L
2554 2554
2555 2555 In [4]: time print 'hello world'
2556 2556 hello world
2557 2557 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2558 2558 Wall time: 0.00
2559 2559
2560 2560 Note that the time needed by Python to compile the given expression
2561 2561 will be reported if it is more than 0.1s. In this example, the
2562 2562 actual exponentiation is done by Python at compilation time, so while
2563 2563 the expression can take a noticeable amount of time to compute, that
2564 2564 time is purely due to the compilation:
2565 2565
2566 2566 In [5]: time 3**9999;
2567 2567 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2568 2568 Wall time: 0.00 s
2569 2569
2570 2570 In [6]: time 3**999999;
2571 2571 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
2572 2572 Wall time: 0.00 s
2573 2573 Compiler : 0.78 s
2574 2574 """
2575 2575
2576 2576 # fail immediately if the given expression can't be compiled
2577 2577
2578 2578 expr = self.shell.prefilter(parameter_s,False)
2579 2579
2580 2580 # Minimum time above which compilation time will be reported
2581 2581 tc_min = 0.1
2582 2582
2583 2583 try:
2584 2584 mode = 'eval'
2585 2585 t0 = clock()
2586 2586 code = compile(expr,'<timed eval>',mode)
2587 2587 tc = clock()-t0
2588 2588 except SyntaxError:
2589 2589 mode = 'exec'
2590 2590 t0 = clock()
2591 2591 code = compile(expr,'<timed exec>',mode)
2592 2592 tc = clock()-t0
2593 2593 # skew measurement as little as possible
2594 2594 glob = self.shell.user_ns
2595 2595 wtime = time.time
2596 2596 # time execution
2597 2597 wall_st = wtime()
2598 2598 if mode=='eval':
2599 2599 st = clock2()
2600 2600 out = eval(code, glob, user_locals)
2601 2601 end = clock2()
2602 2602 else:
2603 2603 st = clock2()
2604 2604 exec code in glob, user_locals
2605 2605 end = clock2()
2606 2606 out = None
2607 2607 wall_end = wtime()
2608 2608 # Compute actual times and report
2609 2609 wall_time = wall_end-wall_st
2610 2610 cpu_user = end[0]-st[0]
2611 2611 cpu_sys = end[1]-st[1]
2612 2612 cpu_tot = cpu_user+cpu_sys
2613 2613 print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \
2614 2614 (cpu_user,cpu_sys,cpu_tot)
2615 2615 print "Wall time: %.2f s" % wall_time
2616 2616 if tc > tc_min:
2617 2617 print "Compiler : %.2f s" % tc
2618 2618 return out
2619 2619
2620 2620 @skip_doctest
2621 2621 @line_magic
2622 2622 def macro(self, parameter_s=''):
2623 2623 """Define a macro for future re-execution. It accepts ranges of history,
2624 2624 filenames or string objects.
2625 2625
2626 2626 Usage:\\
2627 2627 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
2628 2628
2629 2629 Options:
2630 2630
2631 2631 -r: use 'raw' input. By default, the 'processed' history is used,
2632 2632 so that magics are loaded in their transformed version to valid
2633 2633 Python. If this option is given, the raw input as typed as the
2634 2634 command line is used instead.
2635 2635
2636 2636 This will define a global variable called `name` which is a string
2637 2637 made of joining the slices and lines you specify (n1,n2,... numbers
2638 2638 above) from your input history into a single string. This variable
2639 2639 acts like an automatic function which re-executes those lines as if
2640 2640 you had typed them. You just type 'name' at the prompt and the code
2641 2641 executes.
2642 2642
2643 2643 The syntax for indicating input ranges is described in %history.
2644 2644
2645 2645 Note: as a 'hidden' feature, you can also use traditional python slice
2646 2646 notation, where N:M means numbers N through M-1.
2647 2647
2648 2648 For example, if your history contains (%hist prints it)::
2649 2649
2650 2650 44: x=1
2651 2651 45: y=3
2652 2652 46: z=x+y
2653 2653 47: print x
2654 2654 48: a=5
2655 2655 49: print 'x',x,'y',y
2656 2656
2657 2657 you can create a macro with lines 44 through 47 (included) and line 49
2658 2658 called my_macro with::
2659 2659
2660 2660 In [55]: %macro my_macro 44-47 49
2661 2661
2662 2662 Now, typing `my_macro` (without quotes) will re-execute all this code
2663 2663 in one pass.
2664 2664
2665 2665 You don't need to give the line-numbers in order, and any given line
2666 2666 number can appear multiple times. You can assemble macros with any
2667 2667 lines from your input history in any order.
2668 2668
2669 2669 The macro is a simple object which holds its value in an attribute,
2670 2670 but IPython's display system checks for macros and executes them as
2671 2671 code instead of printing them when you type their name.
2672 2672
2673 2673 You can view a macro's contents by explicitly printing it with::
2674 2674
2675 2675 print macro_name
2676 2676
2677 2677 """
2678 2678 opts,args = self.parse_options(parameter_s,'r',mode='list')
2679 2679 if not args: # List existing macros
2680 2680 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
2681 2681 isinstance(v, Macro))
2682 2682 if len(args) == 1:
2683 2683 raise UsageError(
2684 2684 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
2685 2685 name, codefrom = args[0], " ".join(args[1:])
2686 2686
2687 2687 #print 'rng',ranges # dbg
2688 2688 try:
2689 2689 lines = self.shell.find_user_code(codefrom, 'r' in opts)
2690 2690 except (ValueError, TypeError) as e:
2691 2691 print e.args[0]
2692 2692 return
2693 2693 macro = Macro(lines)
2694 2694 self.shell.define_macro(name, macro)
2695 2695 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
2696 2696 print '=== Macro contents: ==='
2697 2697 print macro,
2698 2698
2699 2699
2700 2700 @register_magics
2701 2701 class AutoMagics(Magics):
2702 2702 """Magics that control various autoX behaviors."""
2703 2703
2704 2704 def __init__(self, shell):
2705 2705 super(AutoMagics, self).__init__(shell)
2706 2706 # namespace for holding state we may need
2707 2707 self._magic_state = Bunch()
2708 2708
2709 2709 @line_magic
2710 2710 def automagic(self, parameter_s=''):
2711 2711 """Make magic functions callable without having to type the initial %.
2712 2712
2713 2713 Without argumentsl toggles on/off (when off, you must call it as
2714 2714 %automagic, of course). With arguments it sets the value, and you can
2715 2715 use any of (case insensitive):
2716 2716
2717 2717 - on, 1, True: to activate
2718 2718
2719 2719 - off, 0, False: to deactivate.
2720 2720
2721 2721 Note that magic functions have lowest priority, so if there's a
2722 2722 variable whose name collides with that of a magic fn, automagic won't
2723 2723 work for that function (you get the variable instead). However, if you
2724 2724 delete the variable (del var), the previously shadowed magic function
2725 2725 becomes visible to automagic again."""
2726 2726
2727 2727 arg = parameter_s.lower()
2728 2728 mman = self.shell.magics_manager
2729 2729 if arg in ('on', '1', 'true'):
2730 2730 val = True
2731 2731 elif arg in ('off', '0', 'false'):
2732 2732 val = False
2733 2733 else:
2734 2734 val = not mman.auto_magic
2735 2735 mman.auto_magic = val
2736 2736 print '\n' + self.shell.magics_manager.auto_status()
2737 2737
2738 2738 @skip_doctest
2739 2739 @line_magic
2740 2740 def autocall(self, parameter_s=''):
2741 2741 """Make functions callable without having to type parentheses.
2742 2742
2743 2743 Usage:
2744 2744
2745 2745 %autocall [mode]
2746 2746
2747 2747 The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the
2748 2748 value is toggled on and off (remembering the previous state).
2749 2749
2750 2750 In more detail, these values mean:
2751 2751
2752 2752 0 -> fully disabled
2753 2753
2754 2754 1 -> active, but do not apply if there are no arguments on the line.
2755 2755
2756 2756 In this mode, you get::
2757 2757
2758 2758 In [1]: callable
2759 2759 Out[1]: <built-in function callable>
2760 2760
2761 2761 In [2]: callable 'hello'
2762 2762 ------> callable('hello')
2763 2763 Out[2]: False
2764 2764
2765 2765 2 -> Active always. Even if no arguments are present, the callable
2766 2766 object is called::
2767 2767
2768 2768 In [2]: float
2769 2769 ------> float()
2770 2770 Out[2]: 0.0
2771 2771
2772 2772 Note that even with autocall off, you can still use '/' at the start of
2773 2773 a line to treat the first argument on the command line as a function
2774 2774 and add parentheses to it::
2775 2775
2776 2776 In [8]: /str 43
2777 2777 ------> str(43)
2778 2778 Out[8]: '43'
2779 2779
2780 2780 # all-random (note for auto-testing)
2781 2781 """
2782 2782
2783 2783 if parameter_s:
2784 2784 arg = int(parameter_s)
2785 2785 else:
2786 2786 arg = 'toggle'
2787 2787
2788 2788 if not arg in (0, 1, 2,'toggle'):
2789 2789 error('Valid modes: (0->Off, 1->Smart, 2->Full')
2790 2790 return
2791 2791
2792 2792 if arg in (0, 1, 2):
2793 2793 self.shell.autocall = arg
2794 2794 else: # toggle
2795 2795 if self.shell.autocall:
2796 2796 self._magic_state.autocall_save = self.shell.autocall
2797 2797 self.shell.autocall = 0
2798 2798 else:
2799 2799 try:
2800 2800 self.shell.autocall = self._magic_state.autocall_save
2801 2801 except AttributeError:
2802 2802 self.shell.autocall = self._magic_state.autocall_save = 1
2803 2803
2804 2804 print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall]
2805 2805
2806 2806
2807 2807 @register_magics
2808 2808 class OSMagics(Magics):
2809 2809 """Magics to interact with the underlying OS (shell-type functionality).
2810 2810 """
2811 2811
2812 2812 @skip_doctest
2813 2813 @line_magic
2814 2814 def alias(self, parameter_s=''):
2815 2815 """Define an alias for a system command.
2816 2816
2817 2817 '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd'
2818 2818
2819 2819 Then, typing 'alias_name params' will execute the system command 'cmd
2820 2820 params' (from your underlying operating system).
2821 2821
2822 2822 Aliases have lower precedence than magic functions and Python normal
2823 2823 variables, so if 'foo' is both a Python variable and an alias, the
2824 2824 alias can not be executed until 'del foo' removes the Python variable.
2825 2825
2826 2826 You can use the %l specifier in an alias definition to represent the
2827 2827 whole line when the alias is called. For example::
2828 2828
2829 2829 In [2]: alias bracket echo "Input in brackets: <%l>"
2830 2830 In [3]: bracket hello world
2831 2831 Input in brackets: <hello world>
2832 2832
2833 2833 You can also define aliases with parameters using %s specifiers (one
2834 2834 per parameter)::
2835 2835
2836 2836 In [1]: alias parts echo first %s second %s
2837 2837 In [2]: %parts A B
2838 2838 first A second B
2839 2839 In [3]: %parts A
2840 2840 Incorrect number of arguments: 2 expected.
2841 2841 parts is an alias to: 'echo first %s second %s'
2842 2842
2843 2843 Note that %l and %s are mutually exclusive. You can only use one or
2844 2844 the other in your aliases.
2845 2845
2846 2846 Aliases expand Python variables just like system calls using ! or !!
2847 2847 do: all expressions prefixed with '$' get expanded. For details of
2848 2848 the semantic rules, see PEP-215:
2849 2849 http://www.python.org/peps/pep-0215.html. This is the library used by
2850 2850 IPython for variable expansion. If you want to access a true shell
2851 2851 variable, an extra $ is necessary to prevent its expansion by
2852 2852 IPython::
2853 2853
2854 2854 In [6]: alias show echo
2855 2855 In [7]: PATH='A Python string'
2856 2856 In [8]: show $PATH
2857 2857 A Python string
2858 2858 In [9]: show $$PATH
2859 2859 /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:...
2860 2860
2861 2861 You can use the alias facility to acess all of $PATH. See the %rehash
2862 2862 and %rehashx functions, which automatically create aliases for the
2863 2863 contents of your $PATH.
2864 2864
2865 2865 If called with no parameters, %alias prints the current alias table."""
2866 2866
2867 2867 par = parameter_s.strip()
2868 2868 if not par:
2869 2869 aliases = sorted(self.shell.alias_manager.aliases)
2870 2870 # stored = self.shell.db.get('stored_aliases', {} )
2871 2871 # for k, v in stored:
2872 2872 # atab.append(k, v[0])
2873 2873
2874 2874 print "Total number of aliases:", len(aliases)
2875 2875 sys.stdout.flush()
2876 2876 return aliases
2877 2877
2878 2878 # Now try to define a new one
2879 2879 try:
2880 2880 alias,cmd = par.split(None, 1)
2881 2881 except:
2882 2882 print oinspect.getdoc(self.magic_alias)
2883 2883 else:
2884 2884 self.shell.alias_manager.soft_define_alias(alias, cmd)
2885 2885 # end magic_alias
2886 2886
2887 2887 @line_magic
2888 2888 def unalias(self, parameter_s=''):
2889 2889 """Remove an alias"""
2890 2890
2891 2891 aname = parameter_s.strip()
2892 2892 self.shell.alias_manager.undefine_alias(aname)
2893 2893 stored = self.shell.db.get('stored_aliases', {} )
2894 2894 if aname in stored:
2895 2895 print "Removing %stored alias",aname
2896 2896 del stored[aname]
2897 2897 self.shell.db['stored_aliases'] = stored
2898 2898
2899 2899 @line_magic
2900 2900 def rehashx(self, parameter_s=''):
2901 2901 """Update the alias table with all executable files in $PATH.
2902 2902
2903 2903 This version explicitly checks that every entry in $PATH is a file
2904 2904 with execute access (os.X_OK), so it is much slower than %rehash.
2905 2905
2906 2906 Under Windows, it checks executability as a match against a
2907 2907 '|'-separated string of extensions, stored in the IPython config
2908 2908 variable win_exec_ext. This defaults to 'exe|com|bat'.
2909 2909
2910 2910 This function also resets the root module cache of module completer,
2911 2911 used on slow filesystems.
2912 2912 """
2913 2913 from IPython.core.alias import InvalidAliasError
2914 2914
2915 2915 # for the benefit of module completer in ipy_completers.py
2916 2916 del self.shell.db['rootmodules']
2917 2917
2918 2918 path = [os.path.abspath(os.path.expanduser(p)) for p in
2919 2919 os.environ.get('PATH','').split(os.pathsep)]
2920 2920 path = filter(os.path.isdir,path)
2921 2921
2922 2922 syscmdlist = []
2923 2923 # Now define isexec in a cross platform manner.
2924 2924 if os.name == 'posix':
2925 2925 isexec = lambda fname:os.path.isfile(fname) and \
2926 2926 os.access(fname,os.X_OK)
2927 2927 else:
2928 2928 try:
2929 2929 winext = os.environ['pathext'].replace(';','|').replace('.','')
2930 2930 except KeyError:
2931 2931 winext = 'exe|com|bat|py'
2932 2932 if 'py' not in winext:
2933 2933 winext += '|py'
2934 2934 execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE)
2935 2935 isexec = lambda fname:os.path.isfile(fname) and execre.match(fname)
2936 2936 savedir = os.getcwdu()
2937 2937
2938 2938 # Now walk the paths looking for executables to alias.
2939 2939 try:
2940 2940 # write the whole loop for posix/Windows so we don't have an if in
2941 2941 # the innermost part
2942 2942 if os.name == 'posix':
2943 2943 for pdir in path:
2944 2944 os.chdir(pdir)
2945 2945 for ff in os.listdir(pdir):
2946 2946 if isexec(ff):
2947 2947 try:
2948 2948 # Removes dots from the name since ipython
2949 2949 # will assume names with dots to be python.
2950 2950 self.shell.alias_manager.define_alias(
2951 2951 ff.replace('.',''), ff)
2952 2952 except InvalidAliasError:
2953 2953 pass
2954 2954 else:
2955 2955 syscmdlist.append(ff)
2956 2956 else:
2957 2957 no_alias = self.shell.alias_manager.no_alias
2958 2958 for pdir in path:
2959 2959 os.chdir(pdir)
2960 2960 for ff in os.listdir(pdir):
2961 2961 base, ext = os.path.splitext(ff)
2962 2962 if isexec(ff) and base.lower() not in no_alias:
2963 2963 if ext.lower() == '.exe':
2964 2964 ff = base
2965 2965 try:
2966 2966 # Removes dots from the name since ipython
2967 2967 # will assume names with dots to be python.
2968 2968 self.shell.alias_manager.define_alias(
2969 2969 base.lower().replace('.',''), ff)
2970 2970 except InvalidAliasError:
2971 2971 pass
2972 2972 syscmdlist.append(ff)
2973 2973 self.shell.db['syscmdlist'] = syscmdlist
2974 2974 finally:
2975 2975 os.chdir(savedir)
2976 2976
2977 2977 @skip_doctest
2978 2978 @line_magic
2979 2979 def pwd(self, parameter_s=''):
2980 2980 """Return the current working directory path.
2981 2981
2982 2982 Examples
2983 2983 --------
2984 2984 ::
2985 2985
2986 2986 In [9]: pwd
2987 2987 Out[9]: '/home/tsuser/sprint/ipython'
2988 2988 """
2989 2989 return os.getcwdu()
2990 2990
2991 2991 @skip_doctest
2992 2992 @line_magic
2993 2993 def cd(self, parameter_s=''):
2994 2994 """Change the current working directory.
2995 2995
2996 2996 This command automatically maintains an internal list of directories
2997 2997 you visit during your IPython session, in the variable _dh. The
2998 2998 command %dhist shows this history nicely formatted. You can also
2999 2999 do 'cd -<tab>' to see directory history conveniently.
3000 3000
3001 3001 Usage:
3002 3002
3003 3003 cd 'dir': changes to directory 'dir'.
3004 3004
3005 3005 cd -: changes to the last visited directory.
3006 3006
3007 3007 cd -<n>: changes to the n-th directory in the directory history.
3008 3008
3009 3009 cd --foo: change to directory that matches 'foo' in history
3010 3010
3011 3011 cd -b <bookmark_name>: jump to a bookmark set by %bookmark
3012 3012 (note: cd <bookmark_name> is enough if there is no
3013 3013 directory <bookmark_name>, but a bookmark with the name exists.)
3014 3014 'cd -b <tab>' allows you to tab-complete bookmark names.
3015 3015
3016 3016 Options:
3017 3017
3018 3018 -q: quiet. Do not print the working directory after the cd command is
3019 3019 executed. By default IPython's cd command does print this directory,
3020 3020 since the default prompts do not display path information.
3021 3021
3022 3022 Note that !cd doesn't work for this purpose because the shell where
3023 3023 !command runs is immediately discarded after executing 'command'.
3024 3024
3025 3025 Examples
3026 3026 --------
3027 3027 ::
3028 3028
3029 3029 In [10]: cd parent/child
3030 3030 /home/tsuser/parent/child
3031 3031 """
3032 3032
3033 3033 #bkms = self.shell.persist.get("bookmarks",{})
3034 3034
3035 3035 oldcwd = os.getcwdu()
3036 3036 numcd = re.match(r'(-)(\d+)$',parameter_s)
3037 3037 # jump in directory history by number
3038 3038 if numcd:
3039 3039 nn = int(numcd.group(2))
3040 3040 try:
3041 3041 ps = self.shell.user_ns['_dh'][nn]
3042 3042 except IndexError:
3043 3043 print 'The requested directory does not exist in history.'
3044 3044 return
3045 3045 else:
3046 3046 opts = {}
3047 3047 elif parameter_s.startswith('--'):
3048 3048 ps = None
3049 3049 fallback = None
3050 3050 pat = parameter_s[2:]
3051 3051 dh = self.shell.user_ns['_dh']
3052 3052 # first search only by basename (last component)
3053 3053 for ent in reversed(dh):
3054 3054 if pat in os.path.basename(ent) and os.path.isdir(ent):
3055 3055 ps = ent
3056 3056 break
3057 3057
3058 3058 if fallback is None and pat in ent and os.path.isdir(ent):
3059 3059 fallback = ent
3060 3060
3061 3061 # if we have no last part match, pick the first full path match
3062 3062 if ps is None:
3063 3063 ps = fallback
3064 3064
3065 3065 if ps is None:
3066 3066 print "No matching entry in directory history"
3067 3067 return
3068 3068 else:
3069 3069 opts = {}
3070 3070
3071 3071
3072 3072 else:
3073 3073 #turn all non-space-escaping backslashes to slashes,
3074 3074 # for c:\windows\directory\names\
3075 3075 parameter_s = re.sub(r'\\(?! )','/', parameter_s)
3076 3076 opts,ps = self.parse_options(parameter_s,'qb',mode='string')
3077 3077 # jump to previous
3078 3078 if ps == '-':
3079 3079 try:
3080 3080 ps = self.shell.user_ns['_dh'][-2]
3081 3081 except IndexError:
3082 3082 raise UsageError('%cd -: No previous directory to change to.')
3083 3083 # jump to bookmark if needed
3084 3084 else:
3085 3085 if not os.path.isdir(ps) or opts.has_key('b'):
3086 3086 bkms = self.shell.db.get('bookmarks', {})
3087 3087
3088 3088 if bkms.has_key(ps):
3089 3089 target = bkms[ps]
3090 3090 print '(bookmark:%s) -> %s' % (ps,target)
3091 3091 ps = target
3092 3092 else:
3093 3093 if opts.has_key('b'):
3094 3094 raise UsageError("Bookmark '%s' not found. "
3095 3095 "Use '%%bookmark -l' to see your bookmarks." % ps)
3096 3096
3097 3097 # strip extra quotes on Windows, because os.chdir doesn't like them
3098 3098 ps = unquote_filename(ps)
3099 3099 # at this point ps should point to the target dir
3100 3100 if ps:
3101 3101 try:
3102 3102 os.chdir(os.path.expanduser(ps))
3103 3103 if hasattr(self.shell, 'term_title') and self.shell.term_title:
3104 3104 set_term_title('IPython: ' + abbrev_cwd())
3105 3105 except OSError:
3106 3106 print sys.exc_info()[1]
3107 3107 else:
3108 3108 cwd = os.getcwdu()
3109 3109 dhist = self.shell.user_ns['_dh']
3110 3110 if oldcwd != cwd:
3111 3111 dhist.append(cwd)
3112 3112 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
3113 3113
3114 3114 else:
3115 3115 os.chdir(self.shell.home_dir)
3116 3116 if hasattr(self.shell, 'term_title') and self.shell.term_title:
3117 3117 set_term_title('IPython: ' + '~')
3118 3118 cwd = os.getcwdu()
3119 3119 dhist = self.shell.user_ns['_dh']
3120 3120
3121 3121 if oldcwd != cwd:
3122 3122 dhist.append(cwd)
3123 3123 self.shell.db['dhist'] = compress_dhist(dhist)[-100:]
3124 3124 if not 'q' in opts and self.shell.user_ns['_dh']:
3125 3125 print self.shell.user_ns['_dh'][-1]
3126 3126
3127 3127
3128 3128 @line_magic
3129 3129 def env(self, parameter_s=''):
3130 3130 """List environment variables."""
3131 3131
3132 3132 return dict(os.environ)
3133 3133
3134 3134 @line_magic
3135 3135 def pushd(self, parameter_s=''):
3136 3136 """Place the current dir on stack and change directory.
3137 3137
3138 3138 Usage:\\
3139 3139 %pushd ['dirname']
3140 3140 """
3141 3141
3142 3142 dir_s = self.shell.dir_stack
3143 3143 tgt = os.path.expanduser(unquote_filename(parameter_s))
3144 3144 cwd = os.getcwdu().replace(self.shell.home_dir,'~')
3145 3145 if tgt:
3146 self.magic_cd(parameter_s)
3146 self.cd(parameter_s)
3147 3147 dir_s.insert(0,cwd)
3148 3148 return self.shell.magic('dirs')
3149 3149
3150 3150 @line_magic
3151 3151 def popd(self, parameter_s=''):
3152 3152 """Change to directory popped off the top of the stack.
3153 3153 """
3154 3154 if not self.shell.dir_stack:
3155 3155 raise UsageError("%popd on empty stack")
3156 3156 top = self.shell.dir_stack.pop(0)
3157 self.magic_cd(top)
3157 self.cd(top)
3158 3158 print "popd ->",top
3159 3159
3160 3160 @line_magic
3161 3161 def dirs(self, parameter_s=''):
3162 3162 """Return the current directory stack."""
3163 3163
3164 3164 return self.shell.dir_stack
3165 3165
3166 3166 @line_magic
3167 3167 def dhist(self, parameter_s=''):
3168 3168 """Print your history of visited directories.
3169 3169
3170 3170 %dhist -> print full history\\
3171 3171 %dhist n -> print last n entries only\\
3172 3172 %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\
3173 3173
3174 3174 This history is automatically maintained by the %cd command, and
3175 3175 always available as the global list variable _dh. You can use %cd -<n>
3176 3176 to go to directory number <n>.
3177 3177
3178 3178 Note that most of time, you should view directory history by entering
3179 3179 cd -<TAB>.
3180 3180
3181 3181 """
3182 3182
3183 3183 dh = self.shell.user_ns['_dh']
3184 3184 if parameter_s:
3185 3185 try:
3186 3186 args = map(int,parameter_s.split())
3187 3187 except:
3188 3188 self.arg_err(self.dhist)
3189 3189 return
3190 3190 if len(args) == 1:
3191 3191 ini,fin = max(len(dh)-(args[0]),0),len(dh)
3192 3192 elif len(args) == 2:
3193 3193 ini,fin = args
3194 3194 else:
3195 3195 self.arg_err(self.dhist)
3196 3196 return
3197 3197 else:
3198 3198 ini,fin = 0,len(dh)
3199 3199 nlprint(dh,
3200 3200 header = 'Directory history (kept in _dh)',
3201 3201 start=ini,stop=fin)
3202 3202
3203 3203 @skip_doctest
3204 3204 @line_magic
3205 3205 def sc(self, parameter_s=''):
3206 3206 """Shell capture - execute a shell command and capture its output.
3207 3207
3208 3208 DEPRECATED. Suboptimal, retained for backwards compatibility.
3209 3209
3210 3210 You should use the form 'var = !command' instead. Example:
3211 3211
3212 3212 "%sc -l myfiles = ls ~" should now be written as
3213 3213
3214 3214 "myfiles = !ls ~"
3215 3215
3216 3216 myfiles.s, myfiles.l and myfiles.n still apply as documented
3217 3217 below.
3218 3218
3219 3219 --
3220 3220 %sc [options] varname=command
3221 3221
3222 3222 IPython will run the given command using commands.getoutput(), and
3223 3223 will then update the user's interactive namespace with a variable
3224 3224 called varname, containing the value of the call. Your command can
3225 3225 contain shell wildcards, pipes, etc.
3226 3226
3227 3227 The '=' sign in the syntax is mandatory, and the variable name you
3228 3228 supply must follow Python's standard conventions for valid names.
3229 3229
3230 3230 (A special format without variable name exists for internal use)
3231 3231
3232 3232 Options:
3233 3233
3234 3234 -l: list output. Split the output on newlines into a list before
3235 3235 assigning it to the given variable. By default the output is stored
3236 3236 as a single string.
3237 3237
3238 3238 -v: verbose. Print the contents of the variable.
3239 3239
3240 3240 In most cases you should not need to split as a list, because the
3241 3241 returned value is a special type of string which can automatically
3242 3242 provide its contents either as a list (split on newlines) or as a
3243 3243 space-separated string. These are convenient, respectively, either
3244 3244 for sequential processing or to be passed to a shell command.
3245 3245
3246 3246 For example::
3247 3247
3248 3248 # Capture into variable a
3249 3249 In [1]: sc a=ls *py
3250 3250
3251 3251 # a is a string with embedded newlines
3252 3252 In [2]: a
3253 3253 Out[2]: 'setup.py\\nwin32_manual_post_install.py'
3254 3254
3255 3255 # which can be seen as a list:
3256 3256 In [3]: a.l
3257 3257 Out[3]: ['setup.py', 'win32_manual_post_install.py']
3258 3258
3259 3259 # or as a whitespace-separated string:
3260 3260 In [4]: a.s
3261 3261 Out[4]: 'setup.py win32_manual_post_install.py'
3262 3262
3263 3263 # a.s is useful to pass as a single command line:
3264 3264 In [5]: !wc -l $a.s
3265 3265 146 setup.py
3266 3266 130 win32_manual_post_install.py
3267 3267 276 total
3268 3268
3269 3269 # while the list form is useful to loop over:
3270 3270 In [6]: for f in a.l:
3271 3271 ...: !wc -l $f
3272 3272 ...:
3273 3273 146 setup.py
3274 3274 130 win32_manual_post_install.py
3275 3275
3276 3276 Similarly, the lists returned by the -l option are also special, in
3277 3277 the sense that you can equally invoke the .s attribute on them to
3278 3278 automatically get a whitespace-separated string from their contents::
3279 3279
3280 3280 In [7]: sc -l b=ls *py
3281 3281
3282 3282 In [8]: b
3283 3283 Out[8]: ['setup.py', 'win32_manual_post_install.py']
3284 3284
3285 3285 In [9]: b.s
3286 3286 Out[9]: 'setup.py win32_manual_post_install.py'
3287 3287
3288 3288 In summary, both the lists and strings used for output capture have
3289 3289 the following special attributes::
3290 3290
3291 3291 .l (or .list) : value as list.
3292 3292 .n (or .nlstr): value as newline-separated string.
3293 3293 .s (or .spstr): value as space-separated string.
3294 3294 """
3295 3295
3296 3296 opts,args = self.parse_options(parameter_s,'lv')
3297 3297 # Try to get a variable name and command to run
3298 3298 try:
3299 3299 # the variable name must be obtained from the parse_options
3300 3300 # output, which uses shlex.split to strip options out.
3301 3301 var,_ = args.split('=',1)
3302 3302 var = var.strip()
3303 3303 # But the command has to be extracted from the original input
3304 3304 # parameter_s, not on what parse_options returns, to avoid the
3305 3305 # quote stripping which shlex.split performs on it.
3306 3306 _,cmd = parameter_s.split('=',1)
3307 3307 except ValueError:
3308 3308 var,cmd = '',''
3309 3309 # If all looks ok, proceed
3310 3310 split = 'l' in opts
3311 3311 out = self.shell.getoutput(cmd, split=split)
3312 3312 if opts.has_key('v'):
3313 3313 print '%s ==\n%s' % (var,pformat(out))
3314 3314 if var:
3315 3315 self.shell.user_ns.update({var:out})
3316 3316 else:
3317 3317 return out
3318 3318
3319 3319 @line_magic
3320 3320 def sx(self, parameter_s=''):
3321 3321 """Shell execute - run a shell command and capture its output.
3322 3322
3323 3323 %sx command
3324 3324
3325 3325 IPython will run the given command using commands.getoutput(), and
3326 3326 return the result formatted as a list (split on '\\n'). Since the
3327 3327 output is _returned_, it will be stored in ipython's regular output
3328 3328 cache Out[N] and in the '_N' automatic variables.
3329 3329
3330 3330 Notes:
3331 3331
3332 3332 1) If an input line begins with '!!', then %sx is automatically
3333 3333 invoked. That is, while::
3334 3334
3335 3335 !ls
3336 3336
3337 3337 causes ipython to simply issue system('ls'), typing::
3338 3338
3339 3339 !!ls
3340 3340
3341 3341 is a shorthand equivalent to::
3342 3342
3343 3343 %sx ls
3344 3344
3345 3345 2) %sx differs from %sc in that %sx automatically splits into a list,
3346 3346 like '%sc -l'. The reason for this is to make it as easy as possible
3347 3347 to process line-oriented shell output via further python commands.
3348 3348 %sc is meant to provide much finer control, but requires more
3349 3349 typing.
3350 3350
3351 3351 3) Just like %sc -l, this is a list with special attributes:
3352 3352 ::
3353 3353
3354 3354 .l (or .list) : value as list.
3355 3355 .n (or .nlstr): value as newline-separated string.
3356 3356 .s (or .spstr): value as whitespace-separated string.
3357 3357
3358 3358 This is very useful when trying to use such lists as arguments to
3359 3359 system commands."""
3360 3360
3361 3361 if parameter_s:
3362 3362 return self.shell.getoutput(parameter_s)
3363 3363
3364 3364
3365 3365 @line_magic
3366 3366 def bookmark(self, parameter_s=''):
3367 3367 """Manage IPython's bookmark system.
3368 3368
3369 3369 %bookmark <name> - set bookmark to current dir
3370 3370 %bookmark <name> <dir> - set bookmark to <dir>
3371 3371 %bookmark -l - list all bookmarks
3372 3372 %bookmark -d <name> - remove bookmark
3373 3373 %bookmark -r - remove all bookmarks
3374 3374
3375 3375 You can later on access a bookmarked folder with::
3376 3376
3377 3377 %cd -b <name>
3378 3378
3379 3379 or simply '%cd <name>' if there is no directory called <name> AND
3380 3380 there is such a bookmark defined.
3381 3381
3382 3382 Your bookmarks persist through IPython sessions, but they are
3383 3383 associated with each profile."""
3384 3384
3385 3385 opts,args = self.parse_options(parameter_s,'drl',mode='list')
3386 3386 if len(args) > 2:
3387 3387 raise UsageError("%bookmark: too many arguments")
3388 3388
3389 3389 bkms = self.shell.db.get('bookmarks',{})
3390 3390
3391 3391 if opts.has_key('d'):
3392 3392 try:
3393 3393 todel = args[0]
3394 3394 except IndexError:
3395 3395 raise UsageError(
3396 3396 "%bookmark -d: must provide a bookmark to delete")
3397 3397 else:
3398 3398 try:
3399 3399 del bkms[todel]
3400 3400 except KeyError:
3401 3401 raise UsageError(
3402 3402 "%%bookmark -d: Can't delete bookmark '%s'" % todel)
3403 3403
3404 3404 elif opts.has_key('r'):
3405 3405 bkms = {}
3406 3406 elif opts.has_key('l'):
3407 3407 bks = bkms.keys()
3408 3408 bks.sort()
3409 3409 if bks:
3410 3410 size = max(map(len,bks))
3411 3411 else:
3412 3412 size = 0
3413 3413 fmt = '%-'+str(size)+'s -> %s'
3414 3414 print 'Current bookmarks:'
3415 3415 for bk in bks:
3416 3416 print fmt % (bk,bkms[bk])
3417 3417 else:
3418 3418 if not args:
3419 3419 raise UsageError("%bookmark: You must specify the bookmark name")
3420 3420 elif len(args)==1:
3421 3421 bkms[args[0]] = os.getcwdu()
3422 3422 elif len(args)==2:
3423 3423 bkms[args[0]] = args[1]
3424 3424 self.shell.db['bookmarks'] = bkms
3425 3425
3426 3426 @line_magic
3427 3427 def pycat(self, parameter_s=''):
3428 3428 """Show a syntax-highlighted file through a pager.
3429 3429
3430 3430 This magic is similar to the cat utility, but it will assume the file
3431 3431 to be Python source and will show it with syntax highlighting. """
3432 3432
3433 3433 try:
3434 3434 filename = get_py_filename(parameter_s)
3435 3435 cont = file_read(filename)
3436 3436 except IOError:
3437 3437 try:
3438 3438 cont = eval(parameter_s, self.shell.user_ns)
3439 3439 except NameError:
3440 3440 cont = None
3441 3441 if cont is None:
3442 3442 print "Error: no such file or variable"
3443 3443 return
3444 3444
3445 3445 page.page(self.shell.pycolorize(cont))
3446 3446
3447 3447
3448 3448 @register_magics
3449 3449 class LoggingMagics(Magics):
3450 3450 """Magics related to all logging machinery."""
3451 3451
3452 3452 @line_magic
3453 3453 def logstart(self, parameter_s=''):
3454 3454 """Start logging anywhere in a session.
3455 3455
3456 3456 %logstart [-o|-r|-t] [log_name [log_mode]]
3457 3457
3458 3458 If no name is given, it defaults to a file named 'ipython_log.py' in your
3459 3459 current directory, in 'rotate' mode (see below).
3460 3460
3461 3461 '%logstart name' saves to file 'name' in 'backup' mode. It saves your
3462 3462 history up to that point and then continues logging.
3463 3463
3464 3464 %logstart takes a second optional parameter: logging mode. This can be one
3465 3465 of (note that the modes are given unquoted):\\
3466 3466 append: well, that says it.\\
3467 3467 backup: rename (if exists) to name~ and start name.\\
3468 3468 global: single logfile in your home dir, appended to.\\
3469 3469 over : overwrite existing log.\\
3470 3470 rotate: create rotating logs name.1~, name.2~, etc.
3471 3471
3472 3472 Options:
3473 3473
3474 3474 -o: log also IPython's output. In this mode, all commands which
3475 3475 generate an Out[NN] prompt are recorded to the logfile, right after
3476 3476 their corresponding input line. The output lines are always
3477 3477 prepended with a '#[Out]# ' marker, so that the log remains valid
3478 3478 Python code.
3479 3479
3480 3480 Since this marker is always the same, filtering only the output from
3481 3481 a log is very easy, using for example a simple awk call::
3482 3482
3483 3483 awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py
3484 3484
3485 3485 -r: log 'raw' input. Normally, IPython's logs contain the processed
3486 3486 input, so that user lines are logged in their final form, converted
3487 3487 into valid Python. For example, %Exit is logged as
3488 3488 _ip.magic("Exit"). If the -r flag is given, all input is logged
3489 3489 exactly as typed, with no transformations applied.
3490 3490
3491 3491 -t: put timestamps before each input line logged (these are put in
3492 3492 comments)."""
3493 3493
3494 3494 opts,par = self.parse_options(parameter_s,'ort')
3495 3495 log_output = 'o' in opts
3496 3496 log_raw_input = 'r' in opts
3497 3497 timestamp = 't' in opts
3498 3498
3499 3499 logger = self.shell.logger
3500 3500
3501 3501 # if no args are given, the defaults set in the logger constructor by
3502 3502 # ipython remain valid
3503 3503 if par:
3504 3504 try:
3505 3505 logfname,logmode = par.split()
3506 3506 except:
3507 3507 logfname = par
3508 3508 logmode = 'backup'
3509 3509 else:
3510 3510 logfname = logger.logfname
3511 3511 logmode = logger.logmode
3512 3512 # put logfname into rc struct as if it had been called on the command
3513 3513 # line, so it ends up saved in the log header Save it in case we need
3514 3514 # to restore it...
3515 3515 old_logfile = self.shell.logfile
3516 3516 if logfname:
3517 3517 logfname = os.path.expanduser(logfname)
3518 3518 self.shell.logfile = logfname
3519 3519
3520 3520 loghead = '# IPython log file\n\n'
3521 3521 try:
3522 3522 logger.logstart(logfname, loghead, logmode, log_output, timestamp,
3523 3523 log_raw_input)
3524 3524 except:
3525 3525 self.shell.logfile = old_logfile
3526 3526 warn("Couldn't start log: %s" % sys.exc_info()[1])
3527 3527 else:
3528 3528 # log input history up to this point, optionally interleaving
3529 3529 # output if requested
3530 3530
3531 3531 if timestamp:
3532 3532 # disable timestamping for the previous history, since we've
3533 3533 # lost those already (no time machine here).
3534 3534 logger.timestamp = False
3535 3535
3536 3536 if log_raw_input:
3537 3537 input_hist = self.shell.history_manager.input_hist_raw
3538 3538 else:
3539 3539 input_hist = self.shell.history_manager.input_hist_parsed
3540 3540
3541 3541 if log_output:
3542 3542 log_write = logger.log_write
3543 3543 output_hist = self.shell.history_manager.output_hist
3544 3544 for n in range(1,len(input_hist)-1):
3545 3545 log_write(input_hist[n].rstrip() + '\n')
3546 3546 if n in output_hist:
3547 3547 log_write(repr(output_hist[n]),'output')
3548 3548 else:
3549 3549 logger.log_write('\n'.join(input_hist[1:]))
3550 3550 logger.log_write('\n')
3551 3551 if timestamp:
3552 3552 # re-enable timestamping
3553 3553 logger.timestamp = True
3554 3554
3555 3555 print ('Activating auto-logging. '
3556 3556 'Current session state plus future input saved.')
3557 3557 logger.logstate()
3558 3558
3559 3559 @line_magic
3560 3560 def logstop(self, parameter_s=''):
3561 3561 """Fully stop logging and close log file.
3562 3562
3563 3563 In order to start logging again, a new %logstart call needs to be made,
3564 3564 possibly (though not necessarily) with a new filename, mode and other
3565 3565 options."""
3566 3566 self.logger.logstop()
3567 3567
3568 3568 @line_magic
3569 3569 def logoff(self, parameter_s=''):
3570 3570 """Temporarily stop logging.
3571 3571
3572 3572 You must have previously started logging."""
3573 3573 self.shell.logger.switch_log(0)
3574 3574
3575 3575 @line_magic
3576 3576 def logon(self, parameter_s=''):
3577 3577 """Restart logging.
3578 3578
3579 3579 This function is for restarting logging which you've temporarily
3580 3580 stopped with %logoff. For starting logging for the first time, you
3581 3581 must use the %logstart function, which allows you to specify an
3582 3582 optional log filename."""
3583 3583
3584 3584 self.shell.logger.switch_log(1)
3585 3585
3586 3586 @line_magic
3587 3587 def logstate(self, parameter_s=''):
3588 3588 """Print the status of the logging system."""
3589 3589
3590 3590 self.shell.logger.logstate()
3591 3591
3592 3592
3593 3593 @register_magics
3594 3594 class ExtensionsMagics(Magics):
3595 3595 """Magics to manage the IPython extensions system."""
3596 3596
3597 3597 @line_magic
3598 3598 def install_ext(self, parameter_s=''):
3599 3599 """Download and install an extension from a URL, e.g.::
3600 3600
3601 3601 %install_ext https://bitbucket.org/birkenfeld/ipython-physics/raw/d1310a2ab15d/physics.py
3602 3602
3603 3603 The URL should point to an importable Python module - either a .py file
3604 3604 or a .zip file.
3605 3605
3606 3606 Parameters:
3607 3607
3608 3608 -n filename : Specify a name for the file, rather than taking it from
3609 3609 the URL.
3610 3610 """
3611 3611 opts, args = self.parse_options(parameter_s, 'n:')
3612 3612 try:
3613 3613 filename = self.shell.extension_manager.install_extension(args,
3614 3614 opts.get('n'))
3615 3615 except ValueError as e:
3616 3616 print e
3617 3617 return
3618 3618
3619 3619 filename = os.path.basename(filename)
3620 3620 print "Installed %s. To use it, type:" % filename
3621 3621 print " %%load_ext %s" % os.path.splitext(filename)[0]
3622 3622
3623 3623
3624 3624 @line_magic
3625 3625 def load_ext(self, module_str):
3626 3626 """Load an IPython extension by its module name."""
3627 3627 return self.shell.extension_manager.load_extension(module_str)
3628 3628
3629 3629 @line_magic
3630 3630 def unload_ext(self, module_str):
3631 3631 """Unload an IPython extension by its module name."""
3632 3632 self.shell.extension_manager.unload_extension(module_str)
3633 3633
3634 3634 @line_magic
3635 3635 def reload_ext(self, module_str):
3636 3636 """Reload an IPython extension by its module name."""
3637 3637 self.shell.extension_manager.reload_extension(module_str)
3638 3638
3639 3639
3640 3640 @register_magics
3641 3641 class PylabMagics(Magics):
3642 3642 """Magics related to matplotlib's pylab support"""
3643 3643
3644 3644 @skip_doctest
3645 3645 @line_magic
3646 3646 def pylab(self, parameter_s=''):
3647 3647 """Load numpy and matplotlib to work interactively.
3648 3648
3649 3649 %pylab [GUINAME]
3650 3650
3651 3651 This function lets you activate pylab (matplotlib, numpy and
3652 3652 interactive support) at any point during an IPython session.
3653 3653
3654 3654 It will import at the top level numpy as np, pyplot as plt, matplotlib,
3655 3655 pylab and mlab, as well as all names from numpy and pylab.
3656 3656
3657 3657 If you are using the inline matplotlib backend for embedded figures,
3658 3658 you can adjust its behavior via the %config magic::
3659 3659
3660 3660 # enable SVG figures, necessary for SVG+XHTML export in the qtconsole
3661 3661 In [1]: %config InlineBackend.figure_format = 'svg'
3662 3662
3663 3663 # change the behavior of closing all figures at the end of each
3664 3664 # execution (cell), or allowing reuse of active figures across
3665 3665 # cells:
3666 3666 In [2]: %config InlineBackend.close_figures = False
3667 3667
3668 3668 Parameters
3669 3669 ----------
3670 3670 guiname : optional
3671 3671 One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk',
3672 3672 'osx' or 'tk'). If given, the corresponding Matplotlib backend is
3673 3673 used, otherwise matplotlib's default (which you can override in your
3674 3674 matplotlib config file) is used.
3675 3675
3676 3676 Examples
3677 3677 --------
3678 3678 In this case, where the MPL default is TkAgg::
3679 3679
3680 3680 In [2]: %pylab
3681 3681
3682 3682 Welcome to pylab, a matplotlib-based Python environment.
3683 3683 Backend in use: TkAgg
3684 3684 For more information, type 'help(pylab)'.
3685 3685
3686 3686 But you can explicitly request a different backend::
3687 3687
3688 3688 In [3]: %pylab qt
3689 3689
3690 3690 Welcome to pylab, a matplotlib-based Python environment.
3691 3691 Backend in use: Qt4Agg
3692 3692 For more information, type 'help(pylab)'.
3693 3693 """
3694 3694
3695 3695 if Application.initialized():
3696 3696 app = Application.instance()
3697 3697 try:
3698 3698 import_all_status = app.pylab_import_all
3699 3699 except AttributeError:
3700 3700 import_all_status = True
3701 3701 else:
3702 3702 import_all_status = True
3703 3703
3704 3704 self.shell.enable_pylab(parameter_s, import_all=import_all_status)
3705 3705
3706 3706
3707 3707 @register_magics
3708 3708 class DeprecatedMagics(Magics):
3709 3709 """Magics slated for later removal."""
3710 3710
3711 3711 @line_magic
3712 3712 def install_profiles(self, parameter_s=''):
3713 3713 """%install_profiles has been deprecated."""
3714 3714 print '\n'.join([
3715 3715 "%install_profiles has been deprecated.",
3716 3716 "Use `ipython profile list` to view available profiles.",
3717 3717 "Requesting a profile with `ipython profile create <name>`",
3718 3718 "or `ipython --profile=<name>` will start with the bundled",
3719 3719 "profile of that name if it exists."
3720 3720 ])
3721 3721
3722 3722 @line_magic
3723 3723 def install_default_config(self, parameter_s=''):
3724 3724 """%install_default_config has been deprecated."""
3725 3725 print '\n'.join([
3726 3726 "%install_default_config has been deprecated.",
3727 3727 "Use `ipython profile create <name>` to initialize a profile",
3728 3728 "with the default config files.",
3729 3729 "Add `--reset` to overwrite already existing config files with defaults."
3730 3730 ])
@@ -1,485 +1,487 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tests for various magic functions.
3 3
4 4 Needs to be run by nose (to make ipython session available).
5 5 """
6 6 from __future__ import absolute_import
7 7
8 8 #-----------------------------------------------------------------------------
9 9 # Imports
10 10 #-----------------------------------------------------------------------------
11 11
12 12 import io
13 13 import os
14 14 import sys
15 15 from StringIO import StringIO
16 16
17 17 import nose.tools as nt
18 18
19 19 from IPython.core import magic
20 20 from IPython.core import magic_functions as mf
21 21 from IPython.nbformat.v3.tests.nbexamples import nb0
22 22 from IPython.nbformat import current
23 23 from IPython.testing import decorators as dec
24 24 from IPython.testing import tools as tt
25 25 from IPython.utils import py3compat
26 26 from IPython.utils.tempdir import TemporaryDirectory
27 27
28 28 #-----------------------------------------------------------------------------
29 29 # Test functions begin
30 30 #-----------------------------------------------------------------------------
31 31
32 @magic.register_magics
33 class DummyMagics(magic.Magics): pass
32 34
33 35 def test_rehashx():
34 36 # clear up everything
35 37 _ip = get_ipython()
36 38 _ip.alias_manager.alias_table.clear()
37 39 del _ip.db['syscmdlist']
38 40
39 41 _ip.magic('rehashx')
40 42 # Practically ALL ipython development systems will have more than 10 aliases
41 43
42 44 yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
43 45 for key, val in _ip.alias_manager.alias_table.iteritems():
44 46 # we must strip dots from alias names
45 47 nt.assert_true('.' not in key)
46 48
47 49 # rehashx must fill up syscmdlist
48 50 scoms = _ip.db['syscmdlist']
49 51 yield (nt.assert_true, len(scoms) > 10)
50 52
51 53
52 54 def test_magic_parse_options():
53 55 """Test that we don't mangle paths when parsing magic options."""
54 56 ip = get_ipython()
55 57 path = 'c:\\x'
56 m = magic.Magics(ip)
58 m = DummyMagics(ip)
57 59 opts = m.parse_options('-f %s' % path,'f:')[0]
58 60 # argv splitting is os-dependent
59 61 if os.name == 'posix':
60 62 expected = 'c:x'
61 63 else:
62 64 expected = path
63 65 nt.assert_equals(opts['f'], expected)
64 66
65 67
66 68 @dec.skip_without('sqlite3')
67 69 def doctest_hist_f():
68 70 """Test %hist -f with temporary filename.
69 71
70 72 In [9]: import tempfile
71 73
72 74 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
73 75
74 76 In [11]: %hist -nl -f $tfile 3
75 77
76 78 In [13]: import os; os.unlink(tfile)
77 79 """
78 80
79 81
80 82 @dec.skip_without('sqlite3')
81 83 def doctest_hist_r():
82 84 """Test %hist -r
83 85
84 86 XXX - This test is not recording the output correctly. For some reason, in
85 87 testing mode the raw history isn't getting populated. No idea why.
86 88 Disabling the output checking for now, though at least we do run it.
87 89
88 90 In [1]: 'hist' in _ip.lsmagic()
89 91 Out[1]: True
90 92
91 93 In [2]: x=1
92 94
93 95 In [3]: %hist -rl 2
94 96 x=1 # random
95 97 %hist -r 2
96 98 """
97 99
98 100
99 101 @dec.skip_without('sqlite3')
100 102 def doctest_hist_op():
101 103 """Test %hist -op
102 104
103 105 In [1]: class b(float):
104 106 ...: pass
105 107 ...:
106 108
107 109 In [2]: class s(object):
108 110 ...: def __str__(self):
109 111 ...: return 's'
110 112 ...:
111 113
112 114 In [3]:
113 115
114 116 In [4]: class r(b):
115 117 ...: def __repr__(self):
116 118 ...: return 'r'
117 119 ...:
118 120
119 121 In [5]: class sr(s,r): pass
120 122 ...:
121 123
122 124 In [6]:
123 125
124 126 In [7]: bb=b()
125 127
126 128 In [8]: ss=s()
127 129
128 130 In [9]: rr=r()
129 131
130 132 In [10]: ssrr=sr()
131 133
132 134 In [11]: 4.5
133 135 Out[11]: 4.5
134 136
135 137 In [12]: str(ss)
136 138 Out[12]: 's'
137 139
138 140 In [13]:
139 141
140 142 In [14]: %hist -op
141 143 >>> class b:
142 144 ... pass
143 145 ...
144 146 >>> class s(b):
145 147 ... def __str__(self):
146 148 ... return 's'
147 149 ...
148 150 >>>
149 151 >>> class r(b):
150 152 ... def __repr__(self):
151 153 ... return 'r'
152 154 ...
153 155 >>> class sr(s,r): pass
154 156 >>>
155 157 >>> bb=b()
156 158 >>> ss=s()
157 159 >>> rr=r()
158 160 >>> ssrr=sr()
159 161 >>> 4.5
160 162 4.5
161 163 >>> str(ss)
162 164 's'
163 165 >>>
164 166 """
165 167
166 168
167 169 @dec.skip_without('sqlite3')
168 170 def test_macro():
169 171 ip = get_ipython()
170 172 ip.history_manager.reset() # Clear any existing history.
171 173 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
172 174 for i, cmd in enumerate(cmds, start=1):
173 175 ip.history_manager.store_inputs(i, cmd)
174 176 ip.magic("macro test 1-3")
175 177 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
176 178
177 179 # List macros.
178 180 assert "test" in ip.magic("macro")
179 181
180 182
181 183 @dec.skip_without('sqlite3')
182 184 def test_macro_run():
183 185 """Test that we can run a multi-line macro successfully."""
184 186 ip = get_ipython()
185 187 ip.history_manager.reset()
186 188 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
187 189 "%macro test 2-3"]
188 190 for cmd in cmds:
189 191 ip.run_cell(cmd, store_history=True)
190 192 nt.assert_equal(ip.user_ns["test"].value,
191 193 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
192 194 with tt.AssertPrints("12"):
193 195 ip.run_cell("test")
194 196 with tt.AssertPrints("13"):
195 197 ip.run_cell("test")
196 198
197 199
198 200 @dec.skipif_not_numpy
199 201 def test_numpy_reset_array_undec():
200 202 "Test '%reset array' functionality"
201 203 _ip.ex('import numpy as np')
202 204 _ip.ex('a = np.empty(2)')
203 205 yield (nt.assert_true, 'a' in _ip.user_ns)
204 206 _ip.magic('reset -f array')
205 207 yield (nt.assert_false, 'a' in _ip.user_ns)
206 208
207 209 def test_reset_out():
208 210 "Test '%reset out' magic"
209 211 _ip.run_cell("parrot = 'dead'", store_history=True)
210 212 # test '%reset -f out', make an Out prompt
211 213 _ip.run_cell("parrot", store_history=True)
212 214 nt.assert_true('dead' in [_ip.user_ns[x] for x in '_','__','___'])
213 215 _ip.magic('reset -f out')
214 216 nt.assert_false('dead' in [_ip.user_ns[x] for x in '_','__','___'])
215 217 nt.assert_true(len(_ip.user_ns['Out']) == 0)
216 218
217 219 def test_reset_in():
218 220 "Test '%reset in' magic"
219 221 # test '%reset -f in'
220 222 _ip.run_cell("parrot", store_history=True)
221 223 nt.assert_true('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
222 224 _ip.magic('%reset -f in')
223 225 nt.assert_false('parrot' in [_ip.user_ns[x] for x in '_i','_ii','_iii'])
224 226 nt.assert_true(len(set(_ip.user_ns['In'])) == 1)
225 227
226 228 def test_reset_dhist():
227 229 "Test '%reset dhist' magic"
228 230 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
229 231 _ip.magic('cd ' + os.path.dirname(nt.__file__))
230 232 _ip.magic('cd -')
231 233 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
232 234 _ip.magic('reset -f dhist')
233 235 nt.assert_true(len(_ip.user_ns['_dh']) == 0)
234 236 _ip.run_cell("_dh = [d for d in tmp]") #restore
235 237
236 238 def test_reset_in_length():
237 239 "Test that '%reset in' preserves In[] length"
238 240 _ip.run_cell("print 'foo'")
239 241 _ip.run_cell("reset -f in")
240 242 nt.assert_true(len(_ip.user_ns['In']) == _ip.displayhook.prompt_count+1)
241 243
242 244 def test_time():
243 245 _ip.magic('time None')
244 246
245 247 def test_tb_syntaxerror():
246 248 """test %tb after a SyntaxError"""
247 249 ip = get_ipython()
248 250 ip.run_cell("for")
249 251
250 252 # trap and validate stdout
251 253 save_stdout = sys.stdout
252 254 try:
253 255 sys.stdout = StringIO()
254 256 ip.run_cell("%tb")
255 257 out = sys.stdout.getvalue()
256 258 finally:
257 259 sys.stdout = save_stdout
258 260 # trim output, and only check the last line
259 261 last_line = out.rstrip().splitlines()[-1].strip()
260 262 nt.assert_equals(last_line, "SyntaxError: invalid syntax")
261 263
262 264
263 265 @py3compat.doctest_refactor_print
264 266 def doctest_time():
265 267 """
266 268 In [10]: %time None
267 269 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
268 270 Wall time: 0.00 s
269 271
270 272 In [11]: def f(kmjy):
271 273 ....: %time print 2*kmjy
272 274
273 275 In [12]: f(3)
274 276 6
275 277 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
276 278 Wall time: 0.00 s
277 279 """
278 280
279 281
280 282 def test_doctest_mode():
281 283 "Toggle doctest_mode twice, it should be a no-op and run without error"
282 284 _ip.magic('doctest_mode')
283 285 _ip.magic('doctest_mode')
284 286
285 287
286 288 def test_parse_options():
287 289 """Tests for basic options parsing in magics."""
288 290 # These are only the most minimal of tests, more should be added later. At
289 291 # the very least we check that basic text/unicode calls work OK.
290 m = magic.Magics(ip)
292 m = DummyMagics(_ip)
291 293 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
292 294 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
293 295
294 296
295 297 def test_dirops():
296 298 """Test various directory handling operations."""
297 299 # curpath = lambda :os.path.splitdrive(os.getcwdu())[1].replace('\\','/')
298 300 curpath = os.getcwdu
299 301 startdir = os.getcwdu()
300 302 ipdir = os.path.realpath(_ip.ipython_dir)
301 303 try:
302 304 _ip.magic('cd "%s"' % ipdir)
303 305 nt.assert_equal(curpath(), ipdir)
304 306 _ip.magic('cd -')
305 307 nt.assert_equal(curpath(), startdir)
306 308 _ip.magic('pushd "%s"' % ipdir)
307 309 nt.assert_equal(curpath(), ipdir)
308 310 _ip.magic('popd')
309 311 nt.assert_equal(curpath(), startdir)
310 312 finally:
311 313 os.chdir(startdir)
312 314
313 315
314 316 def test_xmode():
315 317 # Calling xmode three times should be a no-op
316 318 xmode = _ip.InteractiveTB.mode
317 319 for i in range(3):
318 320 _ip.magic("xmode")
319 321 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
320 322
321 323 def test_reset_hard():
322 324 monitor = []
323 325 class A(object):
324 326 def __del__(self):
325 327 monitor.append(1)
326 328 def __repr__(self):
327 329 return "<A instance>"
328 330
329 331 _ip.user_ns["a"] = A()
330 332 _ip.run_cell("a")
331 333
332 334 nt.assert_equal(monitor, [])
333 335 _ip.magic("reset -f")
334 336 nt.assert_equal(monitor, [1])
335 337
336 338 class TestXdel(tt.TempFileMixin):
337 339 def test_xdel(self):
338 340 """Test that references from %run are cleared by xdel."""
339 341 src = ("class A(object):\n"
340 342 " monitor = []\n"
341 343 " def __del__(self):\n"
342 344 " self.monitor.append(1)\n"
343 345 "a = A()\n")
344 346 self.mktmp(src)
345 347 # %run creates some hidden references...
346 348 _ip.magic("run %s" % self.fname)
347 349 # ... as does the displayhook.
348 350 _ip.run_cell("a")
349 351
350 352 monitor = _ip.user_ns["A"].monitor
351 353 nt.assert_equal(monitor, [])
352 354
353 355 _ip.magic("xdel a")
354 356
355 357 # Check that a's __del__ method has been called.
356 358 nt.assert_equal(monitor, [1])
357 359
358 360 def doctest_who():
359 361 """doctest for %who
360 362
361 363 In [1]: %reset -f
362 364
363 365 In [2]: alpha = 123
364 366
365 367 In [3]: beta = 'beta'
366 368
367 369 In [4]: %who int
368 370 alpha
369 371
370 372 In [5]: %who str
371 373 beta
372 374
373 375 In [6]: %whos
374 376 Variable Type Data/Info
375 377 ----------------------------
376 378 alpha int 123
377 379 beta str beta
378 380
379 381 In [7]: %who_ls
380 382 Out[7]: ['alpha', 'beta']
381 383 """
382 384
383 385 def test_whos():
384 386 """Check that whos is protected against objects where repr() fails."""
385 387 class A(object):
386 388 def __repr__(self):
387 389 raise Exception()
388 390 _ip.user_ns['a'] = A()
389 391 _ip.magic("whos")
390 392
391 393 @py3compat.u_format
392 394 def doctest_precision():
393 395 """doctest for %precision
394 396
395 397 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
396 398
397 399 In [2]: %precision 5
398 400 Out[2]: {u}'%.5f'
399 401
400 402 In [3]: f.float_format
401 403 Out[3]: {u}'%.5f'
402 404
403 405 In [4]: %precision %e
404 406 Out[4]: {u}'%e'
405 407
406 408 In [5]: f(3.1415927)
407 409 Out[5]: {u}'3.141593e+00'
408 410 """
409 411
410 412 def test_psearch():
411 413 with tt.AssertPrints("dict.fromkeys"):
412 414 _ip.run_cell("dict.fr*?")
413 415
414 416 def test_timeit_shlex():
415 417 """test shlex issues with timeit (#1109)"""
416 418 _ip.ex("def f(*a,**kw): pass")
417 419 _ip.magic('timeit -n1 "this is a bug".count(" ")')
418 420 _ip.magic('timeit -r1 -n1 f(" ", 1)')
419 421 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
420 422 _ip.magic('timeit -r1 -n1 ("a " + "b")')
421 423 _ip.magic('timeit -r1 -n1 f("a " + "b")')
422 424 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
423 425
424 426
425 427 def test_timeit_arguments():
426 428 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
427 429 _ip.magic("timeit ('#')")
428 430
429 431
430 432 @dec.skipif(mf.profile is None)
431 433 def test_prun_quotes():
432 434 "Test that prun does not clobber string escapes (GH #1302)"
433 435 _ip.magic("prun -q x = '\t'")
434 436 nt.assert_equal(_ip.user_ns['x'], '\t')
435 437
436 438 def test_extension():
437 439 tmpdir = TemporaryDirectory()
438 440 orig_ipython_dir = _ip.ipython_dir
439 441 try:
440 442 _ip.ipython_dir = tmpdir.name
441 443 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
442 444 url = os.path.join(os.path.dirname(__file__), "daft_extension.py")
443 445 _ip.magic("install_ext %s" % url)
444 446 _ip.user_ns.pop('arq', None)
445 447 _ip.magic("load_ext daft_extension")
446 448 tt.assert_equal(_ip.user_ns['arq'], 185)
447 449 _ip.magic("unload_ext daft_extension")
448 450 assert 'arq' not in _ip.user_ns
449 451 finally:
450 452 _ip.ipython_dir = orig_ipython_dir
451 453
452 454 def test_notebook_export_json():
453 455 with TemporaryDirectory() as td:
454 456 outfile = os.path.join(td, "nb.ipynb")
455 457 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
456 458 _ip.magic("notebook -e %s" % outfile)
457 459
458 460 def test_notebook_export_py():
459 461 with TemporaryDirectory() as td:
460 462 outfile = os.path.join(td, "nb.py")
461 463 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
462 464 _ip.magic("notebook -e %s" % outfile)
463 465
464 466 def test_notebook_reformat_py():
465 467 with TemporaryDirectory() as td:
466 468 infile = os.path.join(td, "nb.ipynb")
467 469 with io.open(infile, 'w', encoding='utf-8') as f:
468 470 current.write(nb0, f, 'json')
469 471
470 472 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
471 473 _ip.magic("notebook -f py %s" % infile)
472 474
473 475 def test_notebook_reformat_json():
474 476 with TemporaryDirectory() as td:
475 477 infile = os.path.join(td, "nb.py")
476 478 with io.open(infile, 'w', encoding='utf-8') as f:
477 479 current.write(nb0, f, 'py')
478 480
479 481 _ip.ex(py3compat.u_format(u"u = {u}'héllo'"))
480 482 _ip.magic("notebook -f ipynb %s" % infile)
481 483 _ip.magic("notebook -f json %s" % infile)
482 484
483 485 def test_env():
484 486 env = _ip.magic("env")
485 487 assert isinstance(env, dict), type(env)
General Comments 0
You need to be logged in to leave comments. Login now