##// END OF EJS Templates
Simplify caching of modules from %run-ing scripts....
Thomas Kluyver -
Show More
@@ -1,3108 +1,3079 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Main IPython class."""
3 3
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de>
6 6 # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu>
7 7 # Copyright (C) 2008-2011 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 #-----------------------------------------------------------------------------
14 14 # Imports
15 15 #-----------------------------------------------------------------------------
16 16
17 17 from __future__ import absolute_import
18 18 from __future__ import print_function
19 19
20 20 import __builtin__ as builtin_mod
21 21 import __future__
22 22 import abc
23 23 import ast
24 24 import atexit
25 25 import os
26 26 import re
27 27 import runpy
28 28 import sys
29 29 import tempfile
30 30 import types
31 31 from io import open as io_open
32 32
33 33 from IPython.config.configurable import SingletonConfigurable
34 34 from IPython.core import debugger, oinspect
35 35 from IPython.core import magic
36 36 from IPython.core import page
37 37 from IPython.core import prefilter
38 38 from IPython.core import shadowns
39 39 from IPython.core import ultratb
40 40 from IPython.core.alias import AliasManager, AliasError
41 41 from IPython.core.autocall import ExitAutocall
42 42 from IPython.core.builtin_trap import BuiltinTrap
43 43 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
44 44 from IPython.core.display_trap import DisplayTrap
45 45 from IPython.core.displayhook import DisplayHook
46 46 from IPython.core.displaypub import DisplayPublisher
47 47 from IPython.core.error import UsageError
48 48 from IPython.core.extensions import ExtensionManager
49 49 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
50 50 from IPython.core.formatters import DisplayFormatter
51 51 from IPython.core.history import HistoryManager
52 52 from IPython.core.inputsplitter import IPythonInputSplitter, ESC_MAGIC, ESC_MAGIC2
53 53 from IPython.core.logger import Logger
54 54 from IPython.core.macro import Macro
55 55 from IPython.core.payload import PayloadManager
56 56 from IPython.core.prefilter import PrefilterManager
57 57 from IPython.core.profiledir import ProfileDir
58 58 from IPython.core.pylabtools import pylab_activate
59 59 from IPython.core.prompts import PromptManager
60 60 from IPython.lib.latextools import LaTeXTool
61 61 from IPython.testing.skipdoctest import skip_doctest
62 62 from IPython.utils import PyColorize
63 63 from IPython.utils import io
64 64 from IPython.utils import py3compat
65 65 from IPython.utils import openpy
66 66 from IPython.utils.decorators import undoc
67 67 from IPython.utils.io import ask_yes_no
68 68 from IPython.utils.ipstruct import Struct
69 69 from IPython.utils.path import get_home_dir, get_ipython_dir, get_py_filename, unquote_filename
70 70 from IPython.utils.pickleshare import PickleShareDB
71 71 from IPython.utils.process import system, getoutput
72 72 from IPython.utils.strdispatch import StrDispatch
73 73 from IPython.utils.syspathcontext import prepended_to_syspath
74 74 from IPython.utils.text import (format_screen, LSString, SList,
75 75 DollarFormatter)
76 76 from IPython.utils.traitlets import (Integer, CBool, CaselessStrEnum, Enum,
77 77 List, Unicode, Instance, Type)
78 78 from IPython.utils.warn import warn, error
79 79 import IPython.core.hooks
80 80
81 81 #-----------------------------------------------------------------------------
82 82 # Globals
83 83 #-----------------------------------------------------------------------------
84 84
85 85 # compiled regexps for autoindent management
86 86 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
87 87
88 88 #-----------------------------------------------------------------------------
89 89 # Utilities
90 90 #-----------------------------------------------------------------------------
91 91
92 92 @undoc
93 93 def softspace(file, newvalue):
94 94 """Copied from code.py, to remove the dependency"""
95 95
96 96 oldvalue = 0
97 97 try:
98 98 oldvalue = file.softspace
99 99 except AttributeError:
100 100 pass
101 101 try:
102 102 file.softspace = newvalue
103 103 except (AttributeError, TypeError):
104 104 # "attribute-less object" or "read-only attributes"
105 105 pass
106 106 return oldvalue
107 107
108 108 @undoc
109 109 def no_op(*a, **kw): pass
110 110
111 111 @undoc
112 112 class NoOpContext(object):
113 113 def __enter__(self): pass
114 114 def __exit__(self, type, value, traceback): pass
115 115 no_op_context = NoOpContext()
116 116
117 117 class SpaceInInput(Exception): pass
118 118
119 119 @undoc
120 120 class Bunch: pass
121 121
122 122
123 123 def get_default_colors():
124 124 if sys.platform=='darwin':
125 125 return "LightBG"
126 126 elif os.name=='nt':
127 127 return 'Linux'
128 128 else:
129 129 return 'Linux'
130 130
131 131
132 132 class SeparateUnicode(Unicode):
133 133 """A Unicode subclass to validate separate_in, separate_out, etc.
134 134
135 135 This is a Unicode based trait that converts '0'->'' and '\\n'->'\n'.
136 136 """
137 137
138 138 def validate(self, obj, value):
139 139 if value == '0': value = ''
140 140 value = value.replace('\\n','\n')
141 141 return super(SeparateUnicode, self).validate(obj, value)
142 142
143 143
144 144 class ReadlineNoRecord(object):
145 145 """Context manager to execute some code, then reload readline history
146 146 so that interactive input to the code doesn't appear when pressing up."""
147 147 def __init__(self, shell):
148 148 self.shell = shell
149 149 self._nested_level = 0
150 150
151 151 def __enter__(self):
152 152 if self._nested_level == 0:
153 153 try:
154 154 self.orig_length = self.current_length()
155 155 self.readline_tail = self.get_readline_tail()
156 156 except (AttributeError, IndexError): # Can fail with pyreadline
157 157 self.orig_length, self.readline_tail = 999999, []
158 158 self._nested_level += 1
159 159
160 160 def __exit__(self, type, value, traceback):
161 161 self._nested_level -= 1
162 162 if self._nested_level == 0:
163 163 # Try clipping the end if it's got longer
164 164 try:
165 165 e = self.current_length() - self.orig_length
166 166 if e > 0:
167 167 for _ in range(e):
168 168 self.shell.readline.remove_history_item(self.orig_length)
169 169
170 170 # If it still doesn't match, just reload readline history.
171 171 if self.current_length() != self.orig_length \
172 172 or self.get_readline_tail() != self.readline_tail:
173 173 self.shell.refill_readline_hist()
174 174 except (AttributeError, IndexError):
175 175 pass
176 176 # Returning False will cause exceptions to propagate
177 177 return False
178 178
179 179 def current_length(self):
180 180 return self.shell.readline.get_current_history_length()
181 181
182 182 def get_readline_tail(self, n=10):
183 183 """Get the last n items in readline history."""
184 184 end = self.shell.readline.get_current_history_length() + 1
185 185 start = max(end-n, 1)
186 186 ghi = self.shell.readline.get_history_item
187 187 return [ghi(x) for x in range(start, end)]
188 188
189 189 #-----------------------------------------------------------------------------
190 190 # Main IPython class
191 191 #-----------------------------------------------------------------------------
192 192
193 193 class InteractiveShell(SingletonConfigurable):
194 194 """An enhanced, interactive shell for Python."""
195 195
196 196 _instance = None
197 197
198 198 ast_transformers = List([], config=True, help=
199 199 """
200 200 A list of ast.NodeTransformer subclass instances, which will be applied
201 201 to user input before code is run.
202 202 """
203 203 )
204 204
205 205 autocall = Enum((0,1,2), default_value=0, config=True, help=
206 206 """
207 207 Make IPython automatically call any callable object even if you didn't
208 208 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
209 209 automatically. The value can be '0' to disable the feature, '1' for
210 210 'smart' autocall, where it is not applied if there are no more
211 211 arguments on the line, and '2' for 'full' autocall, where all callable
212 212 objects are automatically called (even if no arguments are present).
213 213 """
214 214 )
215 215 # TODO: remove all autoindent logic and put into frontends.
216 216 # We can't do this yet because even runlines uses the autoindent.
217 217 autoindent = CBool(True, config=True, help=
218 218 """
219 219 Autoindent IPython code entered interactively.
220 220 """
221 221 )
222 222 automagic = CBool(True, config=True, help=
223 223 """
224 224 Enable magic commands to be called without the leading %.
225 225 """
226 226 )
227 227 cache_size = Integer(1000, config=True, help=
228 228 """
229 229 Set the size of the output cache. The default is 1000, you can
230 230 change it permanently in your config file. Setting it to 0 completely
231 231 disables the caching system, and the minimum value accepted is 20 (if
232 232 you provide a value less than 20, it is reset to 0 and a warning is
233 233 issued). This limit is defined because otherwise you'll spend more
234 234 time re-flushing a too small cache than working
235 235 """
236 236 )
237 237 color_info = CBool(True, config=True, help=
238 238 """
239 239 Use colors for displaying information about objects. Because this
240 240 information is passed through a pager (like 'less'), and some pagers
241 241 get confused with color codes, this capability can be turned off.
242 242 """
243 243 )
244 244 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
245 245 default_value=get_default_colors(), config=True,
246 246 help="Set the color scheme (NoColor, Linux, or LightBG)."
247 247 )
248 248 colors_force = CBool(False, help=
249 249 """
250 250 Force use of ANSI color codes, regardless of OS and readline
251 251 availability.
252 252 """
253 253 # FIXME: This is essentially a hack to allow ZMQShell to show colors
254 254 # without readline on Win32. When the ZMQ formatting system is
255 255 # refactored, this should be removed.
256 256 )
257 257 debug = CBool(False, config=True)
258 258 deep_reload = CBool(False, config=True, help=
259 259 """
260 260 Enable deep (recursive) reloading by default. IPython can use the
261 261 deep_reload module which reloads changes in modules recursively (it
262 262 replaces the reload() function, so you don't need to change anything to
263 263 use it). deep_reload() forces a full reload of modules whose code may
264 264 have changed, which the default reload() function does not. When
265 265 deep_reload is off, IPython will use the normal reload(), but
266 266 deep_reload will still be available as dreload().
267 267 """
268 268 )
269 269 disable_failing_post_execute = CBool(False, config=True,
270 270 help="Don't call post-execute functions that have failed in the past."
271 271 )
272 272 display_formatter = Instance(DisplayFormatter)
273 273 displayhook_class = Type(DisplayHook)
274 274 display_pub_class = Type(DisplayPublisher)
275 275 data_pub_class = None
276 276
277 277 exit_now = CBool(False)
278 278 exiter = Instance(ExitAutocall)
279 279 def _exiter_default(self):
280 280 return ExitAutocall(self)
281 281 # Monotonically increasing execution counter
282 282 execution_count = Integer(1)
283 283 filename = Unicode("<ipython console>")
284 284 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
285 285
286 286 # Input splitter, to transform input line by line and detect when a block
287 287 # is ready to be executed.
288 288 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
289 289 (), {'line_input_checker': True})
290 290
291 291 # This InputSplitter instance is used to transform completed cells before
292 292 # running them. It allows cell magics to contain blank lines.
293 293 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
294 294 (), {'line_input_checker': False})
295 295
296 296 logstart = CBool(False, config=True, help=
297 297 """
298 298 Start logging to the default log file.
299 299 """
300 300 )
301 301 logfile = Unicode('', config=True, help=
302 302 """
303 303 The name of the logfile to use.
304 304 """
305 305 )
306 306 logappend = Unicode('', config=True, help=
307 307 """
308 308 Start logging to the given file in append mode.
309 309 """
310 310 )
311 311 object_info_string_level = Enum((0,1,2), default_value=0,
312 312 config=True)
313 313 pdb = CBool(False, config=True, help=
314 314 """
315 315 Automatically call the pdb debugger after every exception.
316 316 """
317 317 )
318 318 multiline_history = CBool(sys.platform != 'win32', config=True,
319 319 help="Save multi-line entries as one entry in readline history"
320 320 )
321 321
322 322 # deprecated prompt traits:
323 323
324 324 prompt_in1 = Unicode('In [\\#]: ', config=True,
325 325 help="Deprecated, use PromptManager.in_template")
326 326 prompt_in2 = Unicode(' .\\D.: ', config=True,
327 327 help="Deprecated, use PromptManager.in2_template")
328 328 prompt_out = Unicode('Out[\\#]: ', config=True,
329 329 help="Deprecated, use PromptManager.out_template")
330 330 prompts_pad_left = CBool(True, config=True,
331 331 help="Deprecated, use PromptManager.justify")
332 332
333 333 def _prompt_trait_changed(self, name, old, new):
334 334 table = {
335 335 'prompt_in1' : 'in_template',
336 336 'prompt_in2' : 'in2_template',
337 337 'prompt_out' : 'out_template',
338 338 'prompts_pad_left' : 'justify',
339 339 }
340 340 warn("InteractiveShell.{name} is deprecated, use PromptManager.{newname}".format(
341 341 name=name, newname=table[name])
342 342 )
343 343 # protect against weird cases where self.config may not exist:
344 344 if self.config is not None:
345 345 # propagate to corresponding PromptManager trait
346 346 setattr(self.config.PromptManager, table[name], new)
347 347
348 348 _prompt_in1_changed = _prompt_trait_changed
349 349 _prompt_in2_changed = _prompt_trait_changed
350 350 _prompt_out_changed = _prompt_trait_changed
351 351 _prompt_pad_left_changed = _prompt_trait_changed
352 352
353 353 show_rewritten_input = CBool(True, config=True,
354 354 help="Show rewritten input, e.g. for autocall."
355 355 )
356 356
357 357 quiet = CBool(False, config=True)
358 358
359 359 history_length = Integer(10000, config=True)
360 360
361 361 # The readline stuff will eventually be moved to the terminal subclass
362 362 # but for now, we can't do that as readline is welded in everywhere.
363 363 readline_use = CBool(True, config=True)
364 364 readline_remove_delims = Unicode('-/~', config=True)
365 365 readline_delims = Unicode() # set by init_readline()
366 366 # don't use \M- bindings by default, because they
367 367 # conflict with 8-bit encodings. See gh-58,gh-88
368 368 readline_parse_and_bind = List([
369 369 'tab: complete',
370 370 '"\C-l": clear-screen',
371 371 'set show-all-if-ambiguous on',
372 372 '"\C-o": tab-insert',
373 373 '"\C-r": reverse-search-history',
374 374 '"\C-s": forward-search-history',
375 375 '"\C-p": history-search-backward',
376 376 '"\C-n": history-search-forward',
377 377 '"\e[A": history-search-backward',
378 378 '"\e[B": history-search-forward',
379 379 '"\C-k": kill-line',
380 380 '"\C-u": unix-line-discard',
381 381 ], allow_none=False, config=True)
382 382
383 383 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none'],
384 384 default_value='last_expr', config=True,
385 385 help="""
386 386 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
387 387 run interactively (displaying output from expressions).""")
388 388
389 389 # TODO: this part of prompt management should be moved to the frontends.
390 390 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
391 391 separate_in = SeparateUnicode('\n', config=True)
392 392 separate_out = SeparateUnicode('', config=True)
393 393 separate_out2 = SeparateUnicode('', config=True)
394 394 wildcards_case_sensitive = CBool(True, config=True)
395 395 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
396 396 default_value='Context', config=True)
397 397
398 398 # Subcomponents of InteractiveShell
399 399 alias_manager = Instance('IPython.core.alias.AliasManager')
400 400 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
401 401 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
402 402 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
403 403 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
404 404 payload_manager = Instance('IPython.core.payload.PayloadManager')
405 405 history_manager = Instance('IPython.core.history.HistoryManager')
406 406 magics_manager = Instance('IPython.core.magic.MagicsManager')
407 407
408 408 profile_dir = Instance('IPython.core.application.ProfileDir')
409 409 @property
410 410 def profile(self):
411 411 if self.profile_dir is not None:
412 412 name = os.path.basename(self.profile_dir.location)
413 413 return name.replace('profile_','')
414 414
415 415
416 416 # Private interface
417 417 _post_execute = Instance(dict)
418 418
419 419 # Tracks any GUI loop loaded for pylab
420 420 pylab_gui_select = None
421 421
422 422 def __init__(self, ipython_dir=None, profile_dir=None,
423 423 user_module=None, user_ns=None,
424 424 custom_exceptions=((), None), **kwargs):
425 425
426 426 # This is where traits with a config_key argument are updated
427 427 # from the values on config.
428 428 super(InteractiveShell, self).__init__(**kwargs)
429 429 self.configurables = [self]
430 430
431 431 # These are relatively independent and stateless
432 432 self.init_ipython_dir(ipython_dir)
433 433 self.init_profile_dir(profile_dir)
434 434 self.init_instance_attrs()
435 435 self.init_environment()
436 436
437 437 # Check if we're in a virtualenv, and set up sys.path.
438 438 self.init_virtualenv()
439 439
440 440 # Create namespaces (user_ns, user_global_ns, etc.)
441 441 self.init_create_namespaces(user_module, user_ns)
442 442 # This has to be done after init_create_namespaces because it uses
443 443 # something in self.user_ns, but before init_sys_modules, which
444 444 # is the first thing to modify sys.
445 445 # TODO: When we override sys.stdout and sys.stderr before this class
446 446 # is created, we are saving the overridden ones here. Not sure if this
447 447 # is what we want to do.
448 448 self.save_sys_module_state()
449 449 self.init_sys_modules()
450 450
451 451 # While we're trying to have each part of the code directly access what
452 452 # it needs without keeping redundant references to objects, we have too
453 453 # much legacy code that expects ip.db to exist.
454 454 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
455 455
456 456 self.init_history()
457 457 self.init_encoding()
458 458 self.init_prefilter()
459 459
460 460 self.init_syntax_highlighting()
461 461 self.init_hooks()
462 462 self.init_pushd_popd_magic()
463 463 # self.init_traceback_handlers use to be here, but we moved it below
464 464 # because it and init_io have to come after init_readline.
465 465 self.init_user_ns()
466 466 self.init_logger()
467 467 self.init_alias()
468 468 self.init_builtins()
469 469
470 470 # The following was in post_config_initialization
471 471 self.init_inspector()
472 472 # init_readline() must come before init_io(), because init_io uses
473 473 # readline related things.
474 474 self.init_readline()
475 475 # We save this here in case user code replaces raw_input, but it needs
476 476 # to be after init_readline(), because PyPy's readline works by replacing
477 477 # raw_input.
478 478 if py3compat.PY3:
479 479 self.raw_input_original = input
480 480 else:
481 481 self.raw_input_original = raw_input
482 482 # init_completer must come after init_readline, because it needs to
483 483 # know whether readline is present or not system-wide to configure the
484 484 # completers, since the completion machinery can now operate
485 485 # independently of readline (e.g. over the network)
486 486 self.init_completer()
487 487 # TODO: init_io() needs to happen before init_traceback handlers
488 488 # because the traceback handlers hardcode the stdout/stderr streams.
489 489 # This logic in in debugger.Pdb and should eventually be changed.
490 490 self.init_io()
491 491 self.init_traceback_handlers(custom_exceptions)
492 492 self.init_prompts()
493 493 self.init_display_formatter()
494 494 self.init_display_pub()
495 495 self.init_data_pub()
496 496 self.init_displayhook()
497 497 self.init_latextool()
498 498 self.init_magics()
499 499 self.init_logstart()
500 500 self.init_pdb()
501 501 self.init_extension_manager()
502 502 self.init_payload()
503 503 self.hooks.late_startup_hook()
504 504 atexit.register(self.atexit_operations)
505 505
506 506 def get_ipython(self):
507 507 """Return the currently running IPython instance."""
508 508 return self
509 509
510 510 #-------------------------------------------------------------------------
511 511 # Trait changed handlers
512 512 #-------------------------------------------------------------------------
513 513
514 514 def _ipython_dir_changed(self, name, new):
515 515 if not os.path.isdir(new):
516 516 os.makedirs(new, mode = 0o777)
517 517
518 518 def set_autoindent(self,value=None):
519 519 """Set the autoindent flag, checking for readline support.
520 520
521 521 If called with no arguments, it acts as a toggle."""
522 522
523 523 if value != 0 and not self.has_readline:
524 524 if os.name == 'posix':
525 525 warn("The auto-indent feature requires the readline library")
526 526 self.autoindent = 0
527 527 return
528 528 if value is None:
529 529 self.autoindent = not self.autoindent
530 530 else:
531 531 self.autoindent = value
532 532
533 533 #-------------------------------------------------------------------------
534 534 # init_* methods called by __init__
535 535 #-------------------------------------------------------------------------
536 536
537 537 def init_ipython_dir(self, ipython_dir):
538 538 if ipython_dir is not None:
539 539 self.ipython_dir = ipython_dir
540 540 return
541 541
542 542 self.ipython_dir = get_ipython_dir()
543 543
544 544 def init_profile_dir(self, profile_dir):
545 545 if profile_dir is not None:
546 546 self.profile_dir = profile_dir
547 547 return
548 548 self.profile_dir =\
549 549 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
550 550
551 551 def init_instance_attrs(self):
552 552 self.more = False
553 553
554 554 # command compiler
555 555 self.compile = CachingCompiler()
556 556
557 557 # Make an empty namespace, which extension writers can rely on both
558 558 # existing and NEVER being used by ipython itself. This gives them a
559 559 # convenient location for storing additional information and state
560 560 # their extensions may require, without fear of collisions with other
561 561 # ipython names that may develop later.
562 562 self.meta = Struct()
563 563
564 564 # Temporary files used for various purposes. Deleted at exit.
565 565 self.tempfiles = []
566 566
567 567 # Keep track of readline usage (later set by init_readline)
568 568 self.has_readline = False
569 569
570 570 # keep track of where we started running (mainly for crash post-mortem)
571 571 # This is not being used anywhere currently.
572 572 self.starting_dir = os.getcwdu()
573 573
574 574 # Indentation management
575 575 self.indent_current_nsp = 0
576 576
577 577 # Dict to track post-execution functions that have been registered
578 578 self._post_execute = {}
579 579
580 580 def init_environment(self):
581 581 """Any changes we need to make to the user's environment."""
582 582 pass
583 583
584 584 def init_encoding(self):
585 585 # Get system encoding at startup time. Certain terminals (like Emacs
586 586 # under Win32 have it set to None, and we need to have a known valid
587 587 # encoding to use in the raw_input() method
588 588 try:
589 589 self.stdin_encoding = sys.stdin.encoding or 'ascii'
590 590 except AttributeError:
591 591 self.stdin_encoding = 'ascii'
592 592
593 593 def init_syntax_highlighting(self):
594 594 # Python source parser/formatter for syntax highlighting
595 595 pyformat = PyColorize.Parser().format
596 596 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
597 597
598 598 def init_pushd_popd_magic(self):
599 599 # for pushd/popd management
600 600 self.home_dir = get_home_dir()
601 601
602 602 self.dir_stack = []
603 603
604 604 def init_logger(self):
605 605 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
606 606 logmode='rotate')
607 607
608 608 def init_logstart(self):
609 609 """Initialize logging in case it was requested at the command line.
610 610 """
611 611 if self.logappend:
612 612 self.magic('logstart %s append' % self.logappend)
613 613 elif self.logfile:
614 614 self.magic('logstart %s' % self.logfile)
615 615 elif self.logstart:
616 616 self.magic('logstart')
617 617
618 618 def init_builtins(self):
619 619 # A single, static flag that we set to True. Its presence indicates
620 620 # that an IPython shell has been created, and we make no attempts at
621 621 # removing on exit or representing the existence of more than one
622 622 # IPython at a time.
623 623 builtin_mod.__dict__['__IPYTHON__'] = True
624 624
625 625 # In 0.11 we introduced '__IPYTHON__active' as an integer we'd try to
626 626 # manage on enter/exit, but with all our shells it's virtually
627 627 # impossible to get all the cases right. We're leaving the name in for
628 628 # those who adapted their codes to check for this flag, but will
629 629 # eventually remove it after a few more releases.
630 630 builtin_mod.__dict__['__IPYTHON__active'] = \
631 631 'Deprecated, check for __IPYTHON__'
632 632
633 633 self.builtin_trap = BuiltinTrap(shell=self)
634 634
635 635 def init_inspector(self):
636 636 # Object inspector
637 637 self.inspector = oinspect.Inspector(oinspect.InspectColors,
638 638 PyColorize.ANSICodeColors,
639 639 'NoColor',
640 640 self.object_info_string_level)
641 641
642 642 def init_io(self):
643 643 # This will just use sys.stdout and sys.stderr. If you want to
644 644 # override sys.stdout and sys.stderr themselves, you need to do that
645 645 # *before* instantiating this class, because io holds onto
646 646 # references to the underlying streams.
647 647 if (sys.platform == 'win32' or sys.platform == 'cli') and self.has_readline:
648 648 io.stdout = io.stderr = io.IOStream(self.readline._outputfile)
649 649 else:
650 650 io.stdout = io.IOStream(sys.stdout)
651 651 io.stderr = io.IOStream(sys.stderr)
652 652
653 653 def init_prompts(self):
654 654 self.prompt_manager = PromptManager(shell=self, parent=self)
655 655 self.configurables.append(self.prompt_manager)
656 656 # Set system prompts, so that scripts can decide if they are running
657 657 # interactively.
658 658 sys.ps1 = 'In : '
659 659 sys.ps2 = '...: '
660 660 sys.ps3 = 'Out: '
661 661
662 662 def init_display_formatter(self):
663 663 self.display_formatter = DisplayFormatter(parent=self)
664 664 self.configurables.append(self.display_formatter)
665 665
666 666 def init_display_pub(self):
667 667 self.display_pub = self.display_pub_class(parent=self)
668 668 self.configurables.append(self.display_pub)
669 669
670 670 def init_data_pub(self):
671 671 if not self.data_pub_class:
672 672 self.data_pub = None
673 673 return
674 674 self.data_pub = self.data_pub_class(parent=self)
675 675 self.configurables.append(self.data_pub)
676 676
677 677 def init_displayhook(self):
678 678 # Initialize displayhook, set in/out prompts and printing system
679 679 self.displayhook = self.displayhook_class(
680 680 parent=self,
681 681 shell=self,
682 682 cache_size=self.cache_size,
683 683 )
684 684 self.configurables.append(self.displayhook)
685 685 # This is a context manager that installs/revmoes the displayhook at
686 686 # the appropriate time.
687 687 self.display_trap = DisplayTrap(hook=self.displayhook)
688 688
689 689 def init_latextool(self):
690 690 """Configure LaTeXTool."""
691 691 cfg = LaTeXTool.instance(parent=self)
692 692 if cfg not in self.configurables:
693 693 self.configurables.append(cfg)
694 694
695 695 def init_virtualenv(self):
696 696 """Add a virtualenv to sys.path so the user can import modules from it.
697 697 This isn't perfect: it doesn't use the Python interpreter with which the
698 698 virtualenv was built, and it ignores the --no-site-packages option. A
699 699 warning will appear suggesting the user installs IPython in the
700 700 virtualenv, but for many cases, it probably works well enough.
701 701
702 702 Adapted from code snippets online.
703 703
704 704 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
705 705 """
706 706 if 'VIRTUAL_ENV' not in os.environ:
707 707 # Not in a virtualenv
708 708 return
709 709
710 710 if sys.executable.startswith(os.environ['VIRTUAL_ENV']):
711 711 # Running properly in the virtualenv, don't need to do anything
712 712 return
713 713
714 714 warn("Attempting to work in a virtualenv. If you encounter problems, please "
715 715 "install IPython inside the virtualenv.")
716 716 if sys.platform == "win32":
717 717 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
718 718 else:
719 719 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
720 720 'python%d.%d' % sys.version_info[:2], 'site-packages')
721 721
722 722 import site
723 723 sys.path.insert(0, virtual_env)
724 724 site.addsitedir(virtual_env)
725 725
726 726 #-------------------------------------------------------------------------
727 727 # Things related to injections into the sys module
728 728 #-------------------------------------------------------------------------
729 729
730 730 def save_sys_module_state(self):
731 731 """Save the state of hooks in the sys module.
732 732
733 733 This has to be called after self.user_module is created.
734 734 """
735 735 self._orig_sys_module_state = {}
736 736 self._orig_sys_module_state['stdin'] = sys.stdin
737 737 self._orig_sys_module_state['stdout'] = sys.stdout
738 738 self._orig_sys_module_state['stderr'] = sys.stderr
739 739 self._orig_sys_module_state['excepthook'] = sys.excepthook
740 740 self._orig_sys_modules_main_name = self.user_module.__name__
741 741 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
742 742
743 743 def restore_sys_module_state(self):
744 744 """Restore the state of the sys module."""
745 745 try:
746 746 for k, v in self._orig_sys_module_state.iteritems():
747 747 setattr(sys, k, v)
748 748 except AttributeError:
749 749 pass
750 750 # Reset what what done in self.init_sys_modules
751 751 if self._orig_sys_modules_main_mod is not None:
752 752 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
753 753
754 754 #-------------------------------------------------------------------------
755 755 # Things related to hooks
756 756 #-------------------------------------------------------------------------
757 757
758 758 def init_hooks(self):
759 759 # hooks holds pointers used for user-side customizations
760 760 self.hooks = Struct()
761 761
762 762 self.strdispatchers = {}
763 763
764 764 # Set all default hooks, defined in the IPython.hooks module.
765 765 hooks = IPython.core.hooks
766 766 for hook_name in hooks.__all__:
767 767 # default hooks have priority 100, i.e. low; user hooks should have
768 768 # 0-100 priority
769 769 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
770 770
771 771 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
772 772 """set_hook(name,hook) -> sets an internal IPython hook.
773 773
774 774 IPython exposes some of its internal API as user-modifiable hooks. By
775 775 adding your function to one of these hooks, you can modify IPython's
776 776 behavior to call at runtime your own routines."""
777 777
778 778 # At some point in the future, this should validate the hook before it
779 779 # accepts it. Probably at least check that the hook takes the number
780 780 # of args it's supposed to.
781 781
782 782 f = types.MethodType(hook,self)
783 783
784 784 # check if the hook is for strdispatcher first
785 785 if str_key is not None:
786 786 sdp = self.strdispatchers.get(name, StrDispatch())
787 787 sdp.add_s(str_key, f, priority )
788 788 self.strdispatchers[name] = sdp
789 789 return
790 790 if re_key is not None:
791 791 sdp = self.strdispatchers.get(name, StrDispatch())
792 792 sdp.add_re(re.compile(re_key), f, priority )
793 793 self.strdispatchers[name] = sdp
794 794 return
795 795
796 796 dp = getattr(self.hooks, name, None)
797 797 if name not in IPython.core.hooks.__all__:
798 798 print("Warning! Hook '%s' is not one of %s" % \
799 799 (name, IPython.core.hooks.__all__ ))
800 800 if not dp:
801 801 dp = IPython.core.hooks.CommandChainDispatcher()
802 802
803 803 try:
804 804 dp.add(f,priority)
805 805 except AttributeError:
806 806 # it was not commandchain, plain old func - replace
807 807 dp = f
808 808
809 809 setattr(self.hooks,name, dp)
810 810
811 811 def register_post_execute(self, func):
812 812 """Register a function for calling after code execution.
813 813 """
814 814 if not callable(func):
815 815 raise ValueError('argument %s must be callable' % func)
816 816 self._post_execute[func] = True
817 817
818 818 #-------------------------------------------------------------------------
819 819 # Things related to the "main" module
820 820 #-------------------------------------------------------------------------
821 821
822 def new_main_mod(self,ns=None):
822 def new_main_mod(self,filename):
823 823 """Return a new 'main' module object for user code execution.
824 """
825 main_mod = self._user_main_module
826 init_fakemod_dict(main_mod,ns)
827 return main_mod
828
829 def cache_main_mod(self,ns,fname):
830 """Cache a main module's namespace.
831
824
832 825 When scripts are executed via %run, we must keep a reference to the
833 826 namespace of their __main__ module (a FakeModule instance) around so
834 827 that Python doesn't clear it, rendering objects defined therein
835 828 useless.
836 829
837 830 This method keeps said reference in a private dict, keyed by the
838 831 absolute path of the module object (which corresponds to the script
839 832 path). This way, for multiple executions of the same script we only
840 833 keep one copy of the namespace (the last one), thus preventing memory
841 834 leaks from old references while allowing the objects from the last
842 835 execution to be accessible.
843
844 Note: we can not allow the actual FakeModule instances to be deleted,
845 because of how Python tears down modules (it hard-sets all their
846 references to None without regard for reference counts). This method
847 must therefore make a *copy* of the given namespace, to allow the
848 original module's __dict__ to be cleared and reused.
849
850
851 Parameters
852 ----------
853 ns : a namespace (a dict, typically)
854
855 fname : str
856 Filename associated with the namespace.
857
858 Examples
859 --------
860
861 In [10]: import IPython
862
863 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
864
865 In [12]: IPython.__file__ in _ip._main_ns_cache
866 Out[12]: True
867 836 """
868 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
837 filename = os.path.abspath(filename)
838 try:
839 main_mod = self._main_mod_cache[filename]
840 except KeyError:
841 main_mod = self._main_mod_cache[filename] = FakeModule()
842 else:
843 init_fakemod_dict(main_mod)
844
845 return main_mod
869 846
870 847 def clear_main_mod_cache(self):
871 848 """Clear the cache of main modules.
872 849
873 850 Mainly for use by utilities like %reset.
874 851
875 852 Examples
876 853 --------
877 854
878 855 In [15]: import IPython
879 856
880 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
857 In [16]: m = _ip.new_main_mod(IPython.__file__)
881 858
882 In [17]: len(_ip._main_ns_cache) > 0
859 In [17]: len(_ip._main_mod_cache) > 0
883 860 Out[17]: True
884 861
885 862 In [18]: _ip.clear_main_mod_cache()
886 863
887 In [19]: len(_ip._main_ns_cache) == 0
864 In [19]: len(_ip._main_mod_cache) == 0
888 865 Out[19]: True
889 866 """
890 self._main_ns_cache.clear()
867 self._main_mod_cache.clear()
891 868
892 869 #-------------------------------------------------------------------------
893 870 # Things related to debugging
894 871 #-------------------------------------------------------------------------
895 872
896 873 def init_pdb(self):
897 874 # Set calling of pdb on exceptions
898 875 # self.call_pdb is a property
899 876 self.call_pdb = self.pdb
900 877
901 878 def _get_call_pdb(self):
902 879 return self._call_pdb
903 880
904 881 def _set_call_pdb(self,val):
905 882
906 883 if val not in (0,1,False,True):
907 884 raise ValueError('new call_pdb value must be boolean')
908 885
909 886 # store value in instance
910 887 self._call_pdb = val
911 888
912 889 # notify the actual exception handlers
913 890 self.InteractiveTB.call_pdb = val
914 891
915 892 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
916 893 'Control auto-activation of pdb at exceptions')
917 894
918 895 def debugger(self,force=False):
919 896 """Call the pydb/pdb debugger.
920 897
921 898 Keywords:
922 899
923 900 - force(False): by default, this routine checks the instance call_pdb
924 901 flag and does not actually invoke the debugger if the flag is false.
925 902 The 'force' option forces the debugger to activate even if the flag
926 903 is false.
927 904 """
928 905
929 906 if not (force or self.call_pdb):
930 907 return
931 908
932 909 if not hasattr(sys,'last_traceback'):
933 910 error('No traceback has been produced, nothing to debug.')
934 911 return
935 912
936 913 # use pydb if available
937 914 if debugger.has_pydb:
938 915 from pydb import pm
939 916 else:
940 917 # fallback to our internal debugger
941 918 pm = lambda : self.InteractiveTB.debugger(force=True)
942 919
943 920 with self.readline_no_record:
944 921 pm()
945 922
946 923 #-------------------------------------------------------------------------
947 924 # Things related to IPython's various namespaces
948 925 #-------------------------------------------------------------------------
949 926 default_user_namespaces = True
950 927
951 928 def init_create_namespaces(self, user_module=None, user_ns=None):
952 929 # Create the namespace where the user will operate. user_ns is
953 930 # normally the only one used, and it is passed to the exec calls as
954 931 # the locals argument. But we do carry a user_global_ns namespace
955 932 # given as the exec 'globals' argument, This is useful in embedding
956 933 # situations where the ipython shell opens in a context where the
957 934 # distinction between locals and globals is meaningful. For
958 935 # non-embedded contexts, it is just the same object as the user_ns dict.
959 936
960 937 # FIXME. For some strange reason, __builtins__ is showing up at user
961 938 # level as a dict instead of a module. This is a manual fix, but I
962 939 # should really track down where the problem is coming from. Alex
963 940 # Schmolck reported this problem first.
964 941
965 942 # A useful post by Alex Martelli on this topic:
966 943 # Re: inconsistent value from __builtins__
967 944 # Von: Alex Martelli <aleaxit@yahoo.com>
968 945 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
969 946 # Gruppen: comp.lang.python
970 947
971 948 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
972 949 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
973 950 # > <type 'dict'>
974 951 # > >>> print type(__builtins__)
975 952 # > <type 'module'>
976 953 # > Is this difference in return value intentional?
977 954
978 955 # Well, it's documented that '__builtins__' can be either a dictionary
979 956 # or a module, and it's been that way for a long time. Whether it's
980 957 # intentional (or sensible), I don't know. In any case, the idea is
981 958 # that if you need to access the built-in namespace directly, you
982 959 # should start with "import __builtin__" (note, no 's') which will
983 960 # definitely give you a module. Yeah, it's somewhat confusing:-(.
984 961
985 962 # These routines return a properly built module and dict as needed by
986 963 # the rest of the code, and can also be used by extension writers to
987 964 # generate properly initialized namespaces.
988 965 if (user_ns is not None) or (user_module is not None):
989 966 self.default_user_namespaces = False
990 967 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
991 968
992 969 # A record of hidden variables we have added to the user namespace, so
993 970 # we can list later only variables defined in actual interactive use.
994 971 self.user_ns_hidden = set()
995 972
996 973 # Now that FakeModule produces a real module, we've run into a nasty
997 974 # problem: after script execution (via %run), the module where the user
998 975 # code ran is deleted. Now that this object is a true module (needed
999 976 # so docetst and other tools work correctly), the Python module
1000 977 # teardown mechanism runs over it, and sets to None every variable
1001 978 # present in that module. Top-level references to objects from the
1002 979 # script survive, because the user_ns is updated with them. However,
1003 980 # calling functions defined in the script that use other things from
1004 981 # the script will fail, because the function's closure had references
1005 982 # to the original objects, which are now all None. So we must protect
1006 983 # these modules from deletion by keeping a cache.
1007 984 #
1008 985 # To avoid keeping stale modules around (we only need the one from the
1009 986 # last run), we use a dict keyed with the full path to the script, so
1010 987 # only the last version of the module is held in the cache. Note,
1011 988 # however, that we must cache the module *namespace contents* (their
1012 989 # __dict__). Because if we try to cache the actual modules, old ones
1013 990 # (uncached) could be destroyed while still holding references (such as
1014 991 # those held by GUI objects that tend to be long-lived)>
1015 992 #
1016 993 # The %reset command will flush this cache. See the cache_main_mod()
1017 994 # and clear_main_mod_cache() methods for details on use.
1018 995
1019 996 # This is the cache used for 'main' namespaces
1020 self._main_ns_cache = {}
1021 # And this is the single instance of FakeModule whose __dict__ we keep
1022 # copying and clearing for reuse on each %run
1023 self._user_main_module = FakeModule()
997 self._main_mod_cache = {}
1024 998
1025 999 # A table holding all the namespaces IPython deals with, so that
1026 1000 # introspection facilities can search easily.
1027 1001 self.ns_table = {'user_global':self.user_module.__dict__,
1028 1002 'user_local':self.user_ns,
1029 1003 'builtin':builtin_mod.__dict__
1030 1004 }
1031 1005
1032 1006 @property
1033 1007 def user_global_ns(self):
1034 1008 return self.user_module.__dict__
1035 1009
1036 1010 def prepare_user_module(self, user_module=None, user_ns=None):
1037 1011 """Prepare the module and namespace in which user code will be run.
1038 1012
1039 1013 When IPython is started normally, both parameters are None: a new module
1040 1014 is created automatically, and its __dict__ used as the namespace.
1041 1015
1042 1016 If only user_module is provided, its __dict__ is used as the namespace.
1043 1017 If only user_ns is provided, a dummy module is created, and user_ns
1044 1018 becomes the global namespace. If both are provided (as they may be
1045 1019 when embedding), user_ns is the local namespace, and user_module
1046 1020 provides the global namespace.
1047 1021
1048 1022 Parameters
1049 1023 ----------
1050 1024 user_module : module, optional
1051 1025 The current user module in which IPython is being run. If None,
1052 1026 a clean module will be created.
1053 1027 user_ns : dict, optional
1054 1028 A namespace in which to run interactive commands.
1055 1029
1056 1030 Returns
1057 1031 -------
1058 1032 A tuple of user_module and user_ns, each properly initialised.
1059 1033 """
1060 1034 if user_module is None and user_ns is not None:
1061 1035 user_ns.setdefault("__name__", "__main__")
1062 1036 class DummyMod(object):
1063 1037 "A dummy module used for IPython's interactive namespace."
1064 1038 pass
1065 1039 user_module = DummyMod()
1066 1040 user_module.__dict__ = user_ns
1067 1041
1068 1042 if user_module is None:
1069 1043 user_module = types.ModuleType("__main__",
1070 1044 doc="Automatically created module for IPython interactive environment")
1071 1045
1072 1046 # We must ensure that __builtin__ (without the final 's') is always
1073 1047 # available and pointing to the __builtin__ *module*. For more details:
1074 1048 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1075 1049 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1076 1050 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1077 1051
1078 1052 if user_ns is None:
1079 1053 user_ns = user_module.__dict__
1080 1054
1081 1055 return user_module, user_ns
1082 1056
1083 1057 def init_sys_modules(self):
1084 1058 # We need to insert into sys.modules something that looks like a
1085 1059 # module but which accesses the IPython namespace, for shelve and
1086 1060 # pickle to work interactively. Normally they rely on getting
1087 1061 # everything out of __main__, but for embedding purposes each IPython
1088 1062 # instance has its own private namespace, so we can't go shoving
1089 1063 # everything into __main__.
1090 1064
1091 1065 # note, however, that we should only do this for non-embedded
1092 1066 # ipythons, which really mimic the __main__.__dict__ with their own
1093 1067 # namespace. Embedded instances, on the other hand, should not do
1094 1068 # this because they need to manage the user local/global namespaces
1095 1069 # only, but they live within a 'normal' __main__ (meaning, they
1096 1070 # shouldn't overtake the execution environment of the script they're
1097 1071 # embedded in).
1098 1072
1099 1073 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1100 1074 main_name = self.user_module.__name__
1101 1075 sys.modules[main_name] = self.user_module
1102 1076
1103 1077 def init_user_ns(self):
1104 1078 """Initialize all user-visible namespaces to their minimum defaults.
1105 1079
1106 1080 Certain history lists are also initialized here, as they effectively
1107 1081 act as user namespaces.
1108 1082
1109 1083 Notes
1110 1084 -----
1111 1085 All data structures here are only filled in, they are NOT reset by this
1112 1086 method. If they were not empty before, data will simply be added to
1113 1087 therm.
1114 1088 """
1115 1089 # This function works in two parts: first we put a few things in
1116 1090 # user_ns, and we sync that contents into user_ns_hidden so that these
1117 1091 # initial variables aren't shown by %who. After the sync, we add the
1118 1092 # rest of what we *do* want the user to see with %who even on a new
1119 1093 # session (probably nothing, so theye really only see their own stuff)
1120 1094
1121 1095 # The user dict must *always* have a __builtin__ reference to the
1122 1096 # Python standard __builtin__ namespace, which must be imported.
1123 1097 # This is so that certain operations in prompt evaluation can be
1124 1098 # reliably executed with builtins. Note that we can NOT use
1125 1099 # __builtins__ (note the 's'), because that can either be a dict or a
1126 1100 # module, and can even mutate at runtime, depending on the context
1127 1101 # (Python makes no guarantees on it). In contrast, __builtin__ is
1128 1102 # always a module object, though it must be explicitly imported.
1129 1103
1130 1104 # For more details:
1131 1105 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1132 1106 ns = dict()
1133 1107
1134 1108 # Put 'help' in the user namespace
1135 1109 try:
1136 1110 from site import _Helper
1137 1111 ns['help'] = _Helper()
1138 1112 except ImportError:
1139 1113 warn('help() not available - check site.py')
1140 1114
1141 1115 # make global variables for user access to the histories
1142 1116 ns['_ih'] = self.history_manager.input_hist_parsed
1143 1117 ns['_oh'] = self.history_manager.output_hist
1144 1118 ns['_dh'] = self.history_manager.dir_hist
1145 1119
1146 1120 ns['_sh'] = shadowns
1147 1121
1148 1122 # user aliases to input and output histories. These shouldn't show up
1149 1123 # in %who, as they can have very large reprs.
1150 1124 ns['In'] = self.history_manager.input_hist_parsed
1151 1125 ns['Out'] = self.history_manager.output_hist
1152 1126
1153 1127 # Store myself as the public api!!!
1154 1128 ns['get_ipython'] = self.get_ipython
1155 1129
1156 1130 ns['exit'] = self.exiter
1157 1131 ns['quit'] = self.exiter
1158 1132
1159 1133 # Sync what we've added so far to user_ns_hidden so these aren't seen
1160 1134 # by %who
1161 1135 self.user_ns_hidden.update(ns)
1162 1136
1163 1137 # Anything put into ns now would show up in %who. Think twice before
1164 1138 # putting anything here, as we really want %who to show the user their
1165 1139 # stuff, not our variables.
1166 1140
1167 1141 # Finally, update the real user's namespace
1168 1142 self.user_ns.update(ns)
1169 1143
1170 1144 @property
1171 1145 def all_ns_refs(self):
1172 1146 """Get a list of references to all the namespace dictionaries in which
1173 1147 IPython might store a user-created object.
1174 1148
1175 1149 Note that this does not include the displayhook, which also caches
1176 1150 objects from the output."""
1177 return [self.user_ns, self.user_global_ns,
1178 self._user_main_module.__dict__] + self._main_ns_cache.values()
1151 return [self.user_ns, self.user_global_ns] + \
1152 [m.__dict__ for m in self._main_mod_cache.values()]
1179 1153
1180 1154 def reset(self, new_session=True):
1181 1155 """Clear all internal namespaces, and attempt to release references to
1182 1156 user objects.
1183 1157
1184 1158 If new_session is True, a new history session will be opened.
1185 1159 """
1186 1160 # Clear histories
1187 1161 self.history_manager.reset(new_session)
1188 1162 # Reset counter used to index all histories
1189 1163 if new_session:
1190 1164 self.execution_count = 1
1191 1165
1192 1166 # Flush cached output items
1193 1167 if self.displayhook.do_full_cache:
1194 1168 self.displayhook.flush()
1195 1169
1196 1170 # The main execution namespaces must be cleared very carefully,
1197 1171 # skipping the deletion of the builtin-related keys, because doing so
1198 1172 # would cause errors in many object's __del__ methods.
1199 1173 if self.user_ns is not self.user_global_ns:
1200 1174 self.user_ns.clear()
1201 1175 ns = self.user_global_ns
1202 1176 drop_keys = set(ns.keys())
1203 1177 drop_keys.discard('__builtin__')
1204 1178 drop_keys.discard('__builtins__')
1205 1179 drop_keys.discard('__name__')
1206 1180 for k in drop_keys:
1207 1181 del ns[k]
1208 1182
1209 1183 self.user_ns_hidden.clear()
1210 1184
1211 1185 # Restore the user namespaces to minimal usability
1212 1186 self.init_user_ns()
1213 1187
1214 1188 # Restore the default and user aliases
1215 1189 self.alias_manager.clear_aliases()
1216 1190 self.alias_manager.init_aliases()
1217 1191
1218 1192 # Flush the private list of module references kept for script
1219 1193 # execution protection
1220 1194 self.clear_main_mod_cache()
1221 1195
1222 # Clear out the namespace from the last %run
1223 self.new_main_mod()
1224
1225 1196 def del_var(self, varname, by_name=False):
1226 1197 """Delete a variable from the various namespaces, so that, as
1227 1198 far as possible, we're not keeping any hidden references to it.
1228 1199
1229 1200 Parameters
1230 1201 ----------
1231 1202 varname : str
1232 1203 The name of the variable to delete.
1233 1204 by_name : bool
1234 1205 If True, delete variables with the given name in each
1235 1206 namespace. If False (default), find the variable in the user
1236 1207 namespace, and delete references to it.
1237 1208 """
1238 1209 if varname in ('__builtin__', '__builtins__'):
1239 1210 raise ValueError("Refusing to delete %s" % varname)
1240 1211
1241 1212 ns_refs = self.all_ns_refs
1242 1213
1243 1214 if by_name: # Delete by name
1244 1215 for ns in ns_refs:
1245 1216 try:
1246 1217 del ns[varname]
1247 1218 except KeyError:
1248 1219 pass
1249 1220 else: # Delete by object
1250 1221 try:
1251 1222 obj = self.user_ns[varname]
1252 1223 except KeyError:
1253 1224 raise NameError("name '%s' is not defined" % varname)
1254 1225 # Also check in output history
1255 1226 ns_refs.append(self.history_manager.output_hist)
1256 1227 for ns in ns_refs:
1257 1228 to_delete = [n for n, o in ns.iteritems() if o is obj]
1258 1229 for name in to_delete:
1259 1230 del ns[name]
1260 1231
1261 1232 # displayhook keeps extra references, but not in a dictionary
1262 1233 for name in ('_', '__', '___'):
1263 1234 if getattr(self.displayhook, name) is obj:
1264 1235 setattr(self.displayhook, name, None)
1265 1236
1266 1237 def reset_selective(self, regex=None):
1267 1238 """Clear selective variables from internal namespaces based on a
1268 1239 specified regular expression.
1269 1240
1270 1241 Parameters
1271 1242 ----------
1272 1243 regex : string or compiled pattern, optional
1273 1244 A regular expression pattern that will be used in searching
1274 1245 variable names in the users namespaces.
1275 1246 """
1276 1247 if regex is not None:
1277 1248 try:
1278 1249 m = re.compile(regex)
1279 1250 except TypeError:
1280 1251 raise TypeError('regex must be a string or compiled pattern')
1281 1252 # Search for keys in each namespace that match the given regex
1282 1253 # If a match is found, delete the key/value pair.
1283 1254 for ns in self.all_ns_refs:
1284 1255 for var in ns:
1285 1256 if m.search(var):
1286 1257 del ns[var]
1287 1258
1288 1259 def push(self, variables, interactive=True):
1289 1260 """Inject a group of variables into the IPython user namespace.
1290 1261
1291 1262 Parameters
1292 1263 ----------
1293 1264 variables : dict, str or list/tuple of str
1294 1265 The variables to inject into the user's namespace. If a dict, a
1295 1266 simple update is done. If a str, the string is assumed to have
1296 1267 variable names separated by spaces. A list/tuple of str can also
1297 1268 be used to give the variable names. If just the variable names are
1298 1269 give (list/tuple/str) then the variable values looked up in the
1299 1270 callers frame.
1300 1271 interactive : bool
1301 1272 If True (default), the variables will be listed with the ``who``
1302 1273 magic.
1303 1274 """
1304 1275 vdict = None
1305 1276
1306 1277 # We need a dict of name/value pairs to do namespace updates.
1307 1278 if isinstance(variables, dict):
1308 1279 vdict = variables
1309 1280 elif isinstance(variables, (basestring, list, tuple)):
1310 1281 if isinstance(variables, basestring):
1311 1282 vlist = variables.split()
1312 1283 else:
1313 1284 vlist = variables
1314 1285 vdict = {}
1315 1286 cf = sys._getframe(1)
1316 1287 for name in vlist:
1317 1288 try:
1318 1289 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1319 1290 except:
1320 1291 print('Could not get variable %s from %s' %
1321 1292 (name,cf.f_code.co_name))
1322 1293 else:
1323 1294 raise ValueError('variables must be a dict/str/list/tuple')
1324 1295
1325 1296 # Propagate variables to user namespace
1326 1297 self.user_ns.update(vdict)
1327 1298
1328 1299 # And configure interactive visibility
1329 1300 user_ns_hidden = self.user_ns_hidden
1330 1301 if interactive:
1331 1302 user_ns_hidden.difference_update(vdict)
1332 1303 else:
1333 1304 user_ns_hidden.update(vdict)
1334 1305
1335 1306 def drop_by_id(self, variables):
1336 1307 """Remove a dict of variables from the user namespace, if they are the
1337 1308 same as the values in the dictionary.
1338 1309
1339 1310 This is intended for use by extensions: variables that they've added can
1340 1311 be taken back out if they are unloaded, without removing any that the
1341 1312 user has overwritten.
1342 1313
1343 1314 Parameters
1344 1315 ----------
1345 1316 variables : dict
1346 1317 A dictionary mapping object names (as strings) to the objects.
1347 1318 """
1348 1319 for name, obj in variables.iteritems():
1349 1320 if name in self.user_ns and self.user_ns[name] is obj:
1350 1321 del self.user_ns[name]
1351 1322 self.user_ns_hidden.discard(name)
1352 1323
1353 1324 #-------------------------------------------------------------------------
1354 1325 # Things related to object introspection
1355 1326 #-------------------------------------------------------------------------
1356 1327
1357 1328 def _ofind(self, oname, namespaces=None):
1358 1329 """Find an object in the available namespaces.
1359 1330
1360 1331 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1361 1332
1362 1333 Has special code to detect magic functions.
1363 1334 """
1364 1335 oname = oname.strip()
1365 1336 #print '1- oname: <%r>' % oname # dbg
1366 1337 if not oname.startswith(ESC_MAGIC) and \
1367 1338 not oname.startswith(ESC_MAGIC2) and \
1368 1339 not py3compat.isidentifier(oname, dotted=True):
1369 1340 return dict(found=False)
1370 1341
1371 1342 alias_ns = None
1372 1343 if namespaces is None:
1373 1344 # Namespaces to search in:
1374 1345 # Put them in a list. The order is important so that we
1375 1346 # find things in the same order that Python finds them.
1376 1347 namespaces = [ ('Interactive', self.user_ns),
1377 1348 ('Interactive (global)', self.user_global_ns),
1378 1349 ('Python builtin', builtin_mod.__dict__),
1379 1350 ('Alias', self.alias_manager.alias_table),
1380 1351 ]
1381 1352 alias_ns = self.alias_manager.alias_table
1382 1353
1383 1354 # initialize results to 'null'
1384 1355 found = False; obj = None; ospace = None; ds = None;
1385 1356 ismagic = False; isalias = False; parent = None
1386 1357
1387 1358 # We need to special-case 'print', which as of python2.6 registers as a
1388 1359 # function but should only be treated as one if print_function was
1389 1360 # loaded with a future import. In this case, just bail.
1390 1361 if (oname == 'print' and not py3compat.PY3 and not \
1391 1362 (self.compile.compiler_flags & __future__.CO_FUTURE_PRINT_FUNCTION)):
1392 1363 return {'found':found, 'obj':obj, 'namespace':ospace,
1393 1364 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1394 1365
1395 1366 # Look for the given name by splitting it in parts. If the head is
1396 1367 # found, then we look for all the remaining parts as members, and only
1397 1368 # declare success if we can find them all.
1398 1369 oname_parts = oname.split('.')
1399 1370 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1400 1371 for nsname,ns in namespaces:
1401 1372 try:
1402 1373 obj = ns[oname_head]
1403 1374 except KeyError:
1404 1375 continue
1405 1376 else:
1406 1377 #print 'oname_rest:', oname_rest # dbg
1407 1378 for part in oname_rest:
1408 1379 try:
1409 1380 parent = obj
1410 1381 obj = getattr(obj,part)
1411 1382 except:
1412 1383 # Blanket except b/c some badly implemented objects
1413 1384 # allow __getattr__ to raise exceptions other than
1414 1385 # AttributeError, which then crashes IPython.
1415 1386 break
1416 1387 else:
1417 1388 # If we finish the for loop (no break), we got all members
1418 1389 found = True
1419 1390 ospace = nsname
1420 1391 if ns == alias_ns:
1421 1392 isalias = True
1422 1393 break # namespace loop
1423 1394
1424 1395 # Try to see if it's magic
1425 1396 if not found:
1426 1397 obj = None
1427 1398 if oname.startswith(ESC_MAGIC2):
1428 1399 oname = oname.lstrip(ESC_MAGIC2)
1429 1400 obj = self.find_cell_magic(oname)
1430 1401 elif oname.startswith(ESC_MAGIC):
1431 1402 oname = oname.lstrip(ESC_MAGIC)
1432 1403 obj = self.find_line_magic(oname)
1433 1404 else:
1434 1405 # search without prefix, so run? will find %run?
1435 1406 obj = self.find_line_magic(oname)
1436 1407 if obj is None:
1437 1408 obj = self.find_cell_magic(oname)
1438 1409 if obj is not None:
1439 1410 found = True
1440 1411 ospace = 'IPython internal'
1441 1412 ismagic = True
1442 1413
1443 1414 # Last try: special-case some literals like '', [], {}, etc:
1444 1415 if not found and oname_head in ["''",'""','[]','{}','()']:
1445 1416 obj = eval(oname_head)
1446 1417 found = True
1447 1418 ospace = 'Interactive'
1448 1419
1449 1420 return {'found':found, 'obj':obj, 'namespace':ospace,
1450 1421 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1451 1422
1452 1423 def _ofind_property(self, oname, info):
1453 1424 """Second part of object finding, to look for property details."""
1454 1425 if info.found:
1455 1426 # Get the docstring of the class property if it exists.
1456 1427 path = oname.split('.')
1457 1428 root = '.'.join(path[:-1])
1458 1429 if info.parent is not None:
1459 1430 try:
1460 1431 target = getattr(info.parent, '__class__')
1461 1432 # The object belongs to a class instance.
1462 1433 try:
1463 1434 target = getattr(target, path[-1])
1464 1435 # The class defines the object.
1465 1436 if isinstance(target, property):
1466 1437 oname = root + '.__class__.' + path[-1]
1467 1438 info = Struct(self._ofind(oname))
1468 1439 except AttributeError: pass
1469 1440 except AttributeError: pass
1470 1441
1471 1442 # We return either the new info or the unmodified input if the object
1472 1443 # hadn't been found
1473 1444 return info
1474 1445
1475 1446 def _object_find(self, oname, namespaces=None):
1476 1447 """Find an object and return a struct with info about it."""
1477 1448 inf = Struct(self._ofind(oname, namespaces))
1478 1449 return Struct(self._ofind_property(oname, inf))
1479 1450
1480 1451 def _inspect(self, meth, oname, namespaces=None, **kw):
1481 1452 """Generic interface to the inspector system.
1482 1453
1483 1454 This function is meant to be called by pdef, pdoc & friends."""
1484 1455 info = self._object_find(oname, namespaces)
1485 1456 if info.found:
1486 1457 pmethod = getattr(self.inspector, meth)
1487 1458 formatter = format_screen if info.ismagic else None
1488 1459 if meth == 'pdoc':
1489 1460 pmethod(info.obj, oname, formatter)
1490 1461 elif meth == 'pinfo':
1491 1462 pmethod(info.obj, oname, formatter, info, **kw)
1492 1463 else:
1493 1464 pmethod(info.obj, oname)
1494 1465 else:
1495 1466 print('Object `%s` not found.' % oname)
1496 1467 return 'not found' # so callers can take other action
1497 1468
1498 1469 def object_inspect(self, oname, detail_level=0):
1499 1470 with self.builtin_trap:
1500 1471 info = self._object_find(oname)
1501 1472 if info.found:
1502 1473 return self.inspector.info(info.obj, oname, info=info,
1503 1474 detail_level=detail_level
1504 1475 )
1505 1476 else:
1506 1477 return oinspect.object_info(name=oname, found=False)
1507 1478
1508 1479 #-------------------------------------------------------------------------
1509 1480 # Things related to history management
1510 1481 #-------------------------------------------------------------------------
1511 1482
1512 1483 def init_history(self):
1513 1484 """Sets up the command history, and starts regular autosaves."""
1514 1485 self.history_manager = HistoryManager(shell=self, parent=self)
1515 1486 self.configurables.append(self.history_manager)
1516 1487
1517 1488 #-------------------------------------------------------------------------
1518 1489 # Things related to exception handling and tracebacks (not debugging)
1519 1490 #-------------------------------------------------------------------------
1520 1491
1521 1492 def init_traceback_handlers(self, custom_exceptions):
1522 1493 # Syntax error handler.
1523 1494 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1524 1495
1525 1496 # The interactive one is initialized with an offset, meaning we always
1526 1497 # want to remove the topmost item in the traceback, which is our own
1527 1498 # internal code. Valid modes: ['Plain','Context','Verbose']
1528 1499 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1529 1500 color_scheme='NoColor',
1530 1501 tb_offset = 1,
1531 1502 check_cache=check_linecache_ipython)
1532 1503
1533 1504 # The instance will store a pointer to the system-wide exception hook,
1534 1505 # so that runtime code (such as magics) can access it. This is because
1535 1506 # during the read-eval loop, it may get temporarily overwritten.
1536 1507 self.sys_excepthook = sys.excepthook
1537 1508
1538 1509 # and add any custom exception handlers the user may have specified
1539 1510 self.set_custom_exc(*custom_exceptions)
1540 1511
1541 1512 # Set the exception mode
1542 1513 self.InteractiveTB.set_mode(mode=self.xmode)
1543 1514
1544 1515 def set_custom_exc(self, exc_tuple, handler):
1545 1516 """set_custom_exc(exc_tuple,handler)
1546 1517
1547 1518 Set a custom exception handler, which will be called if any of the
1548 1519 exceptions in exc_tuple occur in the mainloop (specifically, in the
1549 1520 run_code() method).
1550 1521
1551 1522 Parameters
1552 1523 ----------
1553 1524
1554 1525 exc_tuple : tuple of exception classes
1555 1526 A *tuple* of exception classes, for which to call the defined
1556 1527 handler. It is very important that you use a tuple, and NOT A
1557 1528 LIST here, because of the way Python's except statement works. If
1558 1529 you only want to trap a single exception, use a singleton tuple::
1559 1530
1560 1531 exc_tuple == (MyCustomException,)
1561 1532
1562 1533 handler : callable
1563 1534 handler must have the following signature::
1564 1535
1565 1536 def my_handler(self, etype, value, tb, tb_offset=None):
1566 1537 ...
1567 1538 return structured_traceback
1568 1539
1569 1540 Your handler must return a structured traceback (a list of strings),
1570 1541 or None.
1571 1542
1572 1543 This will be made into an instance method (via types.MethodType)
1573 1544 of IPython itself, and it will be called if any of the exceptions
1574 1545 listed in the exc_tuple are caught. If the handler is None, an
1575 1546 internal basic one is used, which just prints basic info.
1576 1547
1577 1548 To protect IPython from crashes, if your handler ever raises an
1578 1549 exception or returns an invalid result, it will be immediately
1579 1550 disabled.
1580 1551
1581 1552 WARNING: by putting in your own exception handler into IPython's main
1582 1553 execution loop, you run a very good chance of nasty crashes. This
1583 1554 facility should only be used if you really know what you are doing."""
1584 1555
1585 1556 assert type(exc_tuple)==type(()) , \
1586 1557 "The custom exceptions must be given AS A TUPLE."
1587 1558
1588 1559 def dummy_handler(self,etype,value,tb,tb_offset=None):
1589 1560 print('*** Simple custom exception handler ***')
1590 1561 print('Exception type :',etype)
1591 1562 print('Exception value:',value)
1592 1563 print('Traceback :',tb)
1593 1564 #print 'Source code :','\n'.join(self.buffer)
1594 1565
1595 1566 def validate_stb(stb):
1596 1567 """validate structured traceback return type
1597 1568
1598 1569 return type of CustomTB *should* be a list of strings, but allow
1599 1570 single strings or None, which are harmless.
1600 1571
1601 1572 This function will *always* return a list of strings,
1602 1573 and will raise a TypeError if stb is inappropriate.
1603 1574 """
1604 1575 msg = "CustomTB must return list of strings, not %r" % stb
1605 1576 if stb is None:
1606 1577 return []
1607 1578 elif isinstance(stb, basestring):
1608 1579 return [stb]
1609 1580 elif not isinstance(stb, list):
1610 1581 raise TypeError(msg)
1611 1582 # it's a list
1612 1583 for line in stb:
1613 1584 # check every element
1614 1585 if not isinstance(line, basestring):
1615 1586 raise TypeError(msg)
1616 1587 return stb
1617 1588
1618 1589 if handler is None:
1619 1590 wrapped = dummy_handler
1620 1591 else:
1621 1592 def wrapped(self,etype,value,tb,tb_offset=None):
1622 1593 """wrap CustomTB handler, to protect IPython from user code
1623 1594
1624 1595 This makes it harder (but not impossible) for custom exception
1625 1596 handlers to crash IPython.
1626 1597 """
1627 1598 try:
1628 1599 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1629 1600 return validate_stb(stb)
1630 1601 except:
1631 1602 # clear custom handler immediately
1632 1603 self.set_custom_exc((), None)
1633 1604 print("Custom TB Handler failed, unregistering", file=io.stderr)
1634 1605 # show the exception in handler first
1635 1606 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1636 1607 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1637 1608 print("The original exception:", file=io.stdout)
1638 1609 stb = self.InteractiveTB.structured_traceback(
1639 1610 (etype,value,tb), tb_offset=tb_offset
1640 1611 )
1641 1612 return stb
1642 1613
1643 1614 self.CustomTB = types.MethodType(wrapped,self)
1644 1615 self.custom_exceptions = exc_tuple
1645 1616
1646 1617 def excepthook(self, etype, value, tb):
1647 1618 """One more defense for GUI apps that call sys.excepthook.
1648 1619
1649 1620 GUI frameworks like wxPython trap exceptions and call
1650 1621 sys.excepthook themselves. I guess this is a feature that
1651 1622 enables them to keep running after exceptions that would
1652 1623 otherwise kill their mainloop. This is a bother for IPython
1653 1624 which excepts to catch all of the program exceptions with a try:
1654 1625 except: statement.
1655 1626
1656 1627 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1657 1628 any app directly invokes sys.excepthook, it will look to the user like
1658 1629 IPython crashed. In order to work around this, we can disable the
1659 1630 CrashHandler and replace it with this excepthook instead, which prints a
1660 1631 regular traceback using our InteractiveTB. In this fashion, apps which
1661 1632 call sys.excepthook will generate a regular-looking exception from
1662 1633 IPython, and the CrashHandler will only be triggered by real IPython
1663 1634 crashes.
1664 1635
1665 1636 This hook should be used sparingly, only in places which are not likely
1666 1637 to be true IPython errors.
1667 1638 """
1668 1639 self.showtraceback((etype,value,tb),tb_offset=0)
1669 1640
1670 1641 def _get_exc_info(self, exc_tuple=None):
1671 1642 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1672 1643
1673 1644 Ensures sys.last_type,value,traceback hold the exc_info we found,
1674 1645 from whichever source.
1675 1646
1676 1647 raises ValueError if none of these contain any information
1677 1648 """
1678 1649 if exc_tuple is None:
1679 1650 etype, value, tb = sys.exc_info()
1680 1651 else:
1681 1652 etype, value, tb = exc_tuple
1682 1653
1683 1654 if etype is None:
1684 1655 if hasattr(sys, 'last_type'):
1685 1656 etype, value, tb = sys.last_type, sys.last_value, \
1686 1657 sys.last_traceback
1687 1658
1688 1659 if etype is None:
1689 1660 raise ValueError("No exception to find")
1690 1661
1691 1662 # Now store the exception info in sys.last_type etc.
1692 1663 # WARNING: these variables are somewhat deprecated and not
1693 1664 # necessarily safe to use in a threaded environment, but tools
1694 1665 # like pdb depend on their existence, so let's set them. If we
1695 1666 # find problems in the field, we'll need to revisit their use.
1696 1667 sys.last_type = etype
1697 1668 sys.last_value = value
1698 1669 sys.last_traceback = tb
1699 1670
1700 1671 return etype, value, tb
1701 1672
1702 1673
1703 1674 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1704 1675 exception_only=False):
1705 1676 """Display the exception that just occurred.
1706 1677
1707 1678 If nothing is known about the exception, this is the method which
1708 1679 should be used throughout the code for presenting user tracebacks,
1709 1680 rather than directly invoking the InteractiveTB object.
1710 1681
1711 1682 A specific showsyntaxerror() also exists, but this method can take
1712 1683 care of calling it if needed, so unless you are explicitly catching a
1713 1684 SyntaxError exception, don't try to analyze the stack manually and
1714 1685 simply call this method."""
1715 1686
1716 1687 try:
1717 1688 try:
1718 1689 etype, value, tb = self._get_exc_info(exc_tuple)
1719 1690 except ValueError:
1720 1691 self.write_err('No traceback available to show.\n')
1721 1692 return
1722 1693
1723 1694 if issubclass(etype, SyntaxError):
1724 1695 # Though this won't be called by syntax errors in the input
1725 1696 # line, there may be SyntaxError cases with imported code.
1726 1697 self.showsyntaxerror(filename)
1727 1698 elif etype is UsageError:
1728 1699 self.write_err("UsageError: %s" % value)
1729 1700 else:
1730 1701 if exception_only:
1731 1702 stb = ['An exception has occurred, use %tb to see '
1732 1703 'the full traceback.\n']
1733 1704 stb.extend(self.InteractiveTB.get_exception_only(etype,
1734 1705 value))
1735 1706 else:
1736 1707 try:
1737 1708 # Exception classes can customise their traceback - we
1738 1709 # use this in IPython.parallel for exceptions occurring
1739 1710 # in the engines. This should return a list of strings.
1740 1711 stb = value._render_traceback_()
1741 1712 except Exception:
1742 1713 stb = self.InteractiveTB.structured_traceback(etype,
1743 1714 value, tb, tb_offset=tb_offset)
1744 1715
1745 1716 self._showtraceback(etype, value, stb)
1746 1717 if self.call_pdb:
1747 1718 # drop into debugger
1748 1719 self.debugger(force=True)
1749 1720 return
1750 1721
1751 1722 # Actually show the traceback
1752 1723 self._showtraceback(etype, value, stb)
1753 1724
1754 1725 except KeyboardInterrupt:
1755 1726 self.write_err("\nKeyboardInterrupt\n")
1756 1727
1757 1728 def _showtraceback(self, etype, evalue, stb):
1758 1729 """Actually show a traceback.
1759 1730
1760 1731 Subclasses may override this method to put the traceback on a different
1761 1732 place, like a side channel.
1762 1733 """
1763 1734 print(self.InteractiveTB.stb2text(stb), file=io.stdout)
1764 1735
1765 1736 def showsyntaxerror(self, filename=None):
1766 1737 """Display the syntax error that just occurred.
1767 1738
1768 1739 This doesn't display a stack trace because there isn't one.
1769 1740
1770 1741 If a filename is given, it is stuffed in the exception instead
1771 1742 of what was there before (because Python's parser always uses
1772 1743 "<string>" when reading from a string).
1773 1744 """
1774 1745 etype, value, last_traceback = self._get_exc_info()
1775 1746
1776 1747 if filename and issubclass(etype, SyntaxError):
1777 1748 try:
1778 1749 value.filename = filename
1779 1750 except:
1780 1751 # Not the format we expect; leave it alone
1781 1752 pass
1782 1753
1783 1754 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1784 1755 self._showtraceback(etype, value, stb)
1785 1756
1786 1757 # This is overridden in TerminalInteractiveShell to show a message about
1787 1758 # the %paste magic.
1788 1759 def showindentationerror(self):
1789 1760 """Called by run_cell when there's an IndentationError in code entered
1790 1761 at the prompt.
1791 1762
1792 1763 This is overridden in TerminalInteractiveShell to show a message about
1793 1764 the %paste magic."""
1794 1765 self.showsyntaxerror()
1795 1766
1796 1767 #-------------------------------------------------------------------------
1797 1768 # Things related to readline
1798 1769 #-------------------------------------------------------------------------
1799 1770
1800 1771 def init_readline(self):
1801 1772 """Command history completion/saving/reloading."""
1802 1773
1803 1774 if self.readline_use:
1804 1775 import IPython.utils.rlineimpl as readline
1805 1776
1806 1777 self.rl_next_input = None
1807 1778 self.rl_do_indent = False
1808 1779
1809 1780 if not self.readline_use or not readline.have_readline:
1810 1781 self.has_readline = False
1811 1782 self.readline = None
1812 1783 # Set a number of methods that depend on readline to be no-op
1813 1784 self.readline_no_record = no_op_context
1814 1785 self.set_readline_completer = no_op
1815 1786 self.set_custom_completer = no_op
1816 1787 if self.readline_use:
1817 1788 warn('Readline services not available or not loaded.')
1818 1789 else:
1819 1790 self.has_readline = True
1820 1791 self.readline = readline
1821 1792 sys.modules['readline'] = readline
1822 1793
1823 1794 # Platform-specific configuration
1824 1795 if os.name == 'nt':
1825 1796 # FIXME - check with Frederick to see if we can harmonize
1826 1797 # naming conventions with pyreadline to avoid this
1827 1798 # platform-dependent check
1828 1799 self.readline_startup_hook = readline.set_pre_input_hook
1829 1800 else:
1830 1801 self.readline_startup_hook = readline.set_startup_hook
1831 1802
1832 1803 # Load user's initrc file (readline config)
1833 1804 # Or if libedit is used, load editrc.
1834 1805 inputrc_name = os.environ.get('INPUTRC')
1835 1806 if inputrc_name is None:
1836 1807 inputrc_name = '.inputrc'
1837 1808 if readline.uses_libedit:
1838 1809 inputrc_name = '.editrc'
1839 1810 inputrc_name = os.path.join(self.home_dir, inputrc_name)
1840 1811 if os.path.isfile(inputrc_name):
1841 1812 try:
1842 1813 readline.read_init_file(inputrc_name)
1843 1814 except:
1844 1815 warn('Problems reading readline initialization file <%s>'
1845 1816 % inputrc_name)
1846 1817
1847 1818 # Configure readline according to user's prefs
1848 1819 # This is only done if GNU readline is being used. If libedit
1849 1820 # is being used (as on Leopard) the readline config is
1850 1821 # not run as the syntax for libedit is different.
1851 1822 if not readline.uses_libedit:
1852 1823 for rlcommand in self.readline_parse_and_bind:
1853 1824 #print "loading rl:",rlcommand # dbg
1854 1825 readline.parse_and_bind(rlcommand)
1855 1826
1856 1827 # Remove some chars from the delimiters list. If we encounter
1857 1828 # unicode chars, discard them.
1858 1829 delims = readline.get_completer_delims()
1859 1830 if not py3compat.PY3:
1860 1831 delims = delims.encode("ascii", "ignore")
1861 1832 for d in self.readline_remove_delims:
1862 1833 delims = delims.replace(d, "")
1863 1834 delims = delims.replace(ESC_MAGIC, '')
1864 1835 readline.set_completer_delims(delims)
1865 1836 # Store these so we can restore them if something like rpy2 modifies
1866 1837 # them.
1867 1838 self.readline_delims = delims
1868 1839 # otherwise we end up with a monster history after a while:
1869 1840 readline.set_history_length(self.history_length)
1870 1841
1871 1842 self.refill_readline_hist()
1872 1843 self.readline_no_record = ReadlineNoRecord(self)
1873 1844
1874 1845 # Configure auto-indent for all platforms
1875 1846 self.set_autoindent(self.autoindent)
1876 1847
1877 1848 def refill_readline_hist(self):
1878 1849 # Load the last 1000 lines from history
1879 1850 self.readline.clear_history()
1880 1851 stdin_encoding = sys.stdin.encoding or "utf-8"
1881 1852 last_cell = u""
1882 1853 for _, _, cell in self.history_manager.get_tail(1000,
1883 1854 include_latest=True):
1884 1855 # Ignore blank lines and consecutive duplicates
1885 1856 cell = cell.rstrip()
1886 1857 if cell and (cell != last_cell):
1887 1858 if self.multiline_history:
1888 1859 self.readline.add_history(py3compat.unicode_to_str(cell,
1889 1860 stdin_encoding))
1890 1861 else:
1891 1862 for line in cell.splitlines():
1892 1863 self.readline.add_history(py3compat.unicode_to_str(line,
1893 1864 stdin_encoding))
1894 1865 last_cell = cell
1895 1866
1896 1867 @skip_doctest
1897 1868 def set_next_input(self, s):
1898 1869 """ Sets the 'default' input string for the next command line.
1899 1870
1900 1871 Requires readline.
1901 1872
1902 1873 Example::
1903 1874
1904 1875 In [1]: _ip.set_next_input("Hello Word")
1905 1876 In [2]: Hello Word_ # cursor is here
1906 1877 """
1907 1878 self.rl_next_input = py3compat.cast_bytes_py2(s)
1908 1879
1909 1880 # Maybe move this to the terminal subclass?
1910 1881 def pre_readline(self):
1911 1882 """readline hook to be used at the start of each line.
1912 1883
1913 1884 Currently it handles auto-indent only."""
1914 1885
1915 1886 if self.rl_do_indent:
1916 1887 self.readline.insert_text(self._indent_current_str())
1917 1888 if self.rl_next_input is not None:
1918 1889 self.readline.insert_text(self.rl_next_input)
1919 1890 self.rl_next_input = None
1920 1891
1921 1892 def _indent_current_str(self):
1922 1893 """return the current level of indentation as a string"""
1923 1894 return self.input_splitter.indent_spaces * ' '
1924 1895
1925 1896 #-------------------------------------------------------------------------
1926 1897 # Things related to text completion
1927 1898 #-------------------------------------------------------------------------
1928 1899
1929 1900 def init_completer(self):
1930 1901 """Initialize the completion machinery.
1931 1902
1932 1903 This creates completion machinery that can be used by client code,
1933 1904 either interactively in-process (typically triggered by the readline
1934 1905 library), programatically (such as in test suites) or out-of-prcess
1935 1906 (typically over the network by remote frontends).
1936 1907 """
1937 1908 from IPython.core.completer import IPCompleter
1938 1909 from IPython.core.completerlib import (module_completer,
1939 1910 magic_run_completer, cd_completer, reset_completer)
1940 1911
1941 1912 self.Completer = IPCompleter(shell=self,
1942 1913 namespace=self.user_ns,
1943 1914 global_namespace=self.user_global_ns,
1944 1915 alias_table=self.alias_manager.alias_table,
1945 1916 use_readline=self.has_readline,
1946 1917 parent=self,
1947 1918 )
1948 1919 self.configurables.append(self.Completer)
1949 1920
1950 1921 # Add custom completers to the basic ones built into IPCompleter
1951 1922 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1952 1923 self.strdispatchers['complete_command'] = sdisp
1953 1924 self.Completer.custom_completers = sdisp
1954 1925
1955 1926 self.set_hook('complete_command', module_completer, str_key = 'import')
1956 1927 self.set_hook('complete_command', module_completer, str_key = 'from')
1957 1928 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1958 1929 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1959 1930 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1960 1931
1961 1932 # Only configure readline if we truly are using readline. IPython can
1962 1933 # do tab-completion over the network, in GUIs, etc, where readline
1963 1934 # itself may be absent
1964 1935 if self.has_readline:
1965 1936 self.set_readline_completer()
1966 1937
1967 1938 def complete(self, text, line=None, cursor_pos=None):
1968 1939 """Return the completed text and a list of completions.
1969 1940
1970 1941 Parameters
1971 1942 ----------
1972 1943
1973 1944 text : string
1974 1945 A string of text to be completed on. It can be given as empty and
1975 1946 instead a line/position pair are given. In this case, the
1976 1947 completer itself will split the line like readline does.
1977 1948
1978 1949 line : string, optional
1979 1950 The complete line that text is part of.
1980 1951
1981 1952 cursor_pos : int, optional
1982 1953 The position of the cursor on the input line.
1983 1954
1984 1955 Returns
1985 1956 -------
1986 1957 text : string
1987 1958 The actual text that was completed.
1988 1959
1989 1960 matches : list
1990 1961 A sorted list with all possible completions.
1991 1962
1992 1963 The optional arguments allow the completion to take more context into
1993 1964 account, and are part of the low-level completion API.
1994 1965
1995 1966 This is a wrapper around the completion mechanism, similar to what
1996 1967 readline does at the command line when the TAB key is hit. By
1997 1968 exposing it as a method, it can be used by other non-readline
1998 1969 environments (such as GUIs) for text completion.
1999 1970
2000 1971 Simple usage example:
2001 1972
2002 1973 In [1]: x = 'hello'
2003 1974
2004 1975 In [2]: _ip.complete('x.l')
2005 1976 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
2006 1977 """
2007 1978
2008 1979 # Inject names into __builtin__ so we can complete on the added names.
2009 1980 with self.builtin_trap:
2010 1981 return self.Completer.complete(text, line, cursor_pos)
2011 1982
2012 1983 def set_custom_completer(self, completer, pos=0):
2013 1984 """Adds a new custom completer function.
2014 1985
2015 1986 The position argument (defaults to 0) is the index in the completers
2016 1987 list where you want the completer to be inserted."""
2017 1988
2018 1989 newcomp = types.MethodType(completer,self.Completer)
2019 1990 self.Completer.matchers.insert(pos,newcomp)
2020 1991
2021 1992 def set_readline_completer(self):
2022 1993 """Reset readline's completer to be our own."""
2023 1994 self.readline.set_completer(self.Completer.rlcomplete)
2024 1995
2025 1996 def set_completer_frame(self, frame=None):
2026 1997 """Set the frame of the completer."""
2027 1998 if frame:
2028 1999 self.Completer.namespace = frame.f_locals
2029 2000 self.Completer.global_namespace = frame.f_globals
2030 2001 else:
2031 2002 self.Completer.namespace = self.user_ns
2032 2003 self.Completer.global_namespace = self.user_global_ns
2033 2004
2034 2005 #-------------------------------------------------------------------------
2035 2006 # Things related to magics
2036 2007 #-------------------------------------------------------------------------
2037 2008
2038 2009 def init_magics(self):
2039 2010 from IPython.core import magics as m
2040 2011 self.magics_manager = magic.MagicsManager(shell=self,
2041 2012 parent=self,
2042 2013 user_magics=m.UserMagics(self))
2043 2014 self.configurables.append(self.magics_manager)
2044 2015
2045 2016 # Expose as public API from the magics manager
2046 2017 self.register_magics = self.magics_manager.register
2047 2018 self.register_magic_function = self.magics_manager.register_function
2048 2019 self.define_magic = self.magics_manager.define_magic
2049 2020
2050 2021 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2051 2022 m.ConfigMagics, m.DeprecatedMagics, m.DisplayMagics, m.ExecutionMagics,
2052 2023 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2053 2024 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2054 2025 )
2055 2026
2056 2027 # Register Magic Aliases
2057 2028 mman = self.magics_manager
2058 2029 # FIXME: magic aliases should be defined by the Magics classes
2059 2030 # or in MagicsManager, not here
2060 2031 mman.register_alias('ed', 'edit')
2061 2032 mman.register_alias('hist', 'history')
2062 2033 mman.register_alias('rep', 'recall')
2063 2034 mman.register_alias('SVG', 'svg', 'cell')
2064 2035 mman.register_alias('HTML', 'html', 'cell')
2065 2036 mman.register_alias('file', 'writefile', 'cell')
2066 2037
2067 2038 # FIXME: Move the color initialization to the DisplayHook, which
2068 2039 # should be split into a prompt manager and displayhook. We probably
2069 2040 # even need a centralize colors management object.
2070 2041 self.magic('colors %s' % self.colors)
2071 2042
2072 2043 def run_line_magic(self, magic_name, line):
2073 2044 """Execute the given line magic.
2074 2045
2075 2046 Parameters
2076 2047 ----------
2077 2048 magic_name : str
2078 2049 Name of the desired magic function, without '%' prefix.
2079 2050
2080 2051 line : str
2081 2052 The rest of the input line as a single string.
2082 2053 """
2083 2054 fn = self.find_line_magic(magic_name)
2084 2055 if fn is None:
2085 2056 cm = self.find_cell_magic(magic_name)
2086 2057 etpl = "Line magic function `%%%s` not found%s."
2087 2058 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2088 2059 'did you mean that instead?)' % magic_name )
2089 2060 error(etpl % (magic_name, extra))
2090 2061 else:
2091 2062 # Note: this is the distance in the stack to the user's frame.
2092 2063 # This will need to be updated if the internal calling logic gets
2093 2064 # refactored, or else we'll be expanding the wrong variables.
2094 2065 stack_depth = 2
2095 2066 magic_arg_s = self.var_expand(line, stack_depth)
2096 2067 # Put magic args in a list so we can call with f(*a) syntax
2097 2068 args = [magic_arg_s]
2098 2069 kwargs = {}
2099 2070 # Grab local namespace if we need it:
2100 2071 if getattr(fn, "needs_local_scope", False):
2101 2072 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2102 2073 with self.builtin_trap:
2103 2074 result = fn(*args,**kwargs)
2104 2075 return result
2105 2076
2106 2077 def run_cell_magic(self, magic_name, line, cell):
2107 2078 """Execute the given cell magic.
2108 2079
2109 2080 Parameters
2110 2081 ----------
2111 2082 magic_name : str
2112 2083 Name of the desired magic function, without '%' prefix.
2113 2084
2114 2085 line : str
2115 2086 The rest of the first input line as a single string.
2116 2087
2117 2088 cell : str
2118 2089 The body of the cell as a (possibly multiline) string.
2119 2090 """
2120 2091 fn = self.find_cell_magic(magic_name)
2121 2092 if fn is None:
2122 2093 lm = self.find_line_magic(magic_name)
2123 2094 etpl = "Cell magic `%%{0}` not found{1}."
2124 2095 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2125 2096 'did you mean that instead?)'.format(magic_name))
2126 2097 error(etpl.format(magic_name, extra))
2127 2098 elif cell == '':
2128 2099 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2129 2100 if self.find_line_magic(magic_name) is not None:
2130 2101 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2131 2102 raise UsageError(message)
2132 2103 else:
2133 2104 # Note: this is the distance in the stack to the user's frame.
2134 2105 # This will need to be updated if the internal calling logic gets
2135 2106 # refactored, or else we'll be expanding the wrong variables.
2136 2107 stack_depth = 2
2137 2108 magic_arg_s = self.var_expand(line, stack_depth)
2138 2109 with self.builtin_trap:
2139 2110 result = fn(magic_arg_s, cell)
2140 2111 return result
2141 2112
2142 2113 def find_line_magic(self, magic_name):
2143 2114 """Find and return a line magic by name.
2144 2115
2145 2116 Returns None if the magic isn't found."""
2146 2117 return self.magics_manager.magics['line'].get(magic_name)
2147 2118
2148 2119 def find_cell_magic(self, magic_name):
2149 2120 """Find and return a cell magic by name.
2150 2121
2151 2122 Returns None if the magic isn't found."""
2152 2123 return self.magics_manager.magics['cell'].get(magic_name)
2153 2124
2154 2125 def find_magic(self, magic_name, magic_kind='line'):
2155 2126 """Find and return a magic of the given type by name.
2156 2127
2157 2128 Returns None if the magic isn't found."""
2158 2129 return self.magics_manager.magics[magic_kind].get(magic_name)
2159 2130
2160 2131 def magic(self, arg_s):
2161 2132 """DEPRECATED. Use run_line_magic() instead.
2162 2133
2163 2134 Call a magic function by name.
2164 2135
2165 2136 Input: a string containing the name of the magic function to call and
2166 2137 any additional arguments to be passed to the magic.
2167 2138
2168 2139 magic('name -opt foo bar') is equivalent to typing at the ipython
2169 2140 prompt:
2170 2141
2171 2142 In[1]: %name -opt foo bar
2172 2143
2173 2144 To call a magic without arguments, simply use magic('name').
2174 2145
2175 2146 This provides a proper Python function to call IPython's magics in any
2176 2147 valid Python code you can type at the interpreter, including loops and
2177 2148 compound statements.
2178 2149 """
2179 2150 # TODO: should we issue a loud deprecation warning here?
2180 2151 magic_name, _, magic_arg_s = arg_s.partition(' ')
2181 2152 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2182 2153 return self.run_line_magic(magic_name, magic_arg_s)
2183 2154
2184 2155 #-------------------------------------------------------------------------
2185 2156 # Things related to macros
2186 2157 #-------------------------------------------------------------------------
2187 2158
2188 2159 def define_macro(self, name, themacro):
2189 2160 """Define a new macro
2190 2161
2191 2162 Parameters
2192 2163 ----------
2193 2164 name : str
2194 2165 The name of the macro.
2195 2166 themacro : str or Macro
2196 2167 The action to do upon invoking the macro. If a string, a new
2197 2168 Macro object is created by passing the string to it.
2198 2169 """
2199 2170
2200 2171 from IPython.core import macro
2201 2172
2202 2173 if isinstance(themacro, basestring):
2203 2174 themacro = macro.Macro(themacro)
2204 2175 if not isinstance(themacro, macro.Macro):
2205 2176 raise ValueError('A macro must be a string or a Macro instance.')
2206 2177 self.user_ns[name] = themacro
2207 2178
2208 2179 #-------------------------------------------------------------------------
2209 2180 # Things related to the running of system commands
2210 2181 #-------------------------------------------------------------------------
2211 2182
2212 2183 def system_piped(self, cmd):
2213 2184 """Call the given cmd in a subprocess, piping stdout/err
2214 2185
2215 2186 Parameters
2216 2187 ----------
2217 2188 cmd : str
2218 2189 Command to execute (can not end in '&', as background processes are
2219 2190 not supported. Should not be a command that expects input
2220 2191 other than simple text.
2221 2192 """
2222 2193 if cmd.rstrip().endswith('&'):
2223 2194 # this is *far* from a rigorous test
2224 2195 # We do not support backgrounding processes because we either use
2225 2196 # pexpect or pipes to read from. Users can always just call
2226 2197 # os.system() or use ip.system=ip.system_raw
2227 2198 # if they really want a background process.
2228 2199 raise OSError("Background processes not supported.")
2229 2200
2230 2201 # we explicitly do NOT return the subprocess status code, because
2231 2202 # a non-None value would trigger :func:`sys.displayhook` calls.
2232 2203 # Instead, we store the exit_code in user_ns.
2233 2204 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2234 2205
2235 2206 def system_raw(self, cmd):
2236 2207 """Call the given cmd in a subprocess using os.system
2237 2208
2238 2209 Parameters
2239 2210 ----------
2240 2211 cmd : str
2241 2212 Command to execute.
2242 2213 """
2243 2214 cmd = self.var_expand(cmd, depth=1)
2244 2215 # protect os.system from UNC paths on Windows, which it can't handle:
2245 2216 if sys.platform == 'win32':
2246 2217 from IPython.utils._process_win32 import AvoidUNCPath
2247 2218 with AvoidUNCPath() as path:
2248 2219 if path is not None:
2249 2220 cmd = '"pushd %s &&"%s' % (path, cmd)
2250 2221 cmd = py3compat.unicode_to_str(cmd)
2251 2222 ec = os.system(cmd)
2252 2223 else:
2253 2224 cmd = py3compat.unicode_to_str(cmd)
2254 2225 ec = os.system(cmd)
2255 2226 # The high byte is the exit code, the low byte is a signal number
2256 2227 # that we discard for now. See the docs for os.wait()
2257 2228 if ec > 255:
2258 2229 ec >>= 8
2259 2230
2260 2231 # We explicitly do NOT return the subprocess status code, because
2261 2232 # a non-None value would trigger :func:`sys.displayhook` calls.
2262 2233 # Instead, we store the exit_code in user_ns.
2263 2234 self.user_ns['_exit_code'] = ec
2264 2235
2265 2236 # use piped system by default, because it is better behaved
2266 2237 system = system_piped
2267 2238
2268 2239 def getoutput(self, cmd, split=True, depth=0):
2269 2240 """Get output (possibly including stderr) from a subprocess.
2270 2241
2271 2242 Parameters
2272 2243 ----------
2273 2244 cmd : str
2274 2245 Command to execute (can not end in '&', as background processes are
2275 2246 not supported.
2276 2247 split : bool, optional
2277 2248 If True, split the output into an IPython SList. Otherwise, an
2278 2249 IPython LSString is returned. These are objects similar to normal
2279 2250 lists and strings, with a few convenience attributes for easier
2280 2251 manipulation of line-based output. You can use '?' on them for
2281 2252 details.
2282 2253 depth : int, optional
2283 2254 How many frames above the caller are the local variables which should
2284 2255 be expanded in the command string? The default (0) assumes that the
2285 2256 expansion variables are in the stack frame calling this function.
2286 2257 """
2287 2258 if cmd.rstrip().endswith('&'):
2288 2259 # this is *far* from a rigorous test
2289 2260 raise OSError("Background processes not supported.")
2290 2261 out = getoutput(self.var_expand(cmd, depth=depth+1))
2291 2262 if split:
2292 2263 out = SList(out.splitlines())
2293 2264 else:
2294 2265 out = LSString(out)
2295 2266 return out
2296 2267
2297 2268 #-------------------------------------------------------------------------
2298 2269 # Things related to aliases
2299 2270 #-------------------------------------------------------------------------
2300 2271
2301 2272 def init_alias(self):
2302 2273 self.alias_manager = AliasManager(shell=self, parent=self)
2303 2274 self.configurables.append(self.alias_manager)
2304 2275 self.ns_table['alias'] = self.alias_manager.alias_table,
2305 2276
2306 2277 #-------------------------------------------------------------------------
2307 2278 # Things related to extensions
2308 2279 #-------------------------------------------------------------------------
2309 2280
2310 2281 def init_extension_manager(self):
2311 2282 self.extension_manager = ExtensionManager(shell=self, parent=self)
2312 2283 self.configurables.append(self.extension_manager)
2313 2284
2314 2285 #-------------------------------------------------------------------------
2315 2286 # Things related to payloads
2316 2287 #-------------------------------------------------------------------------
2317 2288
2318 2289 def init_payload(self):
2319 2290 self.payload_manager = PayloadManager(parent=self)
2320 2291 self.configurables.append(self.payload_manager)
2321 2292
2322 2293 #-------------------------------------------------------------------------
2323 2294 # Things related to the prefilter
2324 2295 #-------------------------------------------------------------------------
2325 2296
2326 2297 def init_prefilter(self):
2327 2298 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2328 2299 self.configurables.append(self.prefilter_manager)
2329 2300 # Ultimately this will be refactored in the new interpreter code, but
2330 2301 # for now, we should expose the main prefilter method (there's legacy
2331 2302 # code out there that may rely on this).
2332 2303 self.prefilter = self.prefilter_manager.prefilter_lines
2333 2304
2334 2305 def auto_rewrite_input(self, cmd):
2335 2306 """Print to the screen the rewritten form of the user's command.
2336 2307
2337 2308 This shows visual feedback by rewriting input lines that cause
2338 2309 automatic calling to kick in, like::
2339 2310
2340 2311 /f x
2341 2312
2342 2313 into::
2343 2314
2344 2315 ------> f(x)
2345 2316
2346 2317 after the user's input prompt. This helps the user understand that the
2347 2318 input line was transformed automatically by IPython.
2348 2319 """
2349 2320 if not self.show_rewritten_input:
2350 2321 return
2351 2322
2352 2323 rw = self.prompt_manager.render('rewrite') + cmd
2353 2324
2354 2325 try:
2355 2326 # plain ascii works better w/ pyreadline, on some machines, so
2356 2327 # we use it and only print uncolored rewrite if we have unicode
2357 2328 rw = str(rw)
2358 2329 print(rw, file=io.stdout)
2359 2330 except UnicodeEncodeError:
2360 2331 print("------> " + cmd)
2361 2332
2362 2333 #-------------------------------------------------------------------------
2363 2334 # Things related to extracting values/expressions from kernel and user_ns
2364 2335 #-------------------------------------------------------------------------
2365 2336
2366 2337 def _user_obj_error(self):
2367 2338 """return simple exception dict
2368 2339
2369 2340 for use in user_variables / expressions
2370 2341 """
2371 2342
2372 2343 etype, evalue, tb = self._get_exc_info()
2373 2344 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2374 2345
2375 2346 exc_info = {
2376 2347 u'status' : 'error',
2377 2348 u'traceback' : stb,
2378 2349 u'ename' : unicode(etype.__name__),
2379 2350 u'evalue' : py3compat.safe_unicode(evalue),
2380 2351 }
2381 2352
2382 2353 return exc_info
2383 2354
2384 2355 def _format_user_obj(self, obj):
2385 2356 """format a user object to display dict
2386 2357
2387 2358 for use in user_expressions / variables
2388 2359 """
2389 2360
2390 2361 data, md = self.display_formatter.format(obj)
2391 2362 value = {
2392 2363 'status' : 'ok',
2393 2364 'data' : data,
2394 2365 'metadata' : md,
2395 2366 }
2396 2367 return value
2397 2368
2398 2369 def user_variables(self, names):
2399 2370 """Get a list of variable names from the user's namespace.
2400 2371
2401 2372 Parameters
2402 2373 ----------
2403 2374 names : list of strings
2404 2375 A list of names of variables to be read from the user namespace.
2405 2376
2406 2377 Returns
2407 2378 -------
2408 2379 A dict, keyed by the input names and with the rich mime-type repr(s) of each value.
2409 2380 Each element will be a sub-dict of the same form as a display_data message.
2410 2381 """
2411 2382 out = {}
2412 2383 user_ns = self.user_ns
2413 2384
2414 2385 for varname in names:
2415 2386 try:
2416 2387 value = self._format_user_obj(user_ns[varname])
2417 2388 except:
2418 2389 value = self._user_obj_error()
2419 2390 out[varname] = value
2420 2391 return out
2421 2392
2422 2393 def user_expressions(self, expressions):
2423 2394 """Evaluate a dict of expressions in the user's namespace.
2424 2395
2425 2396 Parameters
2426 2397 ----------
2427 2398 expressions : dict
2428 2399 A dict with string keys and string values. The expression values
2429 2400 should be valid Python expressions, each of which will be evaluated
2430 2401 in the user namespace.
2431 2402
2432 2403 Returns
2433 2404 -------
2434 2405 A dict, keyed like the input expressions dict, with the rich mime-typed
2435 2406 display_data of each value.
2436 2407 """
2437 2408 out = {}
2438 2409 user_ns = self.user_ns
2439 2410 global_ns = self.user_global_ns
2440 2411
2441 2412 for key, expr in expressions.iteritems():
2442 2413 try:
2443 2414 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2444 2415 except:
2445 2416 value = self._user_obj_error()
2446 2417 out[key] = value
2447 2418 return out
2448 2419
2449 2420 #-------------------------------------------------------------------------
2450 2421 # Things related to the running of code
2451 2422 #-------------------------------------------------------------------------
2452 2423
2453 2424 def ex(self, cmd):
2454 2425 """Execute a normal python statement in user namespace."""
2455 2426 with self.builtin_trap:
2456 2427 exec cmd in self.user_global_ns, self.user_ns
2457 2428
2458 2429 def ev(self, expr):
2459 2430 """Evaluate python expression expr in user namespace.
2460 2431
2461 2432 Returns the result of evaluation
2462 2433 """
2463 2434 with self.builtin_trap:
2464 2435 return eval(expr, self.user_global_ns, self.user_ns)
2465 2436
2466 2437 def safe_execfile(self, fname, *where, **kw):
2467 2438 """A safe version of the builtin execfile().
2468 2439
2469 2440 This version will never throw an exception, but instead print
2470 2441 helpful error messages to the screen. This only works on pure
2471 2442 Python files with the .py extension.
2472 2443
2473 2444 Parameters
2474 2445 ----------
2475 2446 fname : string
2476 2447 The name of the file to be executed.
2477 2448 where : tuple
2478 2449 One or two namespaces, passed to execfile() as (globals,locals).
2479 2450 If only one is given, it is passed as both.
2480 2451 exit_ignore : bool (False)
2481 2452 If True, then silence SystemExit for non-zero status (it is always
2482 2453 silenced for zero status, as it is so common).
2483 2454 raise_exceptions : bool (False)
2484 2455 If True raise exceptions everywhere. Meant for testing.
2485 2456
2486 2457 """
2487 2458 kw.setdefault('exit_ignore', False)
2488 2459 kw.setdefault('raise_exceptions', False)
2489 2460
2490 2461 fname = os.path.abspath(os.path.expanduser(fname))
2491 2462
2492 2463 # Make sure we can open the file
2493 2464 try:
2494 2465 with open(fname) as thefile:
2495 2466 pass
2496 2467 except:
2497 2468 warn('Could not open file <%s> for safe execution.' % fname)
2498 2469 return
2499 2470
2500 2471 # Find things also in current directory. This is needed to mimic the
2501 2472 # behavior of running a script from the system command line, where
2502 2473 # Python inserts the script's directory into sys.path
2503 2474 dname = os.path.dirname(fname)
2504 2475
2505 2476 with prepended_to_syspath(dname):
2506 2477 try:
2507 2478 py3compat.execfile(fname,*where)
2508 2479 except SystemExit as status:
2509 2480 # If the call was made with 0 or None exit status (sys.exit(0)
2510 2481 # or sys.exit() ), don't bother showing a traceback, as both of
2511 2482 # these are considered normal by the OS:
2512 2483 # > python -c'import sys;sys.exit(0)'; echo $?
2513 2484 # 0
2514 2485 # > python -c'import sys;sys.exit()'; echo $?
2515 2486 # 0
2516 2487 # For other exit status, we show the exception unless
2517 2488 # explicitly silenced, but only in short form.
2518 2489 if kw['raise_exceptions']:
2519 2490 raise
2520 2491 if status.code and not kw['exit_ignore']:
2521 2492 self.showtraceback(exception_only=True)
2522 2493 except:
2523 2494 if kw['raise_exceptions']:
2524 2495 raise
2525 2496 self.showtraceback()
2526 2497
2527 2498 def safe_execfile_ipy(self, fname):
2528 2499 """Like safe_execfile, but for .ipy files with IPython syntax.
2529 2500
2530 2501 Parameters
2531 2502 ----------
2532 2503 fname : str
2533 2504 The name of the file to execute. The filename must have a
2534 2505 .ipy extension.
2535 2506 """
2536 2507 fname = os.path.abspath(os.path.expanduser(fname))
2537 2508
2538 2509 # Make sure we can open the file
2539 2510 try:
2540 2511 with open(fname) as thefile:
2541 2512 pass
2542 2513 except:
2543 2514 warn('Could not open file <%s> for safe execution.' % fname)
2544 2515 return
2545 2516
2546 2517 # Find things also in current directory. This is needed to mimic the
2547 2518 # behavior of running a script from the system command line, where
2548 2519 # Python inserts the script's directory into sys.path
2549 2520 dname = os.path.dirname(fname)
2550 2521
2551 2522 with prepended_to_syspath(dname):
2552 2523 try:
2553 2524 with open(fname) as thefile:
2554 2525 # self.run_cell currently captures all exceptions
2555 2526 # raised in user code. It would be nice if there were
2556 2527 # versions of runlines, execfile that did raise, so
2557 2528 # we could catch the errors.
2558 2529 self.run_cell(thefile.read(), store_history=False, shell_futures=False)
2559 2530 except:
2560 2531 self.showtraceback()
2561 2532 warn('Unknown failure executing file: <%s>' % fname)
2562 2533
2563 2534 def safe_run_module(self, mod_name, where):
2564 2535 """A safe version of runpy.run_module().
2565 2536
2566 2537 This version will never throw an exception, but instead print
2567 2538 helpful error messages to the screen.
2568 2539
2569 2540 `SystemExit` exceptions with status code 0 or None are ignored.
2570 2541
2571 2542 Parameters
2572 2543 ----------
2573 2544 mod_name : string
2574 2545 The name of the module to be executed.
2575 2546 where : dict
2576 2547 The globals namespace.
2577 2548 """
2578 2549 try:
2579 2550 try:
2580 2551 where.update(
2581 2552 runpy.run_module(str(mod_name), run_name="__main__",
2582 2553 alter_sys=True)
2583 2554 )
2584 2555 except SystemExit as status:
2585 2556 if status.code:
2586 2557 raise
2587 2558 except:
2588 2559 self.showtraceback()
2589 2560 warn('Unknown failure executing module: <%s>' % mod_name)
2590 2561
2591 2562 def _run_cached_cell_magic(self, magic_name, line):
2592 2563 """Special method to call a cell magic with the data stored in self.
2593 2564 """
2594 2565 cell = self._current_cell_magic_body
2595 2566 self._current_cell_magic_body = None
2596 2567 return self.run_cell_magic(magic_name, line, cell)
2597 2568
2598 2569 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2599 2570 """Run a complete IPython cell.
2600 2571
2601 2572 Parameters
2602 2573 ----------
2603 2574 raw_cell : str
2604 2575 The code (including IPython code such as %magic functions) to run.
2605 2576 store_history : bool
2606 2577 If True, the raw and translated cell will be stored in IPython's
2607 2578 history. For user code calling back into IPython's machinery, this
2608 2579 should be set to False.
2609 2580 silent : bool
2610 2581 If True, avoid side-effects, such as implicit displayhooks and
2611 2582 and logging. silent=True forces store_history=False.
2612 2583 shell_futures : bool
2613 2584 If True, the code will share future statements with the interactive
2614 2585 shell. It will both be affected by previous __future__ imports, and
2615 2586 any __future__ imports in the code will affect the shell. If False,
2616 2587 __future__ imports are not shared in either direction.
2617 2588 """
2618 2589 if (not raw_cell) or raw_cell.isspace():
2619 2590 return
2620 2591
2621 2592 if silent:
2622 2593 store_history = False
2623 2594
2624 2595 self.input_transformer_manager.push(raw_cell)
2625 2596 cell = self.input_transformer_manager.source_reset()
2626 2597
2627 2598 # Our own compiler remembers the __future__ environment. If we want to
2628 2599 # run code with a separate __future__ environment, use the default
2629 2600 # compiler
2630 2601 compiler = self.compile if shell_futures else CachingCompiler()
2631 2602
2632 2603 with self.builtin_trap:
2633 2604 prefilter_failed = False
2634 2605 if len(cell.splitlines()) == 1:
2635 2606 try:
2636 2607 # use prefilter_lines to handle trailing newlines
2637 2608 # restore trailing newline for ast.parse
2638 2609 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2639 2610 except AliasError as e:
2640 2611 error(e)
2641 2612 prefilter_failed = True
2642 2613 except Exception:
2643 2614 # don't allow prefilter errors to crash IPython
2644 2615 self.showtraceback()
2645 2616 prefilter_failed = True
2646 2617
2647 2618 # Store raw and processed history
2648 2619 if store_history:
2649 2620 self.history_manager.store_inputs(self.execution_count,
2650 2621 cell, raw_cell)
2651 2622 if not silent:
2652 2623 self.logger.log(cell, raw_cell)
2653 2624
2654 2625 if not prefilter_failed:
2655 2626 # don't run if prefilter failed
2656 2627 cell_name = self.compile.cache(cell, self.execution_count)
2657 2628
2658 2629 with self.display_trap:
2659 2630 try:
2660 2631 code_ast = compiler.ast_parse(cell, filename=cell_name)
2661 2632 except IndentationError:
2662 2633 self.showindentationerror()
2663 2634 if store_history:
2664 2635 self.execution_count += 1
2665 2636 return None
2666 2637 except (OverflowError, SyntaxError, ValueError, TypeError,
2667 2638 MemoryError):
2668 2639 self.showsyntaxerror()
2669 2640 if store_history:
2670 2641 self.execution_count += 1
2671 2642 return None
2672 2643
2673 2644 code_ast = self.transform_ast(code_ast)
2674 2645
2675 2646 interactivity = "none" if silent else self.ast_node_interactivity
2676 2647 self.run_ast_nodes(code_ast.body, cell_name,
2677 2648 interactivity=interactivity, compiler=compiler)
2678 2649
2679 2650 # Execute any registered post-execution functions.
2680 2651 # unless we are silent
2681 2652 post_exec = [] if silent else self._post_execute.iteritems()
2682 2653
2683 2654 for func, status in post_exec:
2684 2655 if self.disable_failing_post_execute and not status:
2685 2656 continue
2686 2657 try:
2687 2658 func()
2688 2659 except KeyboardInterrupt:
2689 2660 print("\nKeyboardInterrupt", file=io.stderr)
2690 2661 except Exception:
2691 2662 # register as failing:
2692 2663 self._post_execute[func] = False
2693 2664 self.showtraceback()
2694 2665 print('\n'.join([
2695 2666 "post-execution function %r produced an error." % func,
2696 2667 "If this problem persists, you can disable failing post-exec functions with:",
2697 2668 "",
2698 2669 " get_ipython().disable_failing_post_execute = True"
2699 2670 ]), file=io.stderr)
2700 2671
2701 2672 if store_history:
2702 2673 # Write output to the database. Does nothing unless
2703 2674 # history output logging is enabled.
2704 2675 self.history_manager.store_output(self.execution_count)
2705 2676 # Each cell is a *single* input, regardless of how many lines it has
2706 2677 self.execution_count += 1
2707 2678
2708 2679 def transform_ast(self, node):
2709 2680 """Apply the AST transformations from self.ast_transformers
2710 2681
2711 2682 Parameters
2712 2683 ----------
2713 2684 node : ast.Node
2714 2685 The root node to be transformed. Typically called with the ast.Module
2715 2686 produced by parsing user input.
2716 2687
2717 2688 Returns
2718 2689 -------
2719 2690 An ast.Node corresponding to the node it was called with. Note that it
2720 2691 may also modify the passed object, so don't rely on references to the
2721 2692 original AST.
2722 2693 """
2723 2694 for transformer in self.ast_transformers:
2724 2695 try:
2725 2696 node = transformer.visit(node)
2726 2697 except Exception:
2727 2698 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2728 2699 self.ast_transformers.remove(transformer)
2729 2700
2730 2701 if self.ast_transformers:
2731 2702 ast.fix_missing_locations(node)
2732 2703 return node
2733 2704
2734 2705
2735 2706 def run_ast_nodes(self, nodelist, cell_name, interactivity='last_expr',
2736 2707 compiler=compile):
2737 2708 """Run a sequence of AST nodes. The execution mode depends on the
2738 2709 interactivity parameter.
2739 2710
2740 2711 Parameters
2741 2712 ----------
2742 2713 nodelist : list
2743 2714 A sequence of AST nodes to run.
2744 2715 cell_name : str
2745 2716 Will be passed to the compiler as the filename of the cell. Typically
2746 2717 the value returned by ip.compile.cache(cell).
2747 2718 interactivity : str
2748 2719 'all', 'last', 'last_expr' or 'none', specifying which nodes should be
2749 2720 run interactively (displaying output from expressions). 'last_expr'
2750 2721 will run the last node interactively only if it is an expression (i.e.
2751 2722 expressions in loops or other blocks are not displayed. Other values
2752 2723 for this parameter will raise a ValueError.
2753 2724 compiler : callable
2754 2725 A function with the same interface as the built-in compile(), to turn
2755 2726 the AST nodes into code objects. Default is the built-in compile().
2756 2727 """
2757 2728 if not nodelist:
2758 2729 return
2759 2730
2760 2731 if interactivity == 'last_expr':
2761 2732 if isinstance(nodelist[-1], ast.Expr):
2762 2733 interactivity = "last"
2763 2734 else:
2764 2735 interactivity = "none"
2765 2736
2766 2737 if interactivity == 'none':
2767 2738 to_run_exec, to_run_interactive = nodelist, []
2768 2739 elif interactivity == 'last':
2769 2740 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2770 2741 elif interactivity == 'all':
2771 2742 to_run_exec, to_run_interactive = [], nodelist
2772 2743 else:
2773 2744 raise ValueError("Interactivity was %r" % interactivity)
2774 2745
2775 2746 exec_count = self.execution_count
2776 2747
2777 2748 try:
2778 2749 for i, node in enumerate(to_run_exec):
2779 2750 mod = ast.Module([node])
2780 2751 code = compiler(mod, cell_name, "exec")
2781 2752 if self.run_code(code):
2782 2753 return True
2783 2754
2784 2755 for i, node in enumerate(to_run_interactive):
2785 2756 mod = ast.Interactive([node])
2786 2757 code = compiler(mod, cell_name, "single")
2787 2758 if self.run_code(code):
2788 2759 return True
2789 2760
2790 2761 # Flush softspace
2791 2762 if softspace(sys.stdout, 0):
2792 2763 print()
2793 2764
2794 2765 except:
2795 2766 # It's possible to have exceptions raised here, typically by
2796 2767 # compilation of odd code (such as a naked 'return' outside a
2797 2768 # function) that did parse but isn't valid. Typically the exception
2798 2769 # is a SyntaxError, but it's safest just to catch anything and show
2799 2770 # the user a traceback.
2800 2771
2801 2772 # We do only one try/except outside the loop to minimize the impact
2802 2773 # on runtime, and also because if any node in the node list is
2803 2774 # broken, we should stop execution completely.
2804 2775 self.showtraceback()
2805 2776
2806 2777 return False
2807 2778
2808 2779 def run_code(self, code_obj):
2809 2780 """Execute a code object.
2810 2781
2811 2782 When an exception occurs, self.showtraceback() is called to display a
2812 2783 traceback.
2813 2784
2814 2785 Parameters
2815 2786 ----------
2816 2787 code_obj : code object
2817 2788 A compiled code object, to be executed
2818 2789
2819 2790 Returns
2820 2791 -------
2821 2792 False : successful execution.
2822 2793 True : an error occurred.
2823 2794 """
2824 2795
2825 2796 # Set our own excepthook in case the user code tries to call it
2826 2797 # directly, so that the IPython crash handler doesn't get triggered
2827 2798 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2828 2799
2829 2800 # we save the original sys.excepthook in the instance, in case config
2830 2801 # code (such as magics) needs access to it.
2831 2802 self.sys_excepthook = old_excepthook
2832 2803 outflag = 1 # happens in more places, so it's easier as default
2833 2804 try:
2834 2805 try:
2835 2806 self.hooks.pre_run_code_hook()
2836 2807 #rprint('Running code', repr(code_obj)) # dbg
2837 2808 exec code_obj in self.user_global_ns, self.user_ns
2838 2809 finally:
2839 2810 # Reset our crash handler in place
2840 2811 sys.excepthook = old_excepthook
2841 2812 except SystemExit:
2842 2813 self.showtraceback(exception_only=True)
2843 2814 warn("To exit: use 'exit', 'quit', or Ctrl-D.", level=1)
2844 2815 except self.custom_exceptions:
2845 2816 etype,value,tb = sys.exc_info()
2846 2817 self.CustomTB(etype,value,tb)
2847 2818 except:
2848 2819 self.showtraceback()
2849 2820 else:
2850 2821 outflag = 0
2851 2822 return outflag
2852 2823
2853 2824 # For backwards compatibility
2854 2825 runcode = run_code
2855 2826
2856 2827 #-------------------------------------------------------------------------
2857 2828 # Things related to GUI support and pylab
2858 2829 #-------------------------------------------------------------------------
2859 2830
2860 2831 def enable_gui(self, gui=None):
2861 2832 raise NotImplementedError('Implement enable_gui in a subclass')
2862 2833
2863 2834 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2864 2835 """Activate pylab support at runtime.
2865 2836
2866 2837 This turns on support for matplotlib, preloads into the interactive
2867 2838 namespace all of numpy and pylab, and configures IPython to correctly
2868 2839 interact with the GUI event loop. The GUI backend to be used can be
2869 2840 optionally selected with the optional ``gui`` argument.
2870 2841
2871 2842 Parameters
2872 2843 ----------
2873 2844 gui : optional, string
2874 2845 If given, dictates the choice of matplotlib GUI backend to use
2875 2846 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2876 2847 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2877 2848 matplotlib (as dictated by the matplotlib build-time options plus the
2878 2849 user's matplotlibrc configuration file). Note that not all backends
2879 2850 make sense in all contexts, for example a terminal ipython can't
2880 2851 display figures inline.
2881 2852 """
2882 2853 from IPython.core.pylabtools import mpl_runner
2883 2854 # We want to prevent the loading of pylab to pollute the user's
2884 2855 # namespace as shown by the %who* magics, so we execute the activation
2885 2856 # code in an empty namespace, and we update *both* user_ns and
2886 2857 # user_ns_hidden with this information.
2887 2858 ns = {}
2888 2859 try:
2889 2860 gui = pylab_activate(ns, gui, import_all, self, welcome_message=welcome_message)
2890 2861 except KeyError:
2891 2862 error("Backend %r not supported" % gui)
2892 2863 return
2893 2864 except ImportError:
2894 2865 error("pylab mode doesn't work as matplotlib could not be found." + \
2895 2866 "\nIs it installed on the system?")
2896 2867 return
2897 2868 self.user_ns.update(ns)
2898 2869 self.user_ns_hidden.update(ns)
2899 2870 # Now we must activate the gui pylab wants to use, and fix %run to take
2900 2871 # plot updates into account
2901 2872 self.enable_gui(gui)
2902 2873 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2903 2874 mpl_runner(self.safe_execfile)
2904 2875
2905 2876 #-------------------------------------------------------------------------
2906 2877 # Utilities
2907 2878 #-------------------------------------------------------------------------
2908 2879
2909 2880 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
2910 2881 """Expand python variables in a string.
2911 2882
2912 2883 The depth argument indicates how many frames above the caller should
2913 2884 be walked to look for the local namespace where to expand variables.
2914 2885
2915 2886 The global namespace for expansion is always the user's interactive
2916 2887 namespace.
2917 2888 """
2918 2889 ns = self.user_ns.copy()
2919 2890 ns.update(sys._getframe(depth+1).f_locals)
2920 2891 try:
2921 2892 # We have to use .vformat() here, because 'self' is a valid and common
2922 2893 # name, and expanding **ns for .format() would make it collide with
2923 2894 # the 'self' argument of the method.
2924 2895 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
2925 2896 except Exception:
2926 2897 # if formatter couldn't format, just let it go untransformed
2927 2898 pass
2928 2899 return cmd
2929 2900
2930 2901 def mktempfile(self, data=None, prefix='ipython_edit_'):
2931 2902 """Make a new tempfile and return its filename.
2932 2903
2933 2904 This makes a call to tempfile.mktemp, but it registers the created
2934 2905 filename internally so ipython cleans it up at exit time.
2935 2906
2936 2907 Optional inputs:
2937 2908
2938 2909 - data(None): if data is given, it gets written out to the temp file
2939 2910 immediately, and the file is closed again."""
2940 2911
2941 2912 filename = tempfile.mktemp('.py', prefix)
2942 2913 self.tempfiles.append(filename)
2943 2914
2944 2915 if data:
2945 2916 tmp_file = open(filename,'w')
2946 2917 tmp_file.write(data)
2947 2918 tmp_file.close()
2948 2919 return filename
2949 2920
2950 2921 # TODO: This should be removed when Term is refactored.
2951 2922 def write(self,data):
2952 2923 """Write a string to the default output"""
2953 2924 io.stdout.write(data)
2954 2925
2955 2926 # TODO: This should be removed when Term is refactored.
2956 2927 def write_err(self,data):
2957 2928 """Write a string to the default error output"""
2958 2929 io.stderr.write(data)
2959 2930
2960 2931 def ask_yes_no(self, prompt, default=None):
2961 2932 if self.quiet:
2962 2933 return True
2963 2934 return ask_yes_no(prompt,default)
2964 2935
2965 2936 def show_usage(self):
2966 2937 """Show a usage message"""
2967 2938 page.page(IPython.core.usage.interactive_usage)
2968 2939
2969 2940 def extract_input_lines(self, range_str, raw=False):
2970 2941 """Return as a string a set of input history slices.
2971 2942
2972 2943 Parameters
2973 2944 ----------
2974 2945 range_str : string
2975 2946 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
2976 2947 since this function is for use by magic functions which get their
2977 2948 arguments as strings. The number before the / is the session
2978 2949 number: ~n goes n back from the current session.
2979 2950
2980 2951 Optional Parameters:
2981 2952 - raw(False): by default, the processed input is used. If this is
2982 2953 true, the raw input history is used instead.
2983 2954
2984 2955 Note that slices can be called with two notations:
2985 2956
2986 2957 N:M -> standard python form, means including items N...(M-1).
2987 2958
2988 2959 N-M -> include items N..M (closed endpoint)."""
2989 2960 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
2990 2961 return "\n".join(x for _, _, x in lines)
2991 2962
2992 2963 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True):
2993 2964 """Get a code string from history, file, url, or a string or macro.
2994 2965
2995 2966 This is mainly used by magic functions.
2996 2967
2997 2968 Parameters
2998 2969 ----------
2999 2970
3000 2971 target : str
3001 2972
3002 2973 A string specifying code to retrieve. This will be tried respectively
3003 2974 as: ranges of input history (see %history for syntax), url,
3004 2975 correspnding .py file, filename, or an expression evaluating to a
3005 2976 string or Macro in the user namespace.
3006 2977
3007 2978 raw : bool
3008 2979 If true (default), retrieve raw history. Has no effect on the other
3009 2980 retrieval mechanisms.
3010 2981
3011 2982 py_only : bool (default False)
3012 2983 Only try to fetch python code, do not try alternative methods to decode file
3013 2984 if unicode fails.
3014 2985
3015 2986 Returns
3016 2987 -------
3017 2988 A string of code.
3018 2989
3019 2990 ValueError is raised if nothing is found, and TypeError if it evaluates
3020 2991 to an object of another type. In each case, .args[0] is a printable
3021 2992 message.
3022 2993 """
3023 2994 code = self.extract_input_lines(target, raw=raw) # Grab history
3024 2995 if code:
3025 2996 return code
3026 2997 utarget = unquote_filename(target)
3027 2998 try:
3028 2999 if utarget.startswith(('http://', 'https://')):
3029 3000 return openpy.read_py_url(utarget, skip_encoding_cookie=skip_encoding_cookie)
3030 3001 except UnicodeDecodeError:
3031 3002 if not py_only :
3032 3003 from urllib import urlopen # Deferred import
3033 3004 response = urlopen(target)
3034 3005 return response.read().decode('latin1')
3035 3006 raise ValueError(("'%s' seem to be unreadable.") % utarget)
3036 3007
3037 3008 potential_target = [target]
3038 3009 try :
3039 3010 potential_target.insert(0,get_py_filename(target))
3040 3011 except IOError:
3041 3012 pass
3042 3013
3043 3014 for tgt in potential_target :
3044 3015 if os.path.isfile(tgt): # Read file
3045 3016 try :
3046 3017 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3047 3018 except UnicodeDecodeError :
3048 3019 if not py_only :
3049 3020 with io_open(tgt,'r', encoding='latin1') as f :
3050 3021 return f.read()
3051 3022 raise ValueError(("'%s' seem to be unreadable.") % target)
3052 3023 elif os.path.isdir(os.path.expanduser(tgt)):
3053 3024 raise ValueError("'%s' is a directory, not a regular file." % target)
3054 3025
3055 3026 try: # User namespace
3056 3027 codeobj = eval(target, self.user_ns)
3057 3028 except Exception:
3058 3029 raise ValueError(("'%s' was not found in history, as a file, url, "
3059 3030 "nor in the user namespace.") % target)
3060 3031 if isinstance(codeobj, basestring):
3061 3032 return codeobj
3062 3033 elif isinstance(codeobj, Macro):
3063 3034 return codeobj.value
3064 3035
3065 3036 raise TypeError("%s is neither a string nor a macro." % target,
3066 3037 codeobj)
3067 3038
3068 3039 #-------------------------------------------------------------------------
3069 3040 # Things related to IPython exiting
3070 3041 #-------------------------------------------------------------------------
3071 3042 def atexit_operations(self):
3072 3043 """This will be executed at the time of exit.
3073 3044
3074 3045 Cleanup operations and saving of persistent data that is done
3075 3046 unconditionally by IPython should be performed here.
3076 3047
3077 3048 For things that may depend on startup flags or platform specifics (such
3078 3049 as having readline or not), register a separate atexit function in the
3079 3050 code that has the appropriate information, rather than trying to
3080 3051 clutter
3081 3052 """
3082 3053 # Close the history session (this stores the end time and line count)
3083 3054 # this must be *before* the tempfile cleanup, in case of temporary
3084 3055 # history db
3085 3056 self.history_manager.end_session()
3086 3057
3087 3058 # Cleanup all tempfiles left around
3088 3059 for tfile in self.tempfiles:
3089 3060 try:
3090 3061 os.unlink(tfile)
3091 3062 except OSError:
3092 3063 pass
3093 3064
3094 3065 # Clear all user namespaces to release all references cleanly.
3095 3066 self.reset(new_session=False)
3096 3067
3097 3068 # Run user hooks
3098 3069 self.hooks.shutdown_hook()
3099 3070
3100 3071 def cleanup(self):
3101 3072 self.restore_sys_module_state()
3102 3073
3103 3074
3104 3075 class InteractiveShellABC(object):
3105 3076 """An abstract base class for InteractiveShell."""
3106 3077 __metaclass__ = abc.ABCMeta
3107 3078
3108 3079 InteractiveShellABC.register(InteractiveShell)
@@ -1,1183 +1,1182 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Implementation of execution-related magic functions.
3 3 """
4 4 #-----------------------------------------------------------------------------
5 5 # Copyright (c) 2012 The IPython Development Team.
6 6 #
7 7 # Distributed under the terms of the Modified BSD License.
8 8 #
9 9 # The full license is in the file COPYING.txt, distributed with this software.
10 10 #-----------------------------------------------------------------------------
11 11
12 12 #-----------------------------------------------------------------------------
13 13 # Imports
14 14 #-----------------------------------------------------------------------------
15 15
16 16 # Stdlib
17 17 import __builtin__ as builtin_mod
18 18 import ast
19 19 import bdb
20 20 import os
21 21 import sys
22 22 import time
23 23 from StringIO import StringIO
24 24
25 25 # cProfile was added in Python2.5
26 26 try:
27 27 import cProfile as profile
28 28 import pstats
29 29 except ImportError:
30 30 # profile isn't bundled by default in Debian for license reasons
31 31 try:
32 32 import profile, pstats
33 33 except ImportError:
34 34 profile = pstats = None
35 35
36 36 # Our own packages
37 37 from IPython.core import debugger, oinspect
38 38 from IPython.core import magic_arguments
39 39 from IPython.core import page
40 40 from IPython.core.error import UsageError
41 41 from IPython.core.macro import Macro
42 42 from IPython.core.magic import (Magics, magics_class, line_magic, cell_magic,
43 43 line_cell_magic, on_off, needs_local_scope)
44 44 from IPython.testing.skipdoctest import skip_doctest
45 45 from IPython.utils import py3compat
46 46 from IPython.utils.contexts import preserve_keys
47 47 from IPython.utils.io import capture_output
48 48 from IPython.utils.ipstruct import Struct
49 49 from IPython.utils.module_paths import find_mod
50 50 from IPython.utils.path import get_py_filename, unquote_filename, shellglob
51 51 from IPython.utils.timing import clock, clock2
52 52 from IPython.utils.warn import warn, error
53 53
54 54
55 55 #-----------------------------------------------------------------------------
56 56 # Magic implementation classes
57 57 #-----------------------------------------------------------------------------
58 58
59 59 @magics_class
60 60 class ExecutionMagics(Magics):
61 61 """Magics related to code execution, debugging, profiling, etc.
62 62
63 63 """
64 64
65 65 def __init__(self, shell):
66 66 super(ExecutionMagics, self).__init__(shell)
67 67 if profile is None:
68 68 self.prun = self.profile_missing_notice
69 69 # Default execution function used to actually run user code.
70 70 self.default_runner = None
71 71
72 72 def profile_missing_notice(self, *args, **kwargs):
73 73 error("""\
74 74 The profile module could not be found. It has been removed from the standard
75 75 python packages because of its non-free license. To use profiling, install the
76 76 python-profiler package from non-free.""")
77 77
78 78 @skip_doctest
79 79 @line_cell_magic
80 80 def prun(self, parameter_s='', cell=None):
81 81
82 82 """Run a statement through the python code profiler.
83 83
84 84 Usage, in line mode:
85 85 %prun [options] statement
86 86
87 87 Usage, in cell mode:
88 88 %%prun [options] [statement]
89 89 code...
90 90 code...
91 91
92 92 In cell mode, the additional code lines are appended to the (possibly
93 93 empty) statement in the first line. Cell mode allows you to easily
94 94 profile multiline blocks without having to put them in a separate
95 95 function.
96 96
97 97 The given statement (which doesn't require quote marks) is run via the
98 98 python profiler in a manner similar to the profile.run() function.
99 99 Namespaces are internally managed to work correctly; profile.run
100 100 cannot be used in IPython because it makes certain assumptions about
101 101 namespaces which do not hold under IPython.
102 102
103 103 Options:
104 104
105 105 -l <limit>: you can place restrictions on what or how much of the
106 106 profile gets printed. The limit value can be:
107 107
108 108 * A string: only information for function names containing this string
109 109 is printed.
110 110
111 111 * An integer: only these many lines are printed.
112 112
113 113 * A float (between 0 and 1): this fraction of the report is printed
114 114 (for example, use a limit of 0.4 to see the topmost 40% only).
115 115
116 116 You can combine several limits with repeated use of the option. For
117 117 example, '-l __init__ -l 5' will print only the topmost 5 lines of
118 118 information about class constructors.
119 119
120 120 -r: return the pstats.Stats object generated by the profiling. This
121 121 object has all the information about the profile in it, and you can
122 122 later use it for further analysis or in other functions.
123 123
124 124 -s <key>: sort profile by given key. You can provide more than one key
125 125 by using the option several times: '-s key1 -s key2 -s key3...'. The
126 126 default sorting key is 'time'.
127 127
128 128 The following is copied verbatim from the profile documentation
129 129 referenced below:
130 130
131 131 When more than one key is provided, additional keys are used as
132 132 secondary criteria when the there is equality in all keys selected
133 133 before them.
134 134
135 135 Abbreviations can be used for any key names, as long as the
136 136 abbreviation is unambiguous. The following are the keys currently
137 137 defined:
138 138
139 139 Valid Arg Meaning
140 140 "calls" call count
141 141 "cumulative" cumulative time
142 142 "file" file name
143 143 "module" file name
144 144 "pcalls" primitive call count
145 145 "line" line number
146 146 "name" function name
147 147 "nfl" name/file/line
148 148 "stdname" standard name
149 149 "time" internal time
150 150
151 151 Note that all sorts on statistics are in descending order (placing
152 152 most time consuming items first), where as name, file, and line number
153 153 searches are in ascending order (i.e., alphabetical). The subtle
154 154 distinction between "nfl" and "stdname" is that the standard name is a
155 155 sort of the name as printed, which means that the embedded line
156 156 numbers get compared in an odd way. For example, lines 3, 20, and 40
157 157 would (if the file names were the same) appear in the string order
158 158 "20" "3" and "40". In contrast, "nfl" does a numeric compare of the
159 159 line numbers. In fact, sort_stats("nfl") is the same as
160 160 sort_stats("name", "file", "line").
161 161
162 162 -T <filename>: save profile results as shown on screen to a text
163 163 file. The profile is still shown on screen.
164 164
165 165 -D <filename>: save (via dump_stats) profile statistics to given
166 166 filename. This data is in a format understood by the pstats module, and
167 167 is generated by a call to the dump_stats() method of profile
168 168 objects. The profile is still shown on screen.
169 169
170 170 -q: suppress output to the pager. Best used with -T and/or -D above.
171 171
172 172 If you want to run complete programs under the profiler's control, use
173 173 '%run -p [prof_opts] filename.py [args to program]' where prof_opts
174 174 contains profiler specific options as described here.
175 175
176 176 You can read the complete documentation for the profile module with::
177 177
178 178 In [1]: import profile; profile.help()
179 179 """
180 180 opts, arg_str = self.parse_options(parameter_s, 'D:l:rs:T:q',
181 181 list_all=True, posix=False)
182 182 if cell is not None:
183 183 arg_str += '\n' + cell
184 184 return self._run_with_profiler(arg_str, opts, self.shell.user_ns)
185 185
186 186 def _run_with_profiler(self, code, opts, namespace):
187 187 """
188 188 Run `code` with profiler. Used by ``%prun`` and ``%run -p``.
189 189
190 190 Parameters
191 191 ----------
192 192 code : str
193 193 Code to be executed.
194 194 opts : Struct
195 195 Options parsed by `self.parse_options`.
196 196 namespace : dict
197 197 A dictionary for Python namespace (e.g., `self.shell.user_ns`).
198 198
199 199 """
200 200
201 201 # Fill default values for unspecified options:
202 202 opts.merge(Struct(D=[''], l=[], s=['time'], T=['']))
203 203
204 204 prof = profile.Profile()
205 205 try:
206 206 prof = prof.runctx(code, namespace, namespace)
207 207 sys_exit = ''
208 208 except SystemExit:
209 209 sys_exit = """*** SystemExit exception caught in code being profiled."""
210 210
211 211 stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s)
212 212
213 213 lims = opts.l
214 214 if lims:
215 215 lims = [] # rebuild lims with ints/floats/strings
216 216 for lim in opts.l:
217 217 try:
218 218 lims.append(int(lim))
219 219 except ValueError:
220 220 try:
221 221 lims.append(float(lim))
222 222 except ValueError:
223 223 lims.append(lim)
224 224
225 225 # Trap output.
226 226 stdout_trap = StringIO()
227 227 stats_stream = stats.stream
228 228 try:
229 229 stats.stream = stdout_trap
230 230 stats.print_stats(*lims)
231 231 finally:
232 232 stats.stream = stats_stream
233 233
234 234 output = stdout_trap.getvalue()
235 235 output = output.rstrip()
236 236
237 237 if 'q' not in opts:
238 238 page.page(output)
239 239 print sys_exit,
240 240
241 241 dump_file = opts.D[0]
242 242 text_file = opts.T[0]
243 243 if dump_file:
244 244 dump_file = unquote_filename(dump_file)
245 245 prof.dump_stats(dump_file)
246 246 print '\n*** Profile stats marshalled to file',\
247 247 repr(dump_file)+'.',sys_exit
248 248 if text_file:
249 249 text_file = unquote_filename(text_file)
250 250 pfile = open(text_file,'w')
251 251 pfile.write(output)
252 252 pfile.close()
253 253 print '\n*** Profile printout saved to text file',\
254 254 repr(text_file)+'.',sys_exit
255 255
256 256 if 'r' in opts:
257 257 return stats
258 258 else:
259 259 return None
260 260
261 261 @line_magic
262 262 def pdb(self, parameter_s=''):
263 263 """Control the automatic calling of the pdb interactive debugger.
264 264
265 265 Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without
266 266 argument it works as a toggle.
267 267
268 268 When an exception is triggered, IPython can optionally call the
269 269 interactive pdb debugger after the traceback printout. %pdb toggles
270 270 this feature on and off.
271 271
272 272 The initial state of this feature is set in your configuration
273 273 file (the option is ``InteractiveShell.pdb``).
274 274
275 275 If you want to just activate the debugger AFTER an exception has fired,
276 276 without having to type '%pdb on' and rerunning your code, you can use
277 277 the %debug magic."""
278 278
279 279 par = parameter_s.strip().lower()
280 280
281 281 if par:
282 282 try:
283 283 new_pdb = {'off':0,'0':0,'on':1,'1':1}[par]
284 284 except KeyError:
285 285 print ('Incorrect argument. Use on/1, off/0, '
286 286 'or nothing for a toggle.')
287 287 return
288 288 else:
289 289 # toggle
290 290 new_pdb = not self.shell.call_pdb
291 291
292 292 # set on the shell
293 293 self.shell.call_pdb = new_pdb
294 294 print 'Automatic pdb calling has been turned',on_off(new_pdb)
295 295
296 296 @line_magic
297 297 def debug(self, parameter_s=''):
298 298 """Activate the interactive debugger in post-mortem mode.
299 299
300 300 If an exception has just occurred, this lets you inspect its stack
301 301 frames interactively. Note that this will always work only on the last
302 302 traceback that occurred, so you must call this quickly after an
303 303 exception that you wish to inspect has fired, because if another one
304 304 occurs, it clobbers the previous one.
305 305
306 306 If you want IPython to automatically do this on every exception, see
307 307 the %pdb magic for more details.
308 308 """
309 309 self.shell.debugger(force=True)
310 310
311 311 @line_magic
312 312 def tb(self, s):
313 313 """Print the last traceback with the currently active exception mode.
314 314
315 315 See %xmode for changing exception reporting modes."""
316 316 self.shell.showtraceback()
317 317
318 318 @skip_doctest
319 319 @line_magic
320 320 def run(self, parameter_s='', runner=None,
321 321 file_finder=get_py_filename):
322 322 """Run the named file inside IPython as a program.
323 323
324 324 Usage:
325 325 %run [-n -i -e -G]
326 326 [( -t [-N<N>] | -d [-b<N>] | -p [profile options] )]
327 327 ( -m mod | file ) [args]
328 328
329 329 Parameters after the filename are passed as command-line arguments to
330 330 the program (put in sys.argv). Then, control returns to IPython's
331 331 prompt.
332 332
333 333 This is similar to running at a system prompt:\\
334 334 $ python file args\\
335 335 but with the advantage of giving you IPython's tracebacks, and of
336 336 loading all variables into your interactive namespace for further use
337 337 (unless -p is used, see below).
338 338
339 339 The file is executed in a namespace initially consisting only of
340 340 __name__=='__main__' and sys.argv constructed as indicated. It thus
341 341 sees its environment as if it were being run as a stand-alone program
342 342 (except for sharing global objects such as previously imported
343 343 modules). But after execution, the IPython interactive namespace gets
344 344 updated with all variables defined in the program (except for __name__
345 345 and sys.argv). This allows for very convenient loading of code for
346 346 interactive work, while giving each program a 'clean sheet' to run in.
347 347
348 348 Arguments are expanded using shell-like glob match. Patterns
349 349 '*', '?', '[seq]' and '[!seq]' can be used. Additionally,
350 350 tilde '~' will be expanded into user's home directory. Unlike
351 351 real shells, quotation does not suppress expansions. Use
352 352 *two* back slashes (e.g., '\\\\*') to suppress expansions.
353 353 To completely disable these expansions, you can use -G flag.
354 354
355 355 Options:
356 356
357 357 -n: __name__ is NOT set to '__main__', but to the running file's name
358 358 without extension (as python does under import). This allows running
359 359 scripts and reloading the definitions in them without calling code
360 360 protected by an ' if __name__ == "__main__" ' clause.
361 361
362 362 -i: run the file in IPython's namespace instead of an empty one. This
363 363 is useful if you are experimenting with code written in a text editor
364 364 which depends on variables defined interactively.
365 365
366 366 -e: ignore sys.exit() calls or SystemExit exceptions in the script
367 367 being run. This is particularly useful if IPython is being used to
368 368 run unittests, which always exit with a sys.exit() call. In such
369 369 cases you are interested in the output of the test results, not in
370 370 seeing a traceback of the unittest module.
371 371
372 372 -t: print timing information at the end of the run. IPython will give
373 373 you an estimated CPU time consumption for your script, which under
374 374 Unix uses the resource module to avoid the wraparound problems of
375 375 time.clock(). Under Unix, an estimate of time spent on system tasks
376 376 is also given (for Windows platforms this is reported as 0.0).
377 377
378 378 If -t is given, an additional -N<N> option can be given, where <N>
379 379 must be an integer indicating how many times you want the script to
380 380 run. The final timing report will include total and per run results.
381 381
382 382 For example (testing the script uniq_stable.py)::
383 383
384 384 In [1]: run -t uniq_stable
385 385
386 386 IPython CPU timings (estimated):\\
387 387 User : 0.19597 s.\\
388 388 System: 0.0 s.\\
389 389
390 390 In [2]: run -t -N5 uniq_stable
391 391
392 392 IPython CPU timings (estimated):\\
393 393 Total runs performed: 5\\
394 394 Times : Total Per run\\
395 395 User : 0.910862 s, 0.1821724 s.\\
396 396 System: 0.0 s, 0.0 s.
397 397
398 398 -d: run your program under the control of pdb, the Python debugger.
399 399 This allows you to execute your program step by step, watch variables,
400 400 etc. Internally, what IPython does is similar to calling:
401 401
402 402 pdb.run('execfile("YOURFILENAME")')
403 403
404 404 with a breakpoint set on line 1 of your file. You can change the line
405 405 number for this automatic breakpoint to be <N> by using the -bN option
406 406 (where N must be an integer). For example::
407 407
408 408 %run -d -b40 myscript
409 409
410 410 will set the first breakpoint at line 40 in myscript.py. Note that
411 411 the first breakpoint must be set on a line which actually does
412 412 something (not a comment or docstring) for it to stop execution.
413 413
414 414 Or you can specify a breakpoint in a different file::
415 415
416 416 %run -d -b myotherfile.py:20 myscript
417 417
418 418 When the pdb debugger starts, you will see a (Pdb) prompt. You must
419 419 first enter 'c' (without quotes) to start execution up to the first
420 420 breakpoint.
421 421
422 422 Entering 'help' gives information about the use of the debugger. You
423 423 can easily see pdb's full documentation with "import pdb;pdb.help()"
424 424 at a prompt.
425 425
426 426 -p: run program under the control of the Python profiler module (which
427 427 prints a detailed report of execution times, function calls, etc).
428 428
429 429 You can pass other options after -p which affect the behavior of the
430 430 profiler itself. See the docs for %prun for details.
431 431
432 432 In this mode, the program's variables do NOT propagate back to the
433 433 IPython interactive namespace (because they remain in the namespace
434 434 where the profiler executes them).
435 435
436 436 Internally this triggers a call to %prun, see its documentation for
437 437 details on the options available specifically for profiling.
438 438
439 439 There is one special usage for which the text above doesn't apply:
440 440 if the filename ends with .ipy, the file is run as ipython script,
441 441 just as if the commands were written on IPython prompt.
442 442
443 443 -m: specify module name to load instead of script path. Similar to
444 444 the -m option for the python interpreter. Use this option last if you
445 445 want to combine with other %run options. Unlike the python interpreter
446 446 only source modules are allowed no .pyc or .pyo files.
447 447 For example::
448 448
449 449 %run -m example
450 450
451 451 will run the example module.
452 452
453 453 -G: disable shell-like glob expansion of arguments.
454 454
455 455 """
456 456
457 457 # get arguments and set sys.argv for program to be run.
458 458 opts, arg_lst = self.parse_options(parameter_s,
459 459 'nidtN:b:pD:l:rs:T:em:G',
460 460 mode='list', list_all=1)
461 461 if "m" in opts:
462 462 modulename = opts["m"][0]
463 463 modpath = find_mod(modulename)
464 464 if modpath is None:
465 465 warn('%r is not a valid modulename on sys.path'%modulename)
466 466 return
467 467 arg_lst = [modpath] + arg_lst
468 468 try:
469 469 filename = file_finder(arg_lst[0])
470 470 except IndexError:
471 471 warn('you must provide at least a filename.')
472 472 print '\n%run:\n', oinspect.getdoc(self.run)
473 473 return
474 474 except IOError as e:
475 475 try:
476 476 msg = str(e)
477 477 except UnicodeError:
478 478 msg = e.message
479 479 error(msg)
480 480 return
481 481
482 482 if filename.lower().endswith('.ipy'):
483 483 with preserve_keys(self.shell.user_ns, '__file__'):
484 484 self.shell.user_ns['__file__'] = filename
485 485 self.shell.safe_execfile_ipy(filename)
486 486 return
487 487
488 488 # Control the response to exit() calls made by the script being run
489 489 exit_ignore = 'e' in opts
490 490
491 491 # Make sure that the running script gets a proper sys.argv as if it
492 492 # were run from a system shell.
493 493 save_argv = sys.argv # save it for later restoring
494 494
495 495 if 'G' in opts:
496 496 args = arg_lst[1:]
497 497 else:
498 498 # tilde and glob expansion
499 499 args = shellglob(map(os.path.expanduser, arg_lst[1:]))
500 500
501 501 sys.argv = [filename] + args # put in the proper filename
502 502 # protect sys.argv from potential unicode strings on Python 2:
503 503 if not py3compat.PY3:
504 504 sys.argv = [ py3compat.cast_bytes(a) for a in sys.argv ]
505 505
506 506 if 'i' in opts:
507 507 # Run in user's interactive namespace
508 508 prog_ns = self.shell.user_ns
509 509 __name__save = self.shell.user_ns['__name__']
510 510 prog_ns['__name__'] = '__main__'
511 main_mod = self.shell.new_main_mod(prog_ns)
511 main_mod = self.shell.user_module
512 512 else:
513 513 # Run in a fresh, empty namespace
514 514 if 'n' in opts:
515 515 name = os.path.splitext(os.path.basename(filename))[0]
516 516 else:
517 517 name = '__main__'
518 518
519 main_mod = self.shell.new_main_mod()
519 # The shell MUST hold a reference to prog_ns so after %run
520 # exits, the python deletion mechanism doesn't zero it out
521 # (leaving dangling references). See interactiveshell for details
522 main_mod = self.shell.new_main_mod(filename)
520 523 prog_ns = main_mod.__dict__
521 524 prog_ns['__name__'] = name
522 525
523 526 # Since '%run foo' emulates 'python foo.py' at the cmd line, we must
524 527 # set the __file__ global in the script's namespace
525 528 prog_ns['__file__'] = filename
526 529
527 530 # pickle fix. See interactiveshell for an explanation. But we need to
528 531 # make sure that, if we overwrite __main__, we replace it at the end
529 532 main_mod_name = prog_ns['__name__']
530 533
531 534 if main_mod_name == '__main__':
532 535 restore_main = sys.modules['__main__']
533 536 else:
534 537 restore_main = False
535 538
536 539 # This needs to be undone at the end to prevent holding references to
537 540 # every single object ever created.
538 541 sys.modules[main_mod_name] = main_mod
539 542
540 543 if 'p' in opts or 'd' in opts:
541 544 if 'm' in opts:
542 545 code = 'run_module(modulename, prog_ns)'
543 546 code_ns = {
544 547 'run_module': self.shell.safe_run_module,
545 548 'prog_ns': prog_ns,
546 549 'modulename': modulename,
547 550 }
548 551 else:
549 552 code = 'execfile(filename, prog_ns)'
550 553 code_ns = {
551 554 'execfile': self.shell.safe_execfile,
552 555 'prog_ns': prog_ns,
553 556 'filename': get_py_filename(filename),
554 557 }
555 558
556 559 try:
557 560 stats = None
558 561 with self.shell.readline_no_record:
559 562 if 'p' in opts:
560 563 stats = self._run_with_profiler(code, opts, code_ns)
561 564 else:
562 565 if 'd' in opts:
563 566 self._run_with_debugger(
564 567 code, code_ns, opts.get('b', ['1'])[0], filename)
565 568 else:
566 569 if 'm' in opts:
567 570 def run():
568 571 self.shell.safe_run_module(modulename, prog_ns)
569 572 else:
570 573 if runner is None:
571 574 runner = self.default_runner
572 575 if runner is None:
573 576 runner = self.shell.safe_execfile
574 577
575 578 def run():
576 579 runner(filename, prog_ns, prog_ns,
577 580 exit_ignore=exit_ignore)
578 581
579 582 if 't' in opts:
580 583 # timed execution
581 584 try:
582 585 nruns = int(opts['N'][0])
583 586 if nruns < 1:
584 587 error('Number of runs must be >=1')
585 588 return
586 589 except (KeyError):
587 590 nruns = 1
588 591 self._run_with_timing(run, nruns)
589 592 else:
590 593 # regular execution
591 594 run()
592 595
593 596 if 'i' in opts:
594 597 self.shell.user_ns['__name__'] = __name__save
595 598 else:
596 # The shell MUST hold a reference to prog_ns so after %run
597 # exits, the python deletion mechanism doesn't zero it out
598 # (leaving dangling references).
599 self.shell.cache_main_mod(prog_ns, filename)
600 599 # update IPython interactive namespace
601 600
602 601 # Some forms of read errors on the file may mean the
603 602 # __name__ key was never set; using pop we don't have to
604 603 # worry about a possible KeyError.
605 604 prog_ns.pop('__name__', None)
606 605
607 606 with preserve_keys(self.shell.user_ns, '__file__'):
608 607 self.shell.user_ns.update(prog_ns)
609 608 finally:
610 609 # It's a bit of a mystery why, but __builtins__ can change from
611 610 # being a module to becoming a dict missing some key data after
612 611 # %run. As best I can see, this is NOT something IPython is doing
613 612 # at all, and similar problems have been reported before:
614 613 # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html
615 614 # Since this seems to be done by the interpreter itself, the best
616 615 # we can do is to at least restore __builtins__ for the user on
617 616 # exit.
618 617 self.shell.user_ns['__builtins__'] = builtin_mod
619 618
620 619 # Ensure key global structures are restored
621 620 sys.argv = save_argv
622 621 if restore_main:
623 622 sys.modules['__main__'] = restore_main
624 623 else:
625 624 # Remove from sys.modules the reference to main_mod we'd
626 625 # added. Otherwise it will trap references to objects
627 626 # contained therein.
628 627 del sys.modules[main_mod_name]
629 628
630 629 return stats
631 630
632 631 def _run_with_debugger(self, code, code_ns, break_point, filename):
633 632 """
634 633 Run `code` in debugger with a break point.
635 634
636 635 Parameters
637 636 ----------
638 637 code : str
639 638 Code to execute.
640 639 code_ns : dict
641 640 A namespace in which `code` is executed.
642 641 break_point : str
643 642 Line number in the file specified by `filename` argument
644 643 or a string in the format ``file:line``. In the latter
645 644 case, `filename` is ignored.
646 645 See also :func:`.parse_breakpoint`.
647 646 filename : str
648 647 Path to the file in which break point is specified.
649 648
650 649 Raises
651 650 ------
652 651 UsageError
653 652 If no meaningful break point is given by `break_point` and
654 653 `filename`.
655 654
656 655 """
657 656 deb = debugger.Pdb(self.shell.colors)
658 657 # reset Breakpoint state, which is moronically kept
659 658 # in a class
660 659 bdb.Breakpoint.next = 1
661 660 bdb.Breakpoint.bplist = {}
662 661 bdb.Breakpoint.bpbynumber = [None]
663 662 # Set an initial breakpoint to stop execution
664 663 maxtries = 10
665 664 bp_file, bp_line = parse_breakpoint(break_point, filename)
666 665 checkline = deb.checkline(bp_file, bp_line)
667 666 if not checkline:
668 667 for bp in range(bp_line + 1, bp_line + maxtries + 1):
669 668 if deb.checkline(bp_file, bp):
670 669 break
671 670 else:
672 671 msg = ("\nI failed to find a valid line to set "
673 672 "a breakpoint\n"
674 673 "after trying up to line: %s.\n"
675 674 "Please set a valid breakpoint manually "
676 675 "with the -b option." % bp)
677 676 raise UsageError(msg)
678 677 # if we find a good linenumber, set the breakpoint
679 678 deb.do_break('%s:%s' % (bp_file, bp_line))
680 679
681 680 # Mimic Pdb._runscript(...)
682 681 deb._wait_for_mainpyfile = True
683 682 deb.mainpyfile = deb.canonic(filename)
684 683
685 684 # Start file run
686 685 print "NOTE: Enter 'c' at the",
687 686 print "%s prompt to start your script." % deb.prompt
688 687 try:
689 688 #save filename so it can be used by methods on the deb object
690 689 deb._exec_filename = filename
691 690 deb.run(code, code_ns)
692 691
693 692 except:
694 693 etype, value, tb = sys.exc_info()
695 694 # Skip three frames in the traceback: the %run one,
696 695 # one inside bdb.py, and the command-line typed by the
697 696 # user (run by exec in pdb itself).
698 697 self.shell.InteractiveTB(etype, value, tb, tb_offset=3)
699 698
700 699 @staticmethod
701 700 def _run_with_timing(run, nruns):
702 701 """
703 702 Run function `run` and print timing information.
704 703
705 704 Parameters
706 705 ----------
707 706 run : callable
708 707 Any callable object which takes no argument.
709 708 nruns : int
710 709 Number of times to execute `run`.
711 710
712 711 """
713 712 twall0 = time.time()
714 713 if nruns == 1:
715 714 t0 = clock2()
716 715 run()
717 716 t1 = clock2()
718 717 t_usr = t1[0] - t0[0]
719 718 t_sys = t1[1] - t0[1]
720 719 print "\nIPython CPU timings (estimated):"
721 720 print " User : %10.2f s." % t_usr
722 721 print " System : %10.2f s." % t_sys
723 722 else:
724 723 runs = range(nruns)
725 724 t0 = clock2()
726 725 for nr in runs:
727 726 run()
728 727 t1 = clock2()
729 728 t_usr = t1[0] - t0[0]
730 729 t_sys = t1[1] - t0[1]
731 730 print "\nIPython CPU timings (estimated):"
732 731 print "Total runs performed:", nruns
733 732 print " Times : %10s %10s" % ('Total', 'Per run')
734 733 print " User : %10.2f s, %10.2f s." % (t_usr, t_usr / nruns)
735 734 print " System : %10.2f s, %10.2f s." % (t_sys, t_sys / nruns)
736 735 twall1 = time.time()
737 736 print "Wall time: %10.2f s." % (twall1 - twall0)
738 737
739 738 @skip_doctest
740 739 @line_cell_magic
741 740 def timeit(self, line='', cell=None):
742 741 """Time execution of a Python statement or expression
743 742
744 743 Usage, in line mode:
745 744 %timeit [-n<N> -r<R> [-t|-c]] statement
746 745 or in cell mode:
747 746 %%timeit [-n<N> -r<R> [-t|-c]] setup_code
748 747 code
749 748 code...
750 749
751 750 Time execution of a Python statement or expression using the timeit
752 751 module. This function can be used both as a line and cell magic:
753 752
754 753 - In line mode you can time a single-line statement (though multiple
755 754 ones can be chained with using semicolons).
756 755
757 756 - In cell mode, the statement in the first line is used as setup code
758 757 (executed but not timed) and the body of the cell is timed. The cell
759 758 body has access to any variables created in the setup code.
760 759
761 760 Options:
762 761 -n<N>: execute the given statement <N> times in a loop. If this value
763 762 is not given, a fitting value is chosen.
764 763
765 764 -r<R>: repeat the loop iteration <R> times and take the best result.
766 765 Default: 3
767 766
768 767 -t: use time.time to measure the time, which is the default on Unix.
769 768 This function measures wall time.
770 769
771 770 -c: use time.clock to measure the time, which is the default on
772 771 Windows and measures wall time. On Unix, resource.getrusage is used
773 772 instead and returns the CPU user time.
774 773
775 774 -p<P>: use a precision of <P> digits to display the timing result.
776 775 Default: 3
777 776
778 777
779 778 Examples
780 779 --------
781 780 ::
782 781
783 782 In [1]: %timeit pass
784 783 10000000 loops, best of 3: 53.3 ns per loop
785 784
786 785 In [2]: u = None
787 786
788 787 In [3]: %timeit u is None
789 788 10000000 loops, best of 3: 184 ns per loop
790 789
791 790 In [4]: %timeit -r 4 u == None
792 791 1000000 loops, best of 4: 242 ns per loop
793 792
794 793 In [5]: import time
795 794
796 795 In [6]: %timeit -n1 time.sleep(2)
797 796 1 loops, best of 3: 2 s per loop
798 797
799 798
800 799 The times reported by %timeit will be slightly higher than those
801 800 reported by the timeit.py script when variables are accessed. This is
802 801 due to the fact that %timeit executes the statement in the namespace
803 802 of the shell, compared with timeit.py, which uses a single setup
804 803 statement to import function or create variables. Generally, the bias
805 804 does not matter as long as results from timeit.py are not mixed with
806 805 those from %timeit."""
807 806
808 807 import timeit
809 808
810 809 opts, stmt = self.parse_options(line,'n:r:tcp:',
811 810 posix=False, strict=False)
812 811 if stmt == "" and cell is None:
813 812 return
814 813
815 814 timefunc = timeit.default_timer
816 815 number = int(getattr(opts, "n", 0))
817 816 repeat = int(getattr(opts, "r", timeit.default_repeat))
818 817 precision = int(getattr(opts, "p", 3))
819 818 if hasattr(opts, "t"):
820 819 timefunc = time.time
821 820 if hasattr(opts, "c"):
822 821 timefunc = clock
823 822
824 823 timer = timeit.Timer(timer=timefunc)
825 824 # this code has tight coupling to the inner workings of timeit.Timer,
826 825 # but is there a better way to achieve that the code stmt has access
827 826 # to the shell namespace?
828 827 transform = self.shell.input_splitter.transform_cell
829 828
830 829 if cell is None:
831 830 # called as line magic
832 831 ast_setup = ast.parse("pass")
833 832 ast_stmt = ast.parse(transform(stmt))
834 833 else:
835 834 ast_setup = ast.parse(transform(stmt))
836 835 ast_stmt = ast.parse(transform(cell))
837 836
838 837 ast_setup = self.shell.transform_ast(ast_setup)
839 838 ast_stmt = self.shell.transform_ast(ast_stmt)
840 839
841 840 # This codestring is taken from timeit.template - we fill it in as an
842 841 # AST, so that we can apply our AST transformations to the user code
843 842 # without affecting the timing code.
844 843 timeit_ast_template = ast.parse('def inner(_it, _timer):\n'
845 844 ' setup\n'
846 845 ' _t0 = _timer()\n'
847 846 ' for _i in _it:\n'
848 847 ' stmt\n'
849 848 ' _t1 = _timer()\n'
850 849 ' return _t1 - _t0\n')
851 850
852 851 class TimeitTemplateFiller(ast.NodeTransformer):
853 852 "This is quite tightly tied to the template definition above."
854 853 def visit_FunctionDef(self, node):
855 854 "Fill in the setup statement"
856 855 self.generic_visit(node)
857 856 if node.name == "inner":
858 857 node.body[:1] = ast_setup.body
859 858
860 859 return node
861 860
862 861 def visit_For(self, node):
863 862 "Fill in the statement to be timed"
864 863 if getattr(getattr(node.body[0], 'value', None), 'id', None) == 'stmt':
865 864 node.body = ast_stmt.body
866 865 return node
867 866
868 867 timeit_ast = TimeitTemplateFiller().visit(timeit_ast_template)
869 868 timeit_ast = ast.fix_missing_locations(timeit_ast)
870 869
871 870 # Track compilation time so it can be reported if too long
872 871 # Minimum time above which compilation time will be reported
873 872 tc_min = 0.1
874 873
875 874 t0 = clock()
876 875 code = compile(timeit_ast, "<magic-timeit>", "exec")
877 876 tc = clock()-t0
878 877
879 878 ns = {}
880 879 exec code in self.shell.user_ns, ns
881 880 timer.inner = ns["inner"]
882 881
883 882 if number == 0:
884 883 # determine number so that 0.2 <= total time < 2.0
885 884 number = 1
886 885 for i in range(1, 10):
887 886 if timer.timeit(number) >= 0.2:
888 887 break
889 888 number *= 10
890 889
891 890 best = min(timer.repeat(repeat, number)) / number
892 891
893 892 print u"%d loops, best of %d: %s per loop" % (number, repeat,
894 893 _format_time(best, precision))
895 894 if tc > tc_min:
896 895 print "Compiler time: %.2f s" % tc
897 896
898 897 @skip_doctest
899 898 @needs_local_scope
900 899 @line_cell_magic
901 900 def time(self,line='', cell=None, local_ns=None):
902 901 """Time execution of a Python statement or expression.
903 902
904 903 The CPU and wall clock times are printed, and the value of the
905 904 expression (if any) is returned. Note that under Win32, system time
906 905 is always reported as 0, since it can not be measured.
907 906
908 907 This function can be used both as a line and cell magic:
909 908
910 909 - In line mode you can time a single-line statement (though multiple
911 910 ones can be chained with using semicolons).
912 911
913 912 - In cell mode, you can time the cell body (a directly
914 913 following statement raises an error).
915 914
916 915 This function provides very basic timing functionality. Use the timeit
917 916 magic for more controll over the measurement.
918 917
919 918 Examples
920 919 --------
921 920 ::
922 921
923 922 In [1]: %time 2**128
924 923 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
925 924 Wall time: 0.00
926 925 Out[1]: 340282366920938463463374607431768211456L
927 926
928 927 In [2]: n = 1000000
929 928
930 929 In [3]: %time sum(range(n))
931 930 CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s
932 931 Wall time: 1.37
933 932 Out[3]: 499999500000L
934 933
935 934 In [4]: %time print 'hello world'
936 935 hello world
937 936 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
938 937 Wall time: 0.00
939 938
940 939 Note that the time needed by Python to compile the given expression
941 940 will be reported if it is more than 0.1s. In this example, the
942 941 actual exponentiation is done by Python at compilation time, so while
943 942 the expression can take a noticeable amount of time to compute, that
944 943 time is purely due to the compilation:
945 944
946 945 In [5]: %time 3**9999;
947 946 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
948 947 Wall time: 0.00 s
949 948
950 949 In [6]: %time 3**999999;
951 950 CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
952 951 Wall time: 0.00 s
953 952 Compiler : 0.78 s
954 953 """
955 954
956 955 # fail immediately if the given expression can't be compiled
957 956
958 957 if line and cell:
959 958 raise UsageError("Can't use statement directly after '%%time'!")
960 959
961 960 if cell:
962 961 expr = self.shell.input_transformer_manager.transform_cell(cell)
963 962 else:
964 963 expr = self.shell.input_transformer_manager.transform_cell(line)
965 964
966 965 # Minimum time above which parse time will be reported
967 966 tp_min = 0.1
968 967
969 968 t0 = clock()
970 969 expr_ast = ast.parse(expr)
971 970 tp = clock()-t0
972 971
973 972 # Apply AST transformations
974 973 expr_ast = self.shell.transform_ast(expr_ast)
975 974
976 975 # Minimum time above which compilation time will be reported
977 976 tc_min = 0.1
978 977
979 978 if len(expr_ast.body)==1 and isinstance(expr_ast.body[0], ast.Expr):
980 979 mode = 'eval'
981 980 source = '<timed eval>'
982 981 expr_ast = ast.Expression(expr_ast.body[0].value)
983 982 else:
984 983 mode = 'exec'
985 984 source = '<timed exec>'
986 985 t0 = clock()
987 986 code = compile(expr_ast, source, mode)
988 987 tc = clock()-t0
989 988
990 989 # skew measurement as little as possible
991 990 glob = self.shell.user_ns
992 991 wtime = time.time
993 992 # time execution
994 993 wall_st = wtime()
995 994 if mode=='eval':
996 995 st = clock2()
997 996 out = eval(code, glob, local_ns)
998 997 end = clock2()
999 998 else:
1000 999 st = clock2()
1001 1000 exec code in glob, local_ns
1002 1001 end = clock2()
1003 1002 out = None
1004 1003 wall_end = wtime()
1005 1004 # Compute actual times and report
1006 1005 wall_time = wall_end-wall_st
1007 1006 cpu_user = end[0]-st[0]
1008 1007 cpu_sys = end[1]-st[1]
1009 1008 cpu_tot = cpu_user+cpu_sys
1010 1009 # On windows cpu_sys is always zero, so no new information to the next print
1011 1010 if sys.platform != 'win32':
1012 1011 print "CPU times: user %s, sys: %s, total: %s" % \
1013 1012 (_format_time(cpu_user),_format_time(cpu_sys),_format_time(cpu_tot))
1014 1013 print "Wall time: %s" % _format_time(wall_time)
1015 1014 if tc > tc_min:
1016 1015 print "Compiler : %s" % _format_time(tc)
1017 1016 if tp > tp_min:
1018 1017 print "Parser : %s" % _format_time(tp)
1019 1018 return out
1020 1019
1021 1020 @skip_doctest
1022 1021 @line_magic
1023 1022 def macro(self, parameter_s=''):
1024 1023 """Define a macro for future re-execution. It accepts ranges of history,
1025 1024 filenames or string objects.
1026 1025
1027 1026 Usage:\\
1028 1027 %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ...
1029 1028
1030 1029 Options:
1031 1030
1032 1031 -r: use 'raw' input. By default, the 'processed' history is used,
1033 1032 so that magics are loaded in their transformed version to valid
1034 1033 Python. If this option is given, the raw input as typed at the
1035 1034 command line is used instead.
1036 1035
1037 1036 -q: quiet macro definition. By default, a tag line is printed
1038 1037 to indicate the macro has been created, and then the contents of
1039 1038 the macro are printed. If this option is given, then no printout
1040 1039 is produced once the macro is created.
1041 1040
1042 1041 This will define a global variable called `name` which is a string
1043 1042 made of joining the slices and lines you specify (n1,n2,... numbers
1044 1043 above) from your input history into a single string. This variable
1045 1044 acts like an automatic function which re-executes those lines as if
1046 1045 you had typed them. You just type 'name' at the prompt and the code
1047 1046 executes.
1048 1047
1049 1048 The syntax for indicating input ranges is described in %history.
1050 1049
1051 1050 Note: as a 'hidden' feature, you can also use traditional python slice
1052 1051 notation, where N:M means numbers N through M-1.
1053 1052
1054 1053 For example, if your history contains (print using %hist -n )::
1055 1054
1056 1055 44: x=1
1057 1056 45: y=3
1058 1057 46: z=x+y
1059 1058 47: print x
1060 1059 48: a=5
1061 1060 49: print 'x',x,'y',y
1062 1061
1063 1062 you can create a macro with lines 44 through 47 (included) and line 49
1064 1063 called my_macro with::
1065 1064
1066 1065 In [55]: %macro my_macro 44-47 49
1067 1066
1068 1067 Now, typing `my_macro` (without quotes) will re-execute all this code
1069 1068 in one pass.
1070 1069
1071 1070 You don't need to give the line-numbers in order, and any given line
1072 1071 number can appear multiple times. You can assemble macros with any
1073 1072 lines from your input history in any order.
1074 1073
1075 1074 The macro is a simple object which holds its value in an attribute,
1076 1075 but IPython's display system checks for macros and executes them as
1077 1076 code instead of printing them when you type their name.
1078 1077
1079 1078 You can view a macro's contents by explicitly printing it with::
1080 1079
1081 1080 print macro_name
1082 1081
1083 1082 """
1084 1083 opts,args = self.parse_options(parameter_s,'rq',mode='list')
1085 1084 if not args: # List existing macros
1086 1085 return sorted(k for k,v in self.shell.user_ns.iteritems() if\
1087 1086 isinstance(v, Macro))
1088 1087 if len(args) == 1:
1089 1088 raise UsageError(
1090 1089 "%macro insufficient args; usage '%macro name n1-n2 n3-4...")
1091 1090 name, codefrom = args[0], " ".join(args[1:])
1092 1091
1093 1092 #print 'rng',ranges # dbg
1094 1093 try:
1095 1094 lines = self.shell.find_user_code(codefrom, 'r' in opts)
1096 1095 except (ValueError, TypeError) as e:
1097 1096 print e.args[0]
1098 1097 return
1099 1098 macro = Macro(lines)
1100 1099 self.shell.define_macro(name, macro)
1101 1100 if not ( 'q' in opts) :
1102 1101 print 'Macro `%s` created. To execute, type its name (without quotes).' % name
1103 1102 print '=== Macro contents: ==='
1104 1103 print macro,
1105 1104
1106 1105 @magic_arguments.magic_arguments()
1107 1106 @magic_arguments.argument('output', type=str, default='', nargs='?',
1108 1107 help="""The name of the variable in which to store output.
1109 1108 This is a utils.io.CapturedIO object with stdout/err attributes
1110 1109 for the text of the captured output.
1111 1110
1112 1111 CapturedOutput also has a show() method for displaying the output,
1113 1112 and __call__ as well, so you can use that to quickly display the
1114 1113 output.
1115 1114
1116 1115 If unspecified, captured output is discarded.
1117 1116 """
1118 1117 )
1119 1118 @magic_arguments.argument('--no-stderr', action="store_true",
1120 1119 help="""Don't capture stderr."""
1121 1120 )
1122 1121 @magic_arguments.argument('--no-stdout', action="store_true",
1123 1122 help="""Don't capture stdout."""
1124 1123 )
1125 1124 @cell_magic
1126 1125 def capture(self, line, cell):
1127 1126 """run the cell, capturing stdout/err"""
1128 1127 args = magic_arguments.parse_argstring(self.capture, line)
1129 1128 out = not args.no_stdout
1130 1129 err = not args.no_stderr
1131 1130 with capture_output(out, err) as io:
1132 1131 self.shell.run_cell(cell)
1133 1132 if args.output:
1134 1133 self.shell.user_ns[args.output] = io
1135 1134
1136 1135 def parse_breakpoint(text, current_file):
1137 1136 '''Returns (file, line) for file:line and (current_file, line) for line'''
1138 1137 colon = text.find(':')
1139 1138 if colon == -1:
1140 1139 return current_file, int(text)
1141 1140 else:
1142 1141 return text[:colon], int(text[colon+1:])
1143 1142
1144 1143 def _format_time(timespan, precision=3):
1145 1144 """Formats the timespan in a human readable form"""
1146 1145 import math
1147 1146
1148 1147 if timespan >= 60.0:
1149 1148 # we have more than a minute, format that in a human readable form
1150 1149 # Idea from http://snipplr.com/view/5713/
1151 1150 parts = [("d", 60*60*24),("h", 60*60),("min", 60), ("s", 1)]
1152 1151 time = []
1153 1152 leftover = timespan
1154 1153 for suffix, length in parts:
1155 1154 value = int(leftover / length)
1156 1155 if value > 0:
1157 1156 leftover = leftover % length
1158 1157 time.append(u'%s%s' % (str(value), suffix))
1159 1158 if leftover < 1:
1160 1159 break
1161 1160 return " ".join(time)
1162 1161
1163 1162
1164 1163 # Unfortunately the unicode 'micro' symbol can cause problems in
1165 1164 # certain terminals.
1166 1165 # See bug: https://bugs.launchpad.net/ipython/+bug/348466
1167 1166 # Try to prevent crashes by being more secure than it needs to
1168 1167 # E.g. eclipse is able to print a µ, but has no sys.stdout.encoding set.
1169 1168 units = [u"s", u"ms",u'us',"ns"] # the save value
1170 1169 if hasattr(sys.stdout, 'encoding') and sys.stdout.encoding:
1171 1170 try:
1172 1171 u'\xb5'.encode(sys.stdout.encoding)
1173 1172 units = [u"s", u"ms",u'\xb5s',"ns"]
1174 1173 except:
1175 1174 pass
1176 1175 scaling = [1, 1e3, 1e6, 1e9]
1177 1176
1178 1177 if timespan > 0.0:
1179 1178 order = min(-int(math.floor(math.log10(timespan)) // 3), 3)
1180 1179 else:
1181 1180 order = 3
1182 1181 ret = u"%.*g %s" % (precision, timespan * scaling[order], units[order])
1183 1182 return ret
General Comments 0
You need to be logged in to leave comments. Login now