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