##// END OF EJS Templates
fix for #10327: _stack_depth added and {u} string literals removed from core/tests
adityausathe -
Show More
@@ -1,3263 +1,3259 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 abc
15 15 import ast
16 16 import atexit
17 17 import builtins as builtin_mod
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 ultratb
38 38 from IPython.core.alias import Alias, AliasManager
39 39 from IPython.core.autocall import ExitAutocall
40 40 from IPython.core.builtin_trap import BuiltinTrap
41 41 from IPython.core.events import EventManager, available_events
42 42 from IPython.core.compilerop import CachingCompiler, check_linecache_ipython
43 43 from IPython.core.debugger import Pdb
44 44 from IPython.core.display_trap import DisplayTrap
45 45 from IPython.core.displayhook import DisplayHook
46 46 from IPython.core.displaypub import DisplayPublisher
47 47 from IPython.core.error import InputRejected, UsageError
48 48 from IPython.core.extensions import ExtensionManager
49 49 from IPython.core.formatters import DisplayFormatter
50 50 from IPython.core.history import HistoryManager
51 51 from IPython.core.inputsplitter import ESC_MAGIC, ESC_MAGIC2
52 52 from IPython.core.logger import Logger
53 53 from IPython.core.macro import Macro
54 54 from IPython.core.payload import PayloadManager
55 55 from IPython.core.prefilter import PrefilterManager
56 56 from IPython.core.profiledir import ProfileDir
57 57 from IPython.core.usage import default_banner
58 58 from IPython.display import display
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.strdispatch import StrDispatch
71 71 from IPython.utils.syspathcontext import prepended_to_syspath
72 72 from IPython.utils.text import format_screen, LSString, SList, DollarFormatter
73 73 from IPython.utils.tempdir import TemporaryDirectory
74 74 from traitlets import (
75 75 Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type,
76 76 observe, default,
77 77 )
78 78 from warnings import warn
79 79 from logging import error
80 80 import IPython.core.hooks
81 81
82 82 from typing import List as ListType
83 83 from ast import AST
84 84
85 85 # NoOpContext is deprecated, but ipykernel imports it from here.
86 86 # See https://github.com/ipython/ipykernel/issues/157
87 87 from IPython.utils.contexts import NoOpContext
88 88
89 89 try:
90 90 import docrepr.sphinxify as sphx
91 91
92 92 def sphinxify(doc):
93 93 with TemporaryDirectory() as dirname:
94 94 return {
95 95 'text/html': sphx.sphinxify(doc, dirname),
96 96 'text/plain': doc
97 97 }
98 98 except ImportError:
99 99 sphinxify = None
100 100
101 101
102 102 class ProvisionalWarning(DeprecationWarning):
103 103 """
104 104 Warning class for unstable features
105 105 """
106 106 pass
107 107
108 108 if sys.version_info > (3,6):
109 109 _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign)
110 110 _single_targets_nodes = (ast.AugAssign, ast.AnnAssign)
111 111 else:
112 112 _assign_nodes = (ast.AugAssign, ast.Assign )
113 113 _single_targets_nodes = (ast.AugAssign, )
114 114
115 115 #-----------------------------------------------------------------------------
116 116 # Globals
117 117 #-----------------------------------------------------------------------------
118 118
119 119 # compiled regexps for autoindent management
120 120 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
121 121
122 122 #-----------------------------------------------------------------------------
123 123 # Utilities
124 124 #-----------------------------------------------------------------------------
125 125
126 126 @undoc
127 127 def softspace(file, newvalue):
128 128 """Copied from code.py, to remove the dependency"""
129 129
130 130 oldvalue = 0
131 131 try:
132 132 oldvalue = file.softspace
133 133 except AttributeError:
134 134 pass
135 135 try:
136 136 file.softspace = newvalue
137 137 except (AttributeError, TypeError):
138 138 # "attribute-less object" or "read-only attributes"
139 139 pass
140 140 return oldvalue
141 141
142 142 @undoc
143 143 def no_op(*a, **kw):
144 144 pass
145 145
146 146
147 147 class SpaceInInput(Exception): pass
148 148
149 149
150 150 def get_default_colors():
151 151 "DEPRECATED"
152 152 warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.',
153 153 DeprecationWarning, stacklevel=2)
154 154 return 'Neutral'
155 155
156 156
157 157 class SeparateUnicode(Unicode):
158 158 r"""A Unicode subclass to validate separate_in, separate_out, etc.
159 159
160 160 This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``.
161 161 """
162 162
163 163 def validate(self, obj, value):
164 164 if value == '0': value = ''
165 165 value = value.replace('\\n','\n')
166 166 return super(SeparateUnicode, self).validate(obj, value)
167 167
168 168
169 169 @undoc
170 170 class DummyMod(object):
171 171 """A dummy module used for IPython's interactive module when
172 172 a namespace must be assigned to the module's __dict__."""
173 173 pass
174 174
175 175
176 176 class ExecutionResult(object):
177 177 """The result of a call to :meth:`InteractiveShell.run_cell`
178 178
179 179 Stores information about what took place.
180 180 """
181 181 execution_count = None
182 182 error_before_exec = None
183 183 error_in_exec = None
184 184 result = None
185 185
186 186 @property
187 187 def success(self):
188 188 return (self.error_before_exec is None) and (self.error_in_exec is None)
189 189
190 190 def raise_error(self):
191 191 """Reraises error if `success` is `False`, otherwise does nothing"""
192 192 if self.error_before_exec is not None:
193 193 raise self.error_before_exec
194 194 if self.error_in_exec is not None:
195 195 raise self.error_in_exec
196 196
197 197 def __repr__(self):
198 198 name = self.__class__.__qualname__
199 199 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
200 200 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
201 201
202 202
203 203 class InteractiveShell(SingletonConfigurable):
204 204 """An enhanced, interactive shell for Python."""
205 205
206 206 _instance = None
207 207
208 208 ast_transformers = List([], help=
209 209 """
210 210 A list of ast.NodeTransformer subclass instances, which will be applied
211 211 to user input before code is run.
212 212 """
213 213 ).tag(config=True)
214 214
215 215 autocall = Enum((0,1,2), default_value=0, help=
216 216 """
217 217 Make IPython automatically call any callable object even if you didn't
218 218 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
219 219 automatically. The value can be '0' to disable the feature, '1' for
220 220 'smart' autocall, where it is not applied if there are no more
221 221 arguments on the line, and '2' for 'full' autocall, where all callable
222 222 objects are automatically called (even if no arguments are present).
223 223 """
224 224 ).tag(config=True)
225 225 # TODO: remove all autoindent logic and put into frontends.
226 226 # We can't do this yet because even runlines uses the autoindent.
227 227 autoindent = Bool(True, help=
228 228 """
229 229 Autoindent IPython code entered interactively.
230 230 """
231 231 ).tag(config=True)
232 232
233 233 automagic = Bool(True, help=
234 234 """
235 235 Enable magic commands to be called without the leading %.
236 236 """
237 237 ).tag(config=True)
238 238
239 239 banner1 = Unicode(default_banner,
240 240 help="""The part of the banner to be printed before the profile"""
241 241 ).tag(config=True)
242 242 banner2 = Unicode('',
243 243 help="""The part of the banner to be printed after the profile"""
244 244 ).tag(config=True)
245 245
246 246 cache_size = Integer(1000, help=
247 247 """
248 248 Set the size of the output cache. The default is 1000, you can
249 249 change it permanently in your config file. Setting it to 0 completely
250 250 disables the caching system, and the minimum value accepted is 3 (if
251 251 you provide a value less than 3, it is reset to 0 and a warning is
252 252 issued). This limit is defined because otherwise you'll spend more
253 253 time re-flushing a too small cache than working
254 254 """
255 255 ).tag(config=True)
256 256 color_info = Bool(True, help=
257 257 """
258 258 Use colors for displaying information about objects. Because this
259 259 information is passed through a pager (like 'less'), and some pagers
260 260 get confused with color codes, this capability can be turned off.
261 261 """
262 262 ).tag(config=True)
263 263 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
264 264 default_value='Neutral',
265 265 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
266 266 ).tag(config=True)
267 267 debug = Bool(False).tag(config=True)
268 268 disable_failing_post_execute = Bool(False,
269 269 help="Don't call post-execute functions that have failed in the past."
270 270 ).tag(config=True)
271 271 display_formatter = Instance(DisplayFormatter, allow_none=True)
272 272 displayhook_class = Type(DisplayHook)
273 273 display_pub_class = Type(DisplayPublisher)
274 274
275 275 sphinxify_docstring = Bool(False, help=
276 276 """
277 277 Enables rich html representation of docstrings. (This requires the
278 278 docrepr module).
279 279 """).tag(config=True)
280 280
281 281 @observe("sphinxify_docstring")
282 282 def _sphinxify_docstring_changed(self, change):
283 283 if change['new']:
284 284 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
285 285
286 286 enable_html_pager = Bool(False, help=
287 287 """
288 288 (Provisional API) enables html representation in mime bundles sent
289 289 to pagers.
290 290 """).tag(config=True)
291 291
292 292 @observe("enable_html_pager")
293 293 def _enable_html_pager_changed(self, change):
294 294 if change['new']:
295 295 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
296 296
297 297 data_pub_class = None
298 298
299 299 exit_now = Bool(False)
300 300 exiter = Instance(ExitAutocall)
301 301 @default('exiter')
302 302 def _exiter_default(self):
303 303 return ExitAutocall(self)
304 304 # Monotonically increasing execution counter
305 305 execution_count = Integer(1)
306 306 filename = Unicode("<ipython console>")
307 307 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
308 308
309 309 # Input splitter, to transform input line by line and detect when a block
310 310 # is ready to be executed.
311 311 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
312 312 (), {'line_input_checker': True})
313 313
314 314 # This InputSplitter instance is used to transform completed cells before
315 315 # running them. It allows cell magics to contain blank lines.
316 316 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
317 317 (), {'line_input_checker': False})
318 318
319 319 logstart = Bool(False, help=
320 320 """
321 321 Start logging to the default log file in overwrite mode.
322 322 Use `logappend` to specify a log file to **append** logs to.
323 323 """
324 324 ).tag(config=True)
325 325 logfile = Unicode('', help=
326 326 """
327 327 The name of the logfile to use.
328 328 """
329 329 ).tag(config=True)
330 330 logappend = Unicode('', help=
331 331 """
332 332 Start logging to the given file in append mode.
333 333 Use `logfile` to specify a log file to **overwrite** logs to.
334 334 """
335 335 ).tag(config=True)
336 336 object_info_string_level = Enum((0,1,2), default_value=0,
337 337 ).tag(config=True)
338 338 pdb = Bool(False, help=
339 339 """
340 340 Automatically call the pdb debugger after every exception.
341 341 """
342 342 ).tag(config=True)
343 343 display_page = Bool(False,
344 344 help="""If True, anything that would be passed to the pager
345 345 will be displayed as regular output instead."""
346 346 ).tag(config=True)
347 347
348 348 # deprecated prompt traits:
349 349
350 350 prompt_in1 = Unicode('In [\\#]: ',
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 prompt_in2 = Unicode(' .\\D.: ',
354 354 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
355 355 ).tag(config=True)
356 356 prompt_out = Unicode('Out[\\#]: ',
357 357 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
358 358 ).tag(config=True)
359 359 prompts_pad_left = Bool(True,
360 360 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
361 361 ).tag(config=True)
362 362
363 363 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
364 364 def _prompt_trait_changed(self, change):
365 365 name = change['name']
366 366 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
367 367 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
368 368 " object directly.".format(name=name))
369 369
370 370 # protect against weird cases where self.config may not exist:
371 371
372 372 show_rewritten_input = Bool(True,
373 373 help="Show rewritten input, e.g. for autocall."
374 374 ).tag(config=True)
375 375
376 376 quiet = Bool(False).tag(config=True)
377 377
378 378 history_length = Integer(10000,
379 379 help='Total length of command history'
380 380 ).tag(config=True)
381 381
382 382 history_load_length = Integer(1000, help=
383 383 """
384 384 The number of saved history entries to be loaded
385 385 into the history buffer at startup.
386 386 """
387 387 ).tag(config=True)
388 388
389 389 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
390 390 default_value='last_expr',
391 391 help="""
392 392 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
393 393 which nodes should be run interactively (displaying output from expressions).
394 394 """
395 395 ).tag(config=True)
396 396
397 397 # TODO: this part of prompt management should be moved to the frontends.
398 398 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
399 399 separate_in = SeparateUnicode('\n').tag(config=True)
400 400 separate_out = SeparateUnicode('').tag(config=True)
401 401 separate_out2 = SeparateUnicode('').tag(config=True)
402 402 wildcards_case_sensitive = Bool(True).tag(config=True)
403 403 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
404 404 default_value='Context',
405 405 help="Switch modes for the IPython exception handlers."
406 406 ).tag(config=True)
407 407
408 408 # Subcomponents of InteractiveShell
409 409 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
410 410 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
411 411 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
412 412 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
413 413 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
414 414 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
415 415 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
416 416 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
417 417
418 418 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
419 419 @property
420 420 def profile(self):
421 421 if self.profile_dir is not None:
422 422 name = os.path.basename(self.profile_dir.location)
423 423 return name.replace('profile_','')
424 424
425 425
426 426 # Private interface
427 427 _post_execute = Dict()
428 428
429 429 # Tracks any GUI loop loaded for pylab
430 430 pylab_gui_select = None
431 431
432 432 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
433 433
434 434 def __init__(self, ipython_dir=None, profile_dir=None,
435 435 user_module=None, user_ns=None,
436 436 custom_exceptions=((), None), **kwargs):
437 437
438 438 # This is where traits with a config_key argument are updated
439 439 # from the values on config.
440 440 super(InteractiveShell, self).__init__(**kwargs)
441 441 if 'PromptManager' in self.config:
442 442 warn('As of IPython 5.0 `PromptManager` config will have no effect'
443 443 ' and has been replaced by TerminalInteractiveShell.prompts_class')
444 444 self.configurables = [self]
445 445
446 446 # These are relatively independent and stateless
447 447 self.init_ipython_dir(ipython_dir)
448 448 self.init_profile_dir(profile_dir)
449 449 self.init_instance_attrs()
450 450 self.init_environment()
451 451
452 452 # Check if we're in a virtualenv, and set up sys.path.
453 453 self.init_virtualenv()
454 454
455 455 # Create namespaces (user_ns, user_global_ns, etc.)
456 456 self.init_create_namespaces(user_module, user_ns)
457 457 # This has to be done after init_create_namespaces because it uses
458 458 # something in self.user_ns, but before init_sys_modules, which
459 459 # is the first thing to modify sys.
460 460 # TODO: When we override sys.stdout and sys.stderr before this class
461 461 # is created, we are saving the overridden ones here. Not sure if this
462 462 # is what we want to do.
463 463 self.save_sys_module_state()
464 464 self.init_sys_modules()
465 465
466 466 # While we're trying to have each part of the code directly access what
467 467 # it needs without keeping redundant references to objects, we have too
468 468 # much legacy code that expects ip.db to exist.
469 469 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
470 470
471 471 self.init_history()
472 472 self.init_encoding()
473 473 self.init_prefilter()
474 474
475 475 self.init_syntax_highlighting()
476 476 self.init_hooks()
477 477 self.init_events()
478 478 self.init_pushd_popd_magic()
479 479 self.init_user_ns()
480 480 self.init_logger()
481 481 self.init_builtins()
482 482
483 483 # The following was in post_config_initialization
484 484 self.init_inspector()
485 485 self.raw_input_original = input
486 486 self.init_completer()
487 487 # TODO: init_io() needs to happen before init_traceback handlers
488 488 # because the traceback handlers hardcode the stdout/stderr streams.
489 489 # This logic in in debugger.Pdb and should eventually be changed.
490 490 self.init_io()
491 491 self.init_traceback_handlers(custom_exceptions)
492 492 self.init_prompts()
493 493 self.init_display_formatter()
494 494 self.init_display_pub()
495 495 self.init_data_pub()
496 496 self.init_displayhook()
497 497 self.init_magics()
498 498 self.init_alias()
499 499 self.init_logstart()
500 500 self.init_pdb()
501 501 self.init_extension_manager()
502 502 self.init_payload()
503 503 self.init_deprecation_warnings()
504 504 self.hooks.late_startup_hook()
505 505 self.events.trigger('shell_initialized', self)
506 506 atexit.register(self.atexit_operations)
507 507
508 508 def get_ipython(self):
509 509 """Return the currently running IPython instance."""
510 510 return self
511 511
512 512 #-------------------------------------------------------------------------
513 513 # Trait changed handlers
514 514 #-------------------------------------------------------------------------
515 515 @observe('ipython_dir')
516 516 def _ipython_dir_changed(self, change):
517 517 ensure_dir_exists(change['new'])
518 518
519 519 def set_autoindent(self,value=None):
520 520 """Set the autoindent flag.
521 521
522 522 If called with no arguments, it acts as a toggle."""
523 523 if value is None:
524 524 self.autoindent = not self.autoindent
525 525 else:
526 526 self.autoindent = value
527 527
528 528 #-------------------------------------------------------------------------
529 529 # init_* methods called by __init__
530 530 #-------------------------------------------------------------------------
531 531
532 532 def init_ipython_dir(self, ipython_dir):
533 533 if ipython_dir is not None:
534 534 self.ipython_dir = ipython_dir
535 535 return
536 536
537 537 self.ipython_dir = get_ipython_dir()
538 538
539 539 def init_profile_dir(self, profile_dir):
540 540 if profile_dir is not None:
541 541 self.profile_dir = profile_dir
542 542 return
543 543 self.profile_dir =\
544 544 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
545 545
546 546 def init_instance_attrs(self):
547 547 self.more = False
548 548
549 549 # command compiler
550 550 self.compile = CachingCompiler()
551 551
552 552 # Make an empty namespace, which extension writers can rely on both
553 553 # existing and NEVER being used by ipython itself. This gives them a
554 554 # convenient location for storing additional information and state
555 555 # their extensions may require, without fear of collisions with other
556 556 # ipython names that may develop later.
557 557 self.meta = Struct()
558 558
559 559 # Temporary files used for various purposes. Deleted at exit.
560 560 self.tempfiles = []
561 561 self.tempdirs = []
562 562
563 563 # keep track of where we started running (mainly for crash post-mortem)
564 564 # This is not being used anywhere currently.
565 565 self.starting_dir = os.getcwd()
566 566
567 567 # Indentation management
568 568 self.indent_current_nsp = 0
569 569
570 570 # Dict to track post-execution functions that have been registered
571 571 self._post_execute = {}
572 572
573 573 def init_environment(self):
574 574 """Any changes we need to make to the user's environment."""
575 575 pass
576 576
577 577 def init_encoding(self):
578 578 # Get system encoding at startup time. Certain terminals (like Emacs
579 579 # under Win32 have it set to None, and we need to have a known valid
580 580 # encoding to use in the raw_input() method
581 581 try:
582 582 self.stdin_encoding = sys.stdin.encoding or 'ascii'
583 583 except AttributeError:
584 584 self.stdin_encoding = 'ascii'
585 585
586 586
587 587 @observe('colors')
588 588 def init_syntax_highlighting(self, changes=None):
589 589 # Python source parser/formatter for syntax highlighting
590 590 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
591 591 self.pycolorize = lambda src: pyformat(src,'str')
592 592
593 593 def refresh_style(self):
594 594 # No-op here, used in subclass
595 595 pass
596 596
597 597 def init_pushd_popd_magic(self):
598 598 # for pushd/popd management
599 599 self.home_dir = get_home_dir()
600 600
601 601 self.dir_stack = []
602 602
603 603 def init_logger(self):
604 604 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
605 605 logmode='rotate')
606 606
607 607 def init_logstart(self):
608 608 """Initialize logging in case it was requested at the command line.
609 609 """
610 610 if self.logappend:
611 611 self.magic('logstart %s append' % self.logappend)
612 612 elif self.logfile:
613 613 self.magic('logstart %s' % self.logfile)
614 614 elif self.logstart:
615 615 self.magic('logstart')
616 616
617 617 def init_deprecation_warnings(self):
618 618 """
619 619 register default filter for deprecation warning.
620 620
621 621 This will allow deprecation warning of function used interactively to show
622 622 warning to users, and still hide deprecation warning from libraries import.
623 623 """
624 624 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
625 625
626 626 def init_builtins(self):
627 627 # A single, static flag that we set to True. Its presence indicates
628 628 # that an IPython shell has been created, and we make no attempts at
629 629 # removing on exit or representing the existence of more than one
630 630 # IPython at a time.
631 631 builtin_mod.__dict__['__IPYTHON__'] = True
632 632 builtin_mod.__dict__['display'] = display
633 633
634 634 self.builtin_trap = BuiltinTrap(shell=self)
635 635
636 636 def init_inspector(self):
637 637 # Object inspector
638 638 self.inspector = oinspect.Inspector(oinspect.InspectColors,
639 639 PyColorize.ANSICodeColors,
640 640 self.colors,
641 641 self.object_info_string_level)
642 642
643 643 def init_io(self):
644 644 # This will just use sys.stdout and sys.stderr. If you want to
645 645 # override sys.stdout and sys.stderr themselves, you need to do that
646 646 # *before* instantiating this class, because io holds onto
647 647 # references to the underlying streams.
648 648 # io.std* are deprecated, but don't show our own deprecation warnings
649 649 # during initialization of the deprecated API.
650 650 with warnings.catch_warnings():
651 651 warnings.simplefilter('ignore', DeprecationWarning)
652 652 io.stdout = io.IOStream(sys.stdout)
653 653 io.stderr = io.IOStream(sys.stderr)
654 654
655 655 def init_prompts(self):
656 656 # Set system prompts, so that scripts can decide if they are running
657 657 # interactively.
658 658 sys.ps1 = 'In : '
659 659 sys.ps2 = '...: '
660 660 sys.ps3 = 'Out: '
661 661
662 662 def init_display_formatter(self):
663 663 self.display_formatter = DisplayFormatter(parent=self)
664 664 self.configurables.append(self.display_formatter)
665 665
666 666 def init_display_pub(self):
667 667 self.display_pub = self.display_pub_class(parent=self)
668 668 self.configurables.append(self.display_pub)
669 669
670 670 def init_data_pub(self):
671 671 if not self.data_pub_class:
672 672 self.data_pub = None
673 673 return
674 674 self.data_pub = self.data_pub_class(parent=self)
675 675 self.configurables.append(self.data_pub)
676 676
677 677 def init_displayhook(self):
678 678 # Initialize displayhook, set in/out prompts and printing system
679 679 self.displayhook = self.displayhook_class(
680 680 parent=self,
681 681 shell=self,
682 682 cache_size=self.cache_size,
683 683 )
684 684 self.configurables.append(self.displayhook)
685 685 # This is a context manager that installs/revmoes the displayhook at
686 686 # the appropriate time.
687 687 self.display_trap = DisplayTrap(hook=self.displayhook)
688 688
689 689 def init_virtualenv(self):
690 690 """Add a virtualenv to sys.path so the user can import modules from it.
691 691 This isn't perfect: it doesn't use the Python interpreter with which the
692 692 virtualenv was built, and it ignores the --no-site-packages option. A
693 693 warning will appear suggesting the user installs IPython in the
694 694 virtualenv, but for many cases, it probably works well enough.
695 695
696 696 Adapted from code snippets online.
697 697
698 698 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
699 699 """
700 700 if 'VIRTUAL_ENV' not in os.environ:
701 701 # Not in a virtualenv
702 702 return
703 703
704 704 # venv detection:
705 705 # stdlib venv may symlink sys.executable, so we can't use realpath.
706 706 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
707 707 # So we just check every item in the symlink tree (generally <= 3)
708 708 p = os.path.normcase(sys.executable)
709 709 paths = [p]
710 710 while os.path.islink(p):
711 711 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
712 712 paths.append(p)
713 713 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
714 714
715 715 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
716 716 if p_venv.startswith('\\cygdrive'):
717 717 p_venv = p_venv[11:]
718 718 elif p_venv[1] == ':':
719 719 p_venv = p_venv[2:]
720 720
721 721 if any(p_venv in p for p in paths):
722 722 # Running properly in the virtualenv, don't need to do anything
723 723 return
724 724
725 725 warn("Attempting to work in a virtualenv. If you encounter problems, please "
726 726 "install IPython inside the virtualenv.")
727 727 if sys.platform == "win32":
728 728 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
729 729 else:
730 730 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
731 731 'python%d.%d' % sys.version_info[:2], 'site-packages')
732 732
733 733 import site
734 734 sys.path.insert(0, virtual_env)
735 735 site.addsitedir(virtual_env)
736 736
737 737 #-------------------------------------------------------------------------
738 738 # Things related to injections into the sys module
739 739 #-------------------------------------------------------------------------
740 740
741 741 def save_sys_module_state(self):
742 742 """Save the state of hooks in the sys module.
743 743
744 744 This has to be called after self.user_module is created.
745 745 """
746 746 self._orig_sys_module_state = {'stdin': sys.stdin,
747 747 'stdout': sys.stdout,
748 748 'stderr': sys.stderr,
749 749 'excepthook': sys.excepthook}
750 750 self._orig_sys_modules_main_name = self.user_module.__name__
751 751 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
752 752
753 753 def restore_sys_module_state(self):
754 754 """Restore the state of the sys module."""
755 755 try:
756 756 for k, v in self._orig_sys_module_state.items():
757 757 setattr(sys, k, v)
758 758 except AttributeError:
759 759 pass
760 760 # Reset what what done in self.init_sys_modules
761 761 if self._orig_sys_modules_main_mod is not None:
762 762 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
763 763
764 764 #-------------------------------------------------------------------------
765 765 # Things related to the banner
766 766 #-------------------------------------------------------------------------
767 767
768 768 @property
769 769 def banner(self):
770 770 banner = self.banner1
771 771 if self.profile and self.profile != 'default':
772 772 banner += '\nIPython profile: %s\n' % self.profile
773 773 if self.banner2:
774 774 banner += '\n' + self.banner2
775 775 return banner
776 776
777 777 def show_banner(self, banner=None):
778 778 if banner is None:
779 779 banner = self.banner
780 780 sys.stdout.write(banner)
781 781
782 782 #-------------------------------------------------------------------------
783 783 # Things related to hooks
784 784 #-------------------------------------------------------------------------
785 785
786 786 def init_hooks(self):
787 787 # hooks holds pointers used for user-side customizations
788 788 self.hooks = Struct()
789 789
790 790 self.strdispatchers = {}
791 791
792 792 # Set all default hooks, defined in the IPython.hooks module.
793 793 hooks = IPython.core.hooks
794 794 for hook_name in hooks.__all__:
795 795 # default hooks have priority 100, i.e. low; user hooks should have
796 796 # 0-100 priority
797 797 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
798 798
799 799 if self.display_page:
800 800 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
801 801
802 802 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
803 803 _warn_deprecated=True):
804 804 """set_hook(name,hook) -> sets an internal IPython hook.
805 805
806 806 IPython exposes some of its internal API as user-modifiable hooks. By
807 807 adding your function to one of these hooks, you can modify IPython's
808 808 behavior to call at runtime your own routines."""
809 809
810 810 # At some point in the future, this should validate the hook before it
811 811 # accepts it. Probably at least check that the hook takes the number
812 812 # of args it's supposed to.
813 813
814 814 f = types.MethodType(hook,self)
815 815
816 816 # check if the hook is for strdispatcher first
817 817 if str_key is not None:
818 818 sdp = self.strdispatchers.get(name, StrDispatch())
819 819 sdp.add_s(str_key, f, priority )
820 820 self.strdispatchers[name] = sdp
821 821 return
822 822 if re_key is not None:
823 823 sdp = self.strdispatchers.get(name, StrDispatch())
824 824 sdp.add_re(re.compile(re_key), f, priority )
825 825 self.strdispatchers[name] = sdp
826 826 return
827 827
828 828 dp = getattr(self.hooks, name, None)
829 829 if name not in IPython.core.hooks.__all__:
830 830 print("Warning! Hook '%s' is not one of %s" % \
831 831 (name, IPython.core.hooks.__all__ ))
832 832
833 833 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
834 834 alternative = IPython.core.hooks.deprecated[name]
835 835 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
836 836
837 837 if not dp:
838 838 dp = IPython.core.hooks.CommandChainDispatcher()
839 839
840 840 try:
841 841 dp.add(f,priority)
842 842 except AttributeError:
843 843 # it was not commandchain, plain old func - replace
844 844 dp = f
845 845
846 846 setattr(self.hooks,name, dp)
847 847
848 848 #-------------------------------------------------------------------------
849 849 # Things related to events
850 850 #-------------------------------------------------------------------------
851 851
852 852 def init_events(self):
853 853 self.events = EventManager(self, available_events)
854 854
855 855 self.events.register("pre_execute", self._clear_warning_registry)
856 856
857 857 def register_post_execute(self, func):
858 858 """DEPRECATED: Use ip.events.register('post_run_cell', func)
859 859
860 860 Register a function for calling after code execution.
861 861 """
862 862 warn("ip.register_post_execute is deprecated, use "
863 863 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
864 864 self.events.register('post_run_cell', func)
865 865
866 866 def _clear_warning_registry(self):
867 867 # clear the warning registry, so that different code blocks with
868 868 # overlapping line number ranges don't cause spurious suppression of
869 869 # warnings (see gh-6611 for details)
870 870 if "__warningregistry__" in self.user_global_ns:
871 871 del self.user_global_ns["__warningregistry__"]
872 872
873 873 #-------------------------------------------------------------------------
874 874 # Things related to the "main" module
875 875 #-------------------------------------------------------------------------
876 876
877 877 def new_main_mod(self, filename, modname):
878 878 """Return a new 'main' module object for user code execution.
879 879
880 880 ``filename`` should be the path of the script which will be run in the
881 881 module. Requests with the same filename will get the same module, with
882 882 its namespace cleared.
883 883
884 884 ``modname`` should be the module name - normally either '__main__' or
885 885 the basename of the file without the extension.
886 886
887 887 When scripts are executed via %run, we must keep a reference to their
888 888 __main__ module around so that Python doesn't
889 889 clear it, rendering references to module globals useless.
890 890
891 891 This method keeps said reference in a private dict, keyed by the
892 892 absolute path of the script. This way, for multiple executions of the
893 893 same script we only keep one copy of the namespace (the last one),
894 894 thus preventing memory leaks from old references while allowing the
895 895 objects from the last execution to be accessible.
896 896 """
897 897 filename = os.path.abspath(filename)
898 898 try:
899 899 main_mod = self._main_mod_cache[filename]
900 900 except KeyError:
901 901 main_mod = self._main_mod_cache[filename] = types.ModuleType(
902 902 modname,
903 903 doc="Module created for script run in IPython")
904 904 else:
905 905 main_mod.__dict__.clear()
906 906 main_mod.__name__ = modname
907 907
908 908 main_mod.__file__ = filename
909 909 # It seems pydoc (and perhaps others) needs any module instance to
910 910 # implement a __nonzero__ method
911 911 main_mod.__nonzero__ = lambda : True
912 912
913 913 return main_mod
914 914
915 915 def clear_main_mod_cache(self):
916 916 """Clear the cache of main modules.
917 917
918 918 Mainly for use by utilities like %reset.
919 919
920 920 Examples
921 921 --------
922 922
923 923 In [15]: import IPython
924 924
925 925 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
926 926
927 927 In [17]: len(_ip._main_mod_cache) > 0
928 928 Out[17]: True
929 929
930 930 In [18]: _ip.clear_main_mod_cache()
931 931
932 932 In [19]: len(_ip._main_mod_cache) == 0
933 933 Out[19]: True
934 934 """
935 935 self._main_mod_cache.clear()
936 936
937 937 #-------------------------------------------------------------------------
938 938 # Things related to debugging
939 939 #-------------------------------------------------------------------------
940 940
941 941 def init_pdb(self):
942 942 # Set calling of pdb on exceptions
943 943 # self.call_pdb is a property
944 944 self.call_pdb = self.pdb
945 945
946 946 def _get_call_pdb(self):
947 947 return self._call_pdb
948 948
949 949 def _set_call_pdb(self,val):
950 950
951 951 if val not in (0,1,False,True):
952 952 raise ValueError('new call_pdb value must be boolean')
953 953
954 954 # store value in instance
955 955 self._call_pdb = val
956 956
957 957 # notify the actual exception handlers
958 958 self.InteractiveTB.call_pdb = val
959 959
960 960 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
961 961 'Control auto-activation of pdb at exceptions')
962 962
963 963 def debugger(self,force=False):
964 964 """Call the pdb debugger.
965 965
966 966 Keywords:
967 967
968 968 - force(False): by default, this routine checks the instance call_pdb
969 969 flag and does not actually invoke the debugger if the flag is false.
970 970 The 'force' option forces the debugger to activate even if the flag
971 971 is false.
972 972 """
973 973
974 974 if not (force or self.call_pdb):
975 975 return
976 976
977 977 if not hasattr(sys,'last_traceback'):
978 978 error('No traceback has been produced, nothing to debug.')
979 979 return
980 980
981 981 self.InteractiveTB.debugger(force=True)
982 982
983 983 #-------------------------------------------------------------------------
984 984 # Things related to IPython's various namespaces
985 985 #-------------------------------------------------------------------------
986 986 default_user_namespaces = True
987 987
988 988 def init_create_namespaces(self, user_module=None, user_ns=None):
989 989 # Create the namespace where the user will operate. user_ns is
990 990 # normally the only one used, and it is passed to the exec calls as
991 991 # the locals argument. But we do carry a user_global_ns namespace
992 992 # given as the exec 'globals' argument, This is useful in embedding
993 993 # situations where the ipython shell opens in a context where the
994 994 # distinction between locals and globals is meaningful. For
995 995 # non-embedded contexts, it is just the same object as the user_ns dict.
996 996
997 997 # FIXME. For some strange reason, __builtins__ is showing up at user
998 998 # level as a dict instead of a module. This is a manual fix, but I
999 999 # should really track down where the problem is coming from. Alex
1000 1000 # Schmolck reported this problem first.
1001 1001
1002 1002 # A useful post by Alex Martelli on this topic:
1003 1003 # Re: inconsistent value from __builtins__
1004 1004 # Von: Alex Martelli <aleaxit@yahoo.com>
1005 1005 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1006 1006 # Gruppen: comp.lang.python
1007 1007
1008 1008 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1009 1009 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1010 1010 # > <type 'dict'>
1011 1011 # > >>> print type(__builtins__)
1012 1012 # > <type 'module'>
1013 1013 # > Is this difference in return value intentional?
1014 1014
1015 1015 # Well, it's documented that '__builtins__' can be either a dictionary
1016 1016 # or a module, and it's been that way for a long time. Whether it's
1017 1017 # intentional (or sensible), I don't know. In any case, the idea is
1018 1018 # that if you need to access the built-in namespace directly, you
1019 1019 # should start with "import __builtin__" (note, no 's') which will
1020 1020 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1021 1021
1022 1022 # These routines return a properly built module and dict as needed by
1023 1023 # the rest of the code, and can also be used by extension writers to
1024 1024 # generate properly initialized namespaces.
1025 1025 if (user_ns is not None) or (user_module is not None):
1026 1026 self.default_user_namespaces = False
1027 1027 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1028 1028
1029 1029 # A record of hidden variables we have added to the user namespace, so
1030 1030 # we can list later only variables defined in actual interactive use.
1031 1031 self.user_ns_hidden = {}
1032 1032
1033 1033 # Now that FakeModule produces a real module, we've run into a nasty
1034 1034 # problem: after script execution (via %run), the module where the user
1035 1035 # code ran is deleted. Now that this object is a true module (needed
1036 1036 # so doctest and other tools work correctly), the Python module
1037 1037 # teardown mechanism runs over it, and sets to None every variable
1038 1038 # present in that module. Top-level references to objects from the
1039 1039 # script survive, because the user_ns is updated with them. However,
1040 1040 # calling functions defined in the script that use other things from
1041 1041 # the script will fail, because the function's closure had references
1042 1042 # to the original objects, which are now all None. So we must protect
1043 1043 # these modules from deletion by keeping a cache.
1044 1044 #
1045 1045 # To avoid keeping stale modules around (we only need the one from the
1046 1046 # last run), we use a dict keyed with the full path to the script, so
1047 1047 # only the last version of the module is held in the cache. Note,
1048 1048 # however, that we must cache the module *namespace contents* (their
1049 1049 # __dict__). Because if we try to cache the actual modules, old ones
1050 1050 # (uncached) could be destroyed while still holding references (such as
1051 1051 # those held by GUI objects that tend to be long-lived)>
1052 1052 #
1053 1053 # The %reset command will flush this cache. See the cache_main_mod()
1054 1054 # and clear_main_mod_cache() methods for details on use.
1055 1055
1056 1056 # This is the cache used for 'main' namespaces
1057 1057 self._main_mod_cache = {}
1058 1058
1059 1059 # A table holding all the namespaces IPython deals with, so that
1060 1060 # introspection facilities can search easily.
1061 1061 self.ns_table = {'user_global':self.user_module.__dict__,
1062 1062 'user_local':self.user_ns,
1063 1063 'builtin':builtin_mod.__dict__
1064 1064 }
1065 1065
1066 1066 @property
1067 1067 def user_global_ns(self):
1068 1068 return self.user_module.__dict__
1069 1069
1070 1070 def prepare_user_module(self, user_module=None, user_ns=None):
1071 1071 """Prepare the module and namespace in which user code will be run.
1072 1072
1073 1073 When IPython is started normally, both parameters are None: a new module
1074 1074 is created automatically, and its __dict__ used as the namespace.
1075 1075
1076 1076 If only user_module is provided, its __dict__ is used as the namespace.
1077 1077 If only user_ns is provided, a dummy module is created, and user_ns
1078 1078 becomes the global namespace. If both are provided (as they may be
1079 1079 when embedding), user_ns is the local namespace, and user_module
1080 1080 provides the global namespace.
1081 1081
1082 1082 Parameters
1083 1083 ----------
1084 1084 user_module : module, optional
1085 1085 The current user module in which IPython is being run. If None,
1086 1086 a clean module will be created.
1087 1087 user_ns : dict, optional
1088 1088 A namespace in which to run interactive commands.
1089 1089
1090 1090 Returns
1091 1091 -------
1092 1092 A tuple of user_module and user_ns, each properly initialised.
1093 1093 """
1094 1094 if user_module is None and user_ns is not None:
1095 1095 user_ns.setdefault("__name__", "__main__")
1096 1096 user_module = DummyMod()
1097 1097 user_module.__dict__ = user_ns
1098 1098
1099 1099 if user_module is None:
1100 1100 user_module = types.ModuleType("__main__",
1101 1101 doc="Automatically created module for IPython interactive environment")
1102 1102
1103 1103 # We must ensure that __builtin__ (without the final 's') is always
1104 1104 # available and pointing to the __builtin__ *module*. For more details:
1105 1105 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1106 1106 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1107 1107 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1108 1108
1109 1109 if user_ns is None:
1110 1110 user_ns = user_module.__dict__
1111 1111
1112 1112 return user_module, user_ns
1113 1113
1114 1114 def init_sys_modules(self):
1115 1115 # We need to insert into sys.modules something that looks like a
1116 1116 # module but which accesses the IPython namespace, for shelve and
1117 1117 # pickle to work interactively. Normally they rely on getting
1118 1118 # everything out of __main__, but for embedding purposes each IPython
1119 1119 # instance has its own private namespace, so we can't go shoving
1120 1120 # everything into __main__.
1121 1121
1122 1122 # note, however, that we should only do this for non-embedded
1123 1123 # ipythons, which really mimic the __main__.__dict__ with their own
1124 1124 # namespace. Embedded instances, on the other hand, should not do
1125 1125 # this because they need to manage the user local/global namespaces
1126 1126 # only, but they live within a 'normal' __main__ (meaning, they
1127 1127 # shouldn't overtake the execution environment of the script they're
1128 1128 # embedded in).
1129 1129
1130 1130 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1131 1131 main_name = self.user_module.__name__
1132 1132 sys.modules[main_name] = self.user_module
1133 1133
1134 1134 def init_user_ns(self):
1135 1135 """Initialize all user-visible namespaces to their minimum defaults.
1136 1136
1137 1137 Certain history lists are also initialized here, as they effectively
1138 1138 act as user namespaces.
1139 1139
1140 1140 Notes
1141 1141 -----
1142 1142 All data structures here are only filled in, they are NOT reset by this
1143 1143 method. If they were not empty before, data will simply be added to
1144 1144 therm.
1145 1145 """
1146 1146 # This function works in two parts: first we put a few things in
1147 1147 # user_ns, and we sync that contents into user_ns_hidden so that these
1148 1148 # initial variables aren't shown by %who. After the sync, we add the
1149 1149 # rest of what we *do* want the user to see with %who even on a new
1150 1150 # session (probably nothing, so they really only see their own stuff)
1151 1151
1152 1152 # The user dict must *always* have a __builtin__ reference to the
1153 1153 # Python standard __builtin__ namespace, which must be imported.
1154 1154 # This is so that certain operations in prompt evaluation can be
1155 1155 # reliably executed with builtins. Note that we can NOT use
1156 1156 # __builtins__ (note the 's'), because that can either be a dict or a
1157 1157 # module, and can even mutate at runtime, depending on the context
1158 1158 # (Python makes no guarantees on it). In contrast, __builtin__ is
1159 1159 # always a module object, though it must be explicitly imported.
1160 1160
1161 1161 # For more details:
1162 1162 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1163 1163 ns = {}
1164 1164
1165 1165 # make global variables for user access to the histories
1166 1166 ns['_ih'] = self.history_manager.input_hist_parsed
1167 1167 ns['_oh'] = self.history_manager.output_hist
1168 1168 ns['_dh'] = self.history_manager.dir_hist
1169 1169
1170 1170 # user aliases to input and output histories. These shouldn't show up
1171 1171 # in %who, as they can have very large reprs.
1172 1172 ns['In'] = self.history_manager.input_hist_parsed
1173 1173 ns['Out'] = self.history_manager.output_hist
1174 1174
1175 1175 # Store myself as the public api!!!
1176 1176 ns['get_ipython'] = self.get_ipython
1177 1177
1178 1178 ns['exit'] = self.exiter
1179 1179 ns['quit'] = self.exiter
1180 1180
1181 1181 # Sync what we've added so far to user_ns_hidden so these aren't seen
1182 1182 # by %who
1183 1183 self.user_ns_hidden.update(ns)
1184 1184
1185 1185 # Anything put into ns now would show up in %who. Think twice before
1186 1186 # putting anything here, as we really want %who to show the user their
1187 1187 # stuff, not our variables.
1188 1188
1189 1189 # Finally, update the real user's namespace
1190 1190 self.user_ns.update(ns)
1191 1191
1192 1192 @property
1193 1193 def all_ns_refs(self):
1194 1194 """Get a list of references to all the namespace dictionaries in which
1195 1195 IPython might store a user-created object.
1196 1196
1197 1197 Note that this does not include the displayhook, which also caches
1198 1198 objects from the output."""
1199 1199 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1200 1200 [m.__dict__ for m in self._main_mod_cache.values()]
1201 1201
1202 1202 def reset(self, new_session=True):
1203 1203 """Clear all internal namespaces, and attempt to release references to
1204 1204 user objects.
1205 1205
1206 1206 If new_session is True, a new history session will be opened.
1207 1207 """
1208 1208 # Clear histories
1209 1209 self.history_manager.reset(new_session)
1210 1210 # Reset counter used to index all histories
1211 1211 if new_session:
1212 1212 self.execution_count = 1
1213 1213
1214 1214 # Flush cached output items
1215 1215 if self.displayhook.do_full_cache:
1216 1216 self.displayhook.flush()
1217 1217
1218 1218 # The main execution namespaces must be cleared very carefully,
1219 1219 # skipping the deletion of the builtin-related keys, because doing so
1220 1220 # would cause errors in many object's __del__ methods.
1221 1221 if self.user_ns is not self.user_global_ns:
1222 1222 self.user_ns.clear()
1223 1223 ns = self.user_global_ns
1224 1224 drop_keys = set(ns.keys())
1225 1225 drop_keys.discard('__builtin__')
1226 1226 drop_keys.discard('__builtins__')
1227 1227 drop_keys.discard('__name__')
1228 1228 for k in drop_keys:
1229 1229 del ns[k]
1230 1230
1231 1231 self.user_ns_hidden.clear()
1232 1232
1233 1233 # Restore the user namespaces to minimal usability
1234 1234 self.init_user_ns()
1235 1235
1236 1236 # Restore the default and user aliases
1237 1237 self.alias_manager.clear_aliases()
1238 1238 self.alias_manager.init_aliases()
1239 1239
1240 1240 # Flush the private list of module references kept for script
1241 1241 # execution protection
1242 1242 self.clear_main_mod_cache()
1243 1243
1244 1244 def del_var(self, varname, by_name=False):
1245 1245 """Delete a variable from the various namespaces, so that, as
1246 1246 far as possible, we're not keeping any hidden references to it.
1247 1247
1248 1248 Parameters
1249 1249 ----------
1250 1250 varname : str
1251 1251 The name of the variable to delete.
1252 1252 by_name : bool
1253 1253 If True, delete variables with the given name in each
1254 1254 namespace. If False (default), find the variable in the user
1255 1255 namespace, and delete references to it.
1256 1256 """
1257 1257 if varname in ('__builtin__', '__builtins__'):
1258 1258 raise ValueError("Refusing to delete %s" % varname)
1259 1259
1260 1260 ns_refs = self.all_ns_refs
1261 1261
1262 1262 if by_name: # Delete by name
1263 1263 for ns in ns_refs:
1264 1264 try:
1265 1265 del ns[varname]
1266 1266 except KeyError:
1267 1267 pass
1268 1268 else: # Delete by object
1269 1269 try:
1270 1270 obj = self.user_ns[varname]
1271 1271 except KeyError:
1272 1272 raise NameError("name '%s' is not defined" % varname)
1273 1273 # Also check in output history
1274 1274 ns_refs.append(self.history_manager.output_hist)
1275 1275 for ns in ns_refs:
1276 1276 to_delete = [n for n, o in ns.items() if o is obj]
1277 1277 for name in to_delete:
1278 1278 del ns[name]
1279 1279
1280 1280 # displayhook keeps extra references, but not in a dictionary
1281 1281 for name in ('_', '__', '___'):
1282 1282 if getattr(self.displayhook, name) is obj:
1283 1283 setattr(self.displayhook, name, None)
1284 1284
1285 1285 def reset_selective(self, regex=None):
1286 1286 """Clear selective variables from internal namespaces based on a
1287 1287 specified regular expression.
1288 1288
1289 1289 Parameters
1290 1290 ----------
1291 1291 regex : string or compiled pattern, optional
1292 1292 A regular expression pattern that will be used in searching
1293 1293 variable names in the users namespaces.
1294 1294 """
1295 1295 if regex is not None:
1296 1296 try:
1297 1297 m = re.compile(regex)
1298 1298 except TypeError:
1299 1299 raise TypeError('regex must be a string or compiled pattern')
1300 1300 # Search for keys in each namespace that match the given regex
1301 1301 # If a match is found, delete the key/value pair.
1302 1302 for ns in self.all_ns_refs:
1303 1303 for var in ns:
1304 1304 if m.search(var):
1305 1305 del ns[var]
1306 1306
1307 1307 def push(self, variables, interactive=True):
1308 1308 """Inject a group of variables into the IPython user namespace.
1309 1309
1310 1310 Parameters
1311 1311 ----------
1312 1312 variables : dict, str or list/tuple of str
1313 1313 The variables to inject into the user's namespace. If a dict, a
1314 1314 simple update is done. If a str, the string is assumed to have
1315 1315 variable names separated by spaces. A list/tuple of str can also
1316 1316 be used to give the variable names. If just the variable names are
1317 1317 give (list/tuple/str) then the variable values looked up in the
1318 1318 callers frame.
1319 1319 interactive : bool
1320 1320 If True (default), the variables will be listed with the ``who``
1321 1321 magic.
1322 1322 """
1323 1323 vdict = None
1324 1324
1325 1325 # We need a dict of name/value pairs to do namespace updates.
1326 1326 if isinstance(variables, dict):
1327 1327 vdict = variables
1328 1328 elif isinstance(variables, (str, list, tuple)):
1329 1329 if isinstance(variables, str):
1330 1330 vlist = variables.split()
1331 1331 else:
1332 1332 vlist = variables
1333 1333 vdict = {}
1334 1334 cf = sys._getframe(1)
1335 1335 for name in vlist:
1336 1336 try:
1337 1337 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1338 1338 except:
1339 1339 print('Could not get variable %s from %s' %
1340 1340 (name,cf.f_code.co_name))
1341 1341 else:
1342 1342 raise ValueError('variables must be a dict/str/list/tuple')
1343 1343
1344 1344 # Propagate variables to user namespace
1345 1345 self.user_ns.update(vdict)
1346 1346
1347 1347 # And configure interactive visibility
1348 1348 user_ns_hidden = self.user_ns_hidden
1349 1349 if interactive:
1350 1350 for name in vdict:
1351 1351 user_ns_hidden.pop(name, None)
1352 1352 else:
1353 1353 user_ns_hidden.update(vdict)
1354 1354
1355 1355 def drop_by_id(self, variables):
1356 1356 """Remove a dict of variables from the user namespace, if they are the
1357 1357 same as the values in the dictionary.
1358 1358
1359 1359 This is intended for use by extensions: variables that they've added can
1360 1360 be taken back out if they are unloaded, without removing any that the
1361 1361 user has overwritten.
1362 1362
1363 1363 Parameters
1364 1364 ----------
1365 1365 variables : dict
1366 1366 A dictionary mapping object names (as strings) to the objects.
1367 1367 """
1368 1368 for name, obj in variables.items():
1369 1369 if name in self.user_ns and self.user_ns[name] is obj:
1370 1370 del self.user_ns[name]
1371 1371 self.user_ns_hidden.pop(name, None)
1372 1372
1373 1373 #-------------------------------------------------------------------------
1374 1374 # Things related to object introspection
1375 1375 #-------------------------------------------------------------------------
1376 1376
1377 1377 def _ofind(self, oname, namespaces=None):
1378 1378 """Find an object in the available namespaces.
1379 1379
1380 1380 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1381 1381
1382 1382 Has special code to detect magic functions.
1383 1383 """
1384 1384 oname = oname.strip()
1385 1385 if not oname.startswith(ESC_MAGIC) and \
1386 1386 not oname.startswith(ESC_MAGIC2) and \
1387 1387 not all(a.isidentifier() for a in oname.split(".")):
1388 1388 return {'found': False}
1389 1389
1390 1390 if namespaces is None:
1391 1391 # Namespaces to search in:
1392 1392 # Put them in a list. The order is important so that we
1393 1393 # find things in the same order that Python finds them.
1394 1394 namespaces = [ ('Interactive', self.user_ns),
1395 1395 ('Interactive (global)', self.user_global_ns),
1396 1396 ('Python builtin', builtin_mod.__dict__),
1397 1397 ]
1398 1398
1399 1399 ismagic = False
1400 1400 isalias = False
1401 1401 found = False
1402 1402 ospace = None
1403 1403 parent = None
1404 1404 obj = None
1405 1405
1406 1406 # Look for the given name by splitting it in parts. If the head is
1407 1407 # found, then we look for all the remaining parts as members, and only
1408 1408 # declare success if we can find them all.
1409 1409 oname_parts = oname.split('.')
1410 1410 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1411 1411 for nsname,ns in namespaces:
1412 1412 try:
1413 1413 obj = ns[oname_head]
1414 1414 except KeyError:
1415 1415 continue
1416 1416 else:
1417 1417 for idx, part in enumerate(oname_rest):
1418 1418 try:
1419 1419 parent = obj
1420 1420 # The last part is looked up in a special way to avoid
1421 1421 # descriptor invocation as it may raise or have side
1422 1422 # effects.
1423 1423 if idx == len(oname_rest) - 1:
1424 1424 obj = self._getattr_property(obj, part)
1425 1425 else:
1426 1426 obj = getattr(obj, part)
1427 1427 except:
1428 1428 # Blanket except b/c some badly implemented objects
1429 1429 # allow __getattr__ to raise exceptions other than
1430 1430 # AttributeError, which then crashes IPython.
1431 1431 break
1432 1432 else:
1433 1433 # If we finish the for loop (no break), we got all members
1434 1434 found = True
1435 1435 ospace = nsname
1436 1436 break # namespace loop
1437 1437
1438 1438 # Try to see if it's magic
1439 1439 if not found:
1440 1440 obj = None
1441 1441 if oname.startswith(ESC_MAGIC2):
1442 1442 oname = oname.lstrip(ESC_MAGIC2)
1443 1443 obj = self.find_cell_magic(oname)
1444 1444 elif oname.startswith(ESC_MAGIC):
1445 1445 oname = oname.lstrip(ESC_MAGIC)
1446 1446 obj = self.find_line_magic(oname)
1447 1447 else:
1448 1448 # search without prefix, so run? will find %run?
1449 1449 obj = self.find_line_magic(oname)
1450 1450 if obj is None:
1451 1451 obj = self.find_cell_magic(oname)
1452 1452 if obj is not None:
1453 1453 found = True
1454 1454 ospace = 'IPython internal'
1455 1455 ismagic = True
1456 1456 isalias = isinstance(obj, Alias)
1457 1457
1458 1458 # Last try: special-case some literals like '', [], {}, etc:
1459 1459 if not found and oname_head in ["''",'""','[]','{}','()']:
1460 1460 obj = eval(oname_head)
1461 1461 found = True
1462 1462 ospace = 'Interactive'
1463 1463
1464 1464 return {
1465 1465 'obj':obj,
1466 1466 'found':found,
1467 1467 'parent':parent,
1468 1468 'ismagic':ismagic,
1469 1469 'isalias':isalias,
1470 1470 'namespace':ospace
1471 1471 }
1472 1472
1473 1473 @staticmethod
1474 1474 def _getattr_property(obj, attrname):
1475 1475 """Property-aware getattr to use in object finding.
1476 1476
1477 1477 If attrname represents a property, return it unevaluated (in case it has
1478 1478 side effects or raises an error.
1479 1479
1480 1480 """
1481 1481 if not isinstance(obj, type):
1482 1482 try:
1483 1483 # `getattr(type(obj), attrname)` is not guaranteed to return
1484 1484 # `obj`, but does so for property:
1485 1485 #
1486 1486 # property.__get__(self, None, cls) -> self
1487 1487 #
1488 1488 # The universal alternative is to traverse the mro manually
1489 1489 # searching for attrname in class dicts.
1490 1490 attr = getattr(type(obj), attrname)
1491 1491 except AttributeError:
1492 1492 pass
1493 1493 else:
1494 1494 # This relies on the fact that data descriptors (with both
1495 1495 # __get__ & __set__ magic methods) take precedence over
1496 1496 # instance-level attributes:
1497 1497 #
1498 1498 # class A(object):
1499 1499 # @property
1500 1500 # def foobar(self): return 123
1501 1501 # a = A()
1502 1502 # a.__dict__['foobar'] = 345
1503 1503 # a.foobar # == 123
1504 1504 #
1505 1505 # So, a property may be returned right away.
1506 1506 if isinstance(attr, property):
1507 1507 return attr
1508 1508
1509 1509 # Nothing helped, fall back.
1510 1510 return getattr(obj, attrname)
1511 1511
1512 1512 def _object_find(self, oname, namespaces=None):
1513 1513 """Find an object and return a struct with info about it."""
1514 1514 return Struct(self._ofind(oname, namespaces))
1515 1515
1516 1516 def _inspect(self, meth, oname, namespaces=None, **kw):
1517 1517 """Generic interface to the inspector system.
1518 1518
1519 1519 This function is meant to be called by pdef, pdoc & friends.
1520 1520 """
1521 1521 info = self._object_find(oname, namespaces)
1522 1522 docformat = sphinxify if self.sphinxify_docstring else None
1523 1523 if info.found:
1524 1524 pmethod = getattr(self.inspector, meth)
1525 1525 # TODO: only apply format_screen to the plain/text repr of the mime
1526 1526 # bundle.
1527 1527 formatter = format_screen if info.ismagic else docformat
1528 1528 if meth == 'pdoc':
1529 1529 pmethod(info.obj, oname, formatter)
1530 1530 elif meth == 'pinfo':
1531 1531 pmethod(info.obj, oname, formatter, info,
1532 1532 enable_html_pager=self.enable_html_pager, **kw)
1533 1533 else:
1534 1534 pmethod(info.obj, oname)
1535 1535 else:
1536 1536 print('Object `%s` not found.' % oname)
1537 1537 return 'not found' # so callers can take other action
1538 1538
1539 1539 def object_inspect(self, oname, detail_level=0):
1540 1540 """Get object info about oname"""
1541 1541 with self.builtin_trap:
1542 1542 info = self._object_find(oname)
1543 1543 if info.found:
1544 1544 return self.inspector.info(info.obj, oname, info=info,
1545 1545 detail_level=detail_level
1546 1546 )
1547 1547 else:
1548 1548 return oinspect.object_info(name=oname, found=False)
1549 1549
1550 1550 def object_inspect_text(self, oname, detail_level=0):
1551 1551 """Get object info as formatted text"""
1552 1552 return self.object_inspect_mime(oname, detail_level)['text/plain']
1553 1553
1554 1554 def object_inspect_mime(self, oname, detail_level=0):
1555 1555 """Get object info as a mimebundle of formatted representations.
1556 1556
1557 1557 A mimebundle is a dictionary, keyed by mime-type.
1558 1558 It must always have the key `'text/plain'`.
1559 1559 """
1560 1560 with self.builtin_trap:
1561 1561 info = self._object_find(oname)
1562 1562 if info.found:
1563 1563 return self.inspector._get_info(info.obj, oname, info=info,
1564 1564 detail_level=detail_level
1565 1565 )
1566 1566 else:
1567 1567 raise KeyError(oname)
1568 1568
1569 1569 #-------------------------------------------------------------------------
1570 1570 # Things related to history management
1571 1571 #-------------------------------------------------------------------------
1572 1572
1573 1573 def init_history(self):
1574 1574 """Sets up the command history, and starts regular autosaves."""
1575 1575 self.history_manager = HistoryManager(shell=self, parent=self)
1576 1576 self.configurables.append(self.history_manager)
1577 1577
1578 1578 #-------------------------------------------------------------------------
1579 1579 # Things related to exception handling and tracebacks (not debugging)
1580 1580 #-------------------------------------------------------------------------
1581 1581
1582 1582 debugger_cls = Pdb
1583 1583
1584 1584 def init_traceback_handlers(self, custom_exceptions):
1585 1585 # Syntax error handler.
1586 1586 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1587 1587
1588 1588 # The interactive one is initialized with an offset, meaning we always
1589 1589 # want to remove the topmost item in the traceback, which is our own
1590 1590 # internal code. Valid modes: ['Plain','Context','Verbose']
1591 1591 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1592 1592 color_scheme='NoColor',
1593 1593 tb_offset = 1,
1594 1594 check_cache=check_linecache_ipython,
1595 1595 debugger_cls=self.debugger_cls, parent=self)
1596 1596
1597 1597 # The instance will store a pointer to the system-wide exception hook,
1598 1598 # so that runtime code (such as magics) can access it. This is because
1599 1599 # during the read-eval loop, it may get temporarily overwritten.
1600 1600 self.sys_excepthook = sys.excepthook
1601 1601
1602 1602 # and add any custom exception handlers the user may have specified
1603 1603 self.set_custom_exc(*custom_exceptions)
1604 1604
1605 1605 # Set the exception mode
1606 1606 self.InteractiveTB.set_mode(mode=self.xmode)
1607 1607
1608 1608 def set_custom_exc(self, exc_tuple, handler):
1609 1609 """set_custom_exc(exc_tuple, handler)
1610 1610
1611 1611 Set a custom exception handler, which will be called if any of the
1612 1612 exceptions in exc_tuple occur in the mainloop (specifically, in the
1613 1613 run_code() method).
1614 1614
1615 1615 Parameters
1616 1616 ----------
1617 1617
1618 1618 exc_tuple : tuple of exception classes
1619 1619 A *tuple* of exception classes, for which to call the defined
1620 1620 handler. It is very important that you use a tuple, and NOT A
1621 1621 LIST here, because of the way Python's except statement works. If
1622 1622 you only want to trap a single exception, use a singleton tuple::
1623 1623
1624 1624 exc_tuple == (MyCustomException,)
1625 1625
1626 1626 handler : callable
1627 1627 handler must have the following signature::
1628 1628
1629 1629 def my_handler(self, etype, value, tb, tb_offset=None):
1630 1630 ...
1631 1631 return structured_traceback
1632 1632
1633 1633 Your handler must return a structured traceback (a list of strings),
1634 1634 or None.
1635 1635
1636 1636 This will be made into an instance method (via types.MethodType)
1637 1637 of IPython itself, and it will be called if any of the exceptions
1638 1638 listed in the exc_tuple are caught. If the handler is None, an
1639 1639 internal basic one is used, which just prints basic info.
1640 1640
1641 1641 To protect IPython from crashes, if your handler ever raises an
1642 1642 exception or returns an invalid result, it will be immediately
1643 1643 disabled.
1644 1644
1645 1645 WARNING: by putting in your own exception handler into IPython's main
1646 1646 execution loop, you run a very good chance of nasty crashes. This
1647 1647 facility should only be used if you really know what you are doing."""
1648 1648 if not isinstance(exc_tuple, tuple):
1649 1649 raise TypeError("The custom exceptions must be given as a tuple.")
1650 1650
1651 1651 def dummy_handler(self, etype, value, tb, tb_offset=None):
1652 1652 print('*** Simple custom exception handler ***')
1653 1653 print('Exception type :', etype)
1654 1654 print('Exception value:', value)
1655 1655 print('Traceback :', tb)
1656 1656
1657 1657 def validate_stb(stb):
1658 1658 """validate structured traceback return type
1659 1659
1660 1660 return type of CustomTB *should* be a list of strings, but allow
1661 1661 single strings or None, which are harmless.
1662 1662
1663 1663 This function will *always* return a list of strings,
1664 1664 and will raise a TypeError if stb is inappropriate.
1665 1665 """
1666 1666 msg = "CustomTB must return list of strings, not %r" % stb
1667 1667 if stb is None:
1668 1668 return []
1669 1669 elif isinstance(stb, str):
1670 1670 return [stb]
1671 1671 elif not isinstance(stb, list):
1672 1672 raise TypeError(msg)
1673 1673 # it's a list
1674 1674 for line in stb:
1675 1675 # check every element
1676 1676 if not isinstance(line, str):
1677 1677 raise TypeError(msg)
1678 1678 return stb
1679 1679
1680 1680 if handler is None:
1681 1681 wrapped = dummy_handler
1682 1682 else:
1683 1683 def wrapped(self,etype,value,tb,tb_offset=None):
1684 1684 """wrap CustomTB handler, to protect IPython from user code
1685 1685
1686 1686 This makes it harder (but not impossible) for custom exception
1687 1687 handlers to crash IPython.
1688 1688 """
1689 1689 try:
1690 1690 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1691 1691 return validate_stb(stb)
1692 1692 except:
1693 1693 # clear custom handler immediately
1694 1694 self.set_custom_exc((), None)
1695 1695 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1696 1696 # show the exception in handler first
1697 1697 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1698 1698 print(self.InteractiveTB.stb2text(stb))
1699 1699 print("The original exception:")
1700 1700 stb = self.InteractiveTB.structured_traceback(
1701 1701 (etype,value,tb), tb_offset=tb_offset
1702 1702 )
1703 1703 return stb
1704 1704
1705 1705 self.CustomTB = types.MethodType(wrapped,self)
1706 1706 self.custom_exceptions = exc_tuple
1707 1707
1708 1708 def excepthook(self, etype, value, tb):
1709 1709 """One more defense for GUI apps that call sys.excepthook.
1710 1710
1711 1711 GUI frameworks like wxPython trap exceptions and call
1712 1712 sys.excepthook themselves. I guess this is a feature that
1713 1713 enables them to keep running after exceptions that would
1714 1714 otherwise kill their mainloop. This is a bother for IPython
1715 1715 which excepts to catch all of the program exceptions with a try:
1716 1716 except: statement.
1717 1717
1718 1718 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1719 1719 any app directly invokes sys.excepthook, it will look to the user like
1720 1720 IPython crashed. In order to work around this, we can disable the
1721 1721 CrashHandler and replace it with this excepthook instead, which prints a
1722 1722 regular traceback using our InteractiveTB. In this fashion, apps which
1723 1723 call sys.excepthook will generate a regular-looking exception from
1724 1724 IPython, and the CrashHandler will only be triggered by real IPython
1725 1725 crashes.
1726 1726
1727 1727 This hook should be used sparingly, only in places which are not likely
1728 1728 to be true IPython errors.
1729 1729 """
1730 1730 self.showtraceback((etype, value, tb), tb_offset=0)
1731 1731
1732 1732 def _get_exc_info(self, exc_tuple=None):
1733 1733 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1734 1734
1735 1735 Ensures sys.last_type,value,traceback hold the exc_info we found,
1736 1736 from whichever source.
1737 1737
1738 1738 raises ValueError if none of these contain any information
1739 1739 """
1740 1740 if exc_tuple is None:
1741 1741 etype, value, tb = sys.exc_info()
1742 1742 else:
1743 1743 etype, value, tb = exc_tuple
1744 1744
1745 1745 if etype is None:
1746 1746 if hasattr(sys, 'last_type'):
1747 1747 etype, value, tb = sys.last_type, sys.last_value, \
1748 1748 sys.last_traceback
1749 1749
1750 1750 if etype is None:
1751 1751 raise ValueError("No exception to find")
1752 1752
1753 1753 # Now store the exception info in sys.last_type etc.
1754 1754 # WARNING: these variables are somewhat deprecated and not
1755 1755 # necessarily safe to use in a threaded environment, but tools
1756 1756 # like pdb depend on their existence, so let's set them. If we
1757 1757 # find problems in the field, we'll need to revisit their use.
1758 1758 sys.last_type = etype
1759 1759 sys.last_value = value
1760 1760 sys.last_traceback = tb
1761 1761
1762 1762 return etype, value, tb
1763 1763
1764 1764 def show_usage_error(self, exc):
1765 1765 """Show a short message for UsageErrors
1766 1766
1767 1767 These are special exceptions that shouldn't show a traceback.
1768 1768 """
1769 1769 print("UsageError: %s" % exc, file=sys.stderr)
1770 1770
1771 1771 def get_exception_only(self, exc_tuple=None):
1772 1772 """
1773 1773 Return as a string (ending with a newline) the exception that
1774 1774 just occurred, without any traceback.
1775 1775 """
1776 1776 etype, value, tb = self._get_exc_info(exc_tuple)
1777 1777 msg = traceback.format_exception_only(etype, value)
1778 1778 return ''.join(msg)
1779 1779
1780 1780 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1781 1781 exception_only=False, running_compiled_code=False):
1782 1782 """Display the exception that just occurred.
1783 1783
1784 1784 If nothing is known about the exception, this is the method which
1785 1785 should be used throughout the code for presenting user tracebacks,
1786 1786 rather than directly invoking the InteractiveTB object.
1787 1787
1788 1788 A specific showsyntaxerror() also exists, but this method can take
1789 1789 care of calling it if needed, so unless you are explicitly catching a
1790 1790 SyntaxError exception, don't try to analyze the stack manually and
1791 1791 simply call this method."""
1792 1792
1793 1793 try:
1794 1794 try:
1795 1795 etype, value, tb = self._get_exc_info(exc_tuple)
1796 1796 except ValueError:
1797 1797 print('No traceback available to show.', file=sys.stderr)
1798 1798 return
1799 1799
1800 1800 if issubclass(etype, SyntaxError):
1801 1801 # Though this won't be called by syntax errors in the input
1802 1802 # line, there may be SyntaxError cases with imported code.
1803 1803 self.showsyntaxerror(filename, running_compiled_code)
1804 1804 elif etype is UsageError:
1805 1805 self.show_usage_error(value)
1806 1806 else:
1807 1807 if exception_only:
1808 1808 stb = ['An exception has occurred, use %tb to see '
1809 1809 'the full traceback.\n']
1810 1810 stb.extend(self.InteractiveTB.get_exception_only(etype,
1811 1811 value))
1812 1812 else:
1813 1813 try:
1814 1814 # Exception classes can customise their traceback - we
1815 1815 # use this in IPython.parallel for exceptions occurring
1816 1816 # in the engines. This should return a list of strings.
1817 1817 stb = value._render_traceback_()
1818 1818 except Exception:
1819 1819 stb = self.InteractiveTB.structured_traceback(etype,
1820 1820 value, tb, tb_offset=tb_offset)
1821 1821
1822 1822 self._showtraceback(etype, value, stb)
1823 1823 if self.call_pdb:
1824 1824 # drop into debugger
1825 1825 self.debugger(force=True)
1826 1826 return
1827 1827
1828 1828 # Actually show the traceback
1829 1829 self._showtraceback(etype, value, stb)
1830 1830
1831 1831 except KeyboardInterrupt:
1832 1832 print('\n' + self.get_exception_only(), file=sys.stderr)
1833 1833
1834 1834 def _showtraceback(self, etype, evalue, stb):
1835 1835 """Actually show a traceback.
1836 1836
1837 1837 Subclasses may override this method to put the traceback on a different
1838 1838 place, like a side channel.
1839 1839 """
1840 1840 print(self.InteractiveTB.stb2text(stb))
1841 1841
1842 1842 def showsyntaxerror(self, filename=None, running_compiled_code=False):
1843 1843 """Display the syntax error that just occurred.
1844 1844
1845 1845 This doesn't display a stack trace because there isn't one.
1846 1846
1847 1847 If a filename is given, it is stuffed in the exception instead
1848 1848 of what was there before (because Python's parser always uses
1849 1849 "<string>" when reading from a string).
1850 1850
1851 1851 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
1852 1852 longer stack trace will be displayed.
1853 1853 """
1854 1854 etype, value, last_traceback = self._get_exc_info()
1855 1855
1856 1856 if filename and issubclass(etype, SyntaxError):
1857 1857 try:
1858 1858 value.filename = filename
1859 1859 except:
1860 1860 # Not the format we expect; leave it alone
1861 1861 pass
1862 1862
1863 1863 # If the error occured when executing compiled code, we should provide full stacktrace.
1864 1864 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
1865 1865 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
1866 1866 self._showtraceback(etype, value, stb)
1867 1867
1868 1868 # This is overridden in TerminalInteractiveShell to show a message about
1869 1869 # the %paste magic.
1870 1870 def showindentationerror(self):
1871 1871 """Called by run_cell when there's an IndentationError in code entered
1872 1872 at the prompt.
1873 1873
1874 1874 This is overridden in TerminalInteractiveShell to show a message about
1875 1875 the %paste magic."""
1876 1876 self.showsyntaxerror()
1877 1877
1878 1878 #-------------------------------------------------------------------------
1879 1879 # Things related to readline
1880 1880 #-------------------------------------------------------------------------
1881 1881
1882 1882 def init_readline(self):
1883 1883 """DEPRECATED
1884 1884
1885 1885 Moved to terminal subclass, here only to simplify the init logic."""
1886 1886 # Set a number of methods that depend on readline to be no-op
1887 1887 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1888 1888 DeprecationWarning, stacklevel=2)
1889 1889 self.set_custom_completer = no_op
1890 1890
1891 1891 @skip_doctest
1892 1892 def set_next_input(self, s, replace=False):
1893 1893 """ Sets the 'default' input string for the next command line.
1894 1894
1895 1895 Example::
1896 1896
1897 1897 In [1]: _ip.set_next_input("Hello Word")
1898 1898 In [2]: Hello Word_ # cursor is here
1899 1899 """
1900 1900 self.rl_next_input = s
1901 1901
1902 1902 def _indent_current_str(self):
1903 1903 """return the current level of indentation as a string"""
1904 1904 return self.input_splitter.indent_spaces * ' '
1905 1905
1906 1906 #-------------------------------------------------------------------------
1907 1907 # Things related to text completion
1908 1908 #-------------------------------------------------------------------------
1909 1909
1910 1910 def init_completer(self):
1911 1911 """Initialize the completion machinery.
1912 1912
1913 1913 This creates completion machinery that can be used by client code,
1914 1914 either interactively in-process (typically triggered by the readline
1915 1915 library), programmatically (such as in test suites) or out-of-process
1916 1916 (typically over the network by remote frontends).
1917 1917 """
1918 1918 from IPython.core.completer import IPCompleter
1919 1919 from IPython.core.completerlib import (module_completer,
1920 1920 magic_run_completer, cd_completer, reset_completer)
1921 1921
1922 1922 self.Completer = IPCompleter(shell=self,
1923 1923 namespace=self.user_ns,
1924 1924 global_namespace=self.user_global_ns,
1925 1925 parent=self,
1926 1926 )
1927 1927 self.configurables.append(self.Completer)
1928 1928
1929 1929 # Add custom completers to the basic ones built into IPCompleter
1930 1930 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1931 1931 self.strdispatchers['complete_command'] = sdisp
1932 1932 self.Completer.custom_completers = sdisp
1933 1933
1934 1934 self.set_hook('complete_command', module_completer, str_key = 'import')
1935 1935 self.set_hook('complete_command', module_completer, str_key = 'from')
1936 1936 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1937 1937 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1938 1938 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1939 1939 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1940 1940
1941 1941
1942 1942 def complete(self, text, line=None, cursor_pos=None):
1943 1943 """Return the completed text and a list of completions.
1944 1944
1945 1945 Parameters
1946 1946 ----------
1947 1947
1948 1948 text : string
1949 1949 A string of text to be completed on. It can be given as empty and
1950 1950 instead a line/position pair are given. In this case, the
1951 1951 completer itself will split the line like readline does.
1952 1952
1953 1953 line : string, optional
1954 1954 The complete line that text is part of.
1955 1955
1956 1956 cursor_pos : int, optional
1957 1957 The position of the cursor on the input line.
1958 1958
1959 1959 Returns
1960 1960 -------
1961 1961 text : string
1962 1962 The actual text that was completed.
1963 1963
1964 1964 matches : list
1965 1965 A sorted list with all possible completions.
1966 1966
1967 1967 The optional arguments allow the completion to take more context into
1968 1968 account, and are part of the low-level completion API.
1969 1969
1970 1970 This is a wrapper around the completion mechanism, similar to what
1971 1971 readline does at the command line when the TAB key is hit. By
1972 1972 exposing it as a method, it can be used by other non-readline
1973 1973 environments (such as GUIs) for text completion.
1974 1974
1975 1975 Simple usage example:
1976 1976
1977 1977 In [1]: x = 'hello'
1978 1978
1979 1979 In [2]: _ip.complete('x.l')
1980 1980 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1981 1981 """
1982 1982
1983 1983 # Inject names into __builtin__ so we can complete on the added names.
1984 1984 with self.builtin_trap:
1985 1985 return self.Completer.complete(text, line, cursor_pos)
1986 1986
1987 1987 def set_custom_completer(self, completer, pos=0):
1988 1988 """Adds a new custom completer function.
1989 1989
1990 1990 The position argument (defaults to 0) is the index in the completers
1991 1991 list where you want the completer to be inserted."""
1992 1992
1993 1993 newcomp = types.MethodType(completer,self.Completer)
1994 1994 self.Completer.matchers.insert(pos,newcomp)
1995 1995
1996 1996 def set_completer_frame(self, frame=None):
1997 1997 """Set the frame of the completer."""
1998 1998 if frame:
1999 1999 self.Completer.namespace = frame.f_locals
2000 2000 self.Completer.global_namespace = frame.f_globals
2001 2001 else:
2002 2002 self.Completer.namespace = self.user_ns
2003 2003 self.Completer.global_namespace = self.user_global_ns
2004 2004
2005 2005 #-------------------------------------------------------------------------
2006 2006 # Things related to magics
2007 2007 #-------------------------------------------------------------------------
2008 2008
2009 2009 def init_magics(self):
2010 2010 from IPython.core import magics as m
2011 2011 self.magics_manager = magic.MagicsManager(shell=self,
2012 2012 parent=self,
2013 2013 user_magics=m.UserMagics(self))
2014 2014 self.configurables.append(self.magics_manager)
2015 2015
2016 2016 # Expose as public API from the magics manager
2017 2017 self.register_magics = self.magics_manager.register
2018 2018
2019 2019 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2020 2020 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2021 2021 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2022 2022 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2023 2023 )
2024 2024
2025 2025 # Register Magic Aliases
2026 2026 mman = self.magics_manager
2027 2027 # FIXME: magic aliases should be defined by the Magics classes
2028 2028 # or in MagicsManager, not here
2029 2029 mman.register_alias('ed', 'edit')
2030 2030 mman.register_alias('hist', 'history')
2031 2031 mman.register_alias('rep', 'recall')
2032 2032 mman.register_alias('SVG', 'svg', 'cell')
2033 2033 mman.register_alias('HTML', 'html', 'cell')
2034 2034 mman.register_alias('file', 'writefile', 'cell')
2035 2035
2036 2036 # FIXME: Move the color initialization to the DisplayHook, which
2037 2037 # should be split into a prompt manager and displayhook. We probably
2038 2038 # even need a centralize colors management object.
2039 self.magic('colors %s' % self.colors)
2039 self.run_line_magic('colors', self.colors)
2040 2040
2041 2041 # Defined here so that it's included in the documentation
2042 2042 @functools.wraps(magic.MagicsManager.register_function)
2043 2043 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2044 2044 self.magics_manager.register_function(func,
2045 2045 magic_kind=magic_kind, magic_name=magic_name)
2046 2046
2047 def run_line_magic(self, magic_name, line, back_compat=False):
2047 def run_line_magic(self, magic_name, line, _stack_depth=1):
2048 2048 """Execute the given line magic.
2049 2049
2050 2050 Parameters
2051 2051 ----------
2052 2052 magic_name : str
2053 2053 Name of the desired magic function, without '%' prefix.
2054 2054
2055 2055 line : str
2056 2056 The rest of the input line as a single string.
2057 2057
2058 back_compat : bool
2059 If run_line_magic() is called from magic() then it should be 'True'.
2058 _stack_depth : int
2059 If run_line_magic() is called from magic() then _stack_depth=2.
2060 2060 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2061 2061 """
2062 2062 fn = self.find_line_magic(magic_name)
2063 2063 if fn is None:
2064 2064 cm = self.find_cell_magic(magic_name)
2065 2065 etpl = "Line magic function `%%%s` not found%s."
2066 2066 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2067 2067 'did you mean that instead?)' % magic_name )
2068 2068 error(etpl % (magic_name, extra))
2069 2069 else:
2070 2070 # Note: this is the distance in the stack to the user's frame.
2071 2071 # This will need to be updated if the internal calling logic gets
2072 2072 # refactored, or else we'll be expanding the wrong variables.
2073
2073 2074 # Determine stack_depth depending on where run_line_magic() has been called
2074 if back_compat:
2075 # run_line_magic() called directly using 'get_ipython().magic()'
2076 stack_depth = 2
2077 else:
2078 # run_line_magic() called directly using 'get_ipython().run_line_magic()'
2079 stack_depth = 1
2075 stack_depth = _stack_depth
2080 2076 magic_arg_s = self.var_expand(line, stack_depth)
2081 2077 # Put magic args in a list so we can call with f(*a) syntax
2082 2078 args = [magic_arg_s]
2083 2079 kwargs = {}
2084 2080 # Grab local namespace if we need it:
2085 2081 if getattr(fn, "needs_local_scope", False):
2086 2082 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2087 2083 with self.builtin_trap:
2088 2084 result = fn(*args,**kwargs)
2089 2085 return result
2090 2086
2091 2087 def run_cell_magic(self, magic_name, line, cell):
2092 2088 """Execute the given cell magic.
2093 2089
2094 2090 Parameters
2095 2091 ----------
2096 2092 magic_name : str
2097 2093 Name of the desired magic function, without '%' prefix.
2098 2094
2099 2095 line : str
2100 2096 The rest of the first input line as a single string.
2101 2097
2102 2098 cell : str
2103 2099 The body of the cell as a (possibly multiline) string.
2104 2100 """
2105 2101 fn = self.find_cell_magic(magic_name)
2106 2102 if fn is None:
2107 2103 lm = self.find_line_magic(magic_name)
2108 2104 etpl = "Cell magic `%%{0}` not found{1}."
2109 2105 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2110 2106 'did you mean that instead?)'.format(magic_name))
2111 2107 error(etpl.format(magic_name, extra))
2112 2108 elif cell == '':
2113 2109 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2114 2110 if self.find_line_magic(magic_name) is not None:
2115 2111 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2116 2112 raise UsageError(message)
2117 2113 else:
2118 2114 # Note: this is the distance in the stack to the user's frame.
2119 2115 # This will need to be updated if the internal calling logic gets
2120 2116 # refactored, or else we'll be expanding the wrong variables.
2121 2117 stack_depth = 2
2122 2118 magic_arg_s = self.var_expand(line, stack_depth)
2123 2119 with self.builtin_trap:
2124 2120 result = fn(magic_arg_s, cell)
2125 2121 return result
2126 2122
2127 2123 def find_line_magic(self, magic_name):
2128 2124 """Find and return a line magic by name.
2129 2125
2130 2126 Returns None if the magic isn't found."""
2131 2127 return self.magics_manager.magics['line'].get(magic_name)
2132 2128
2133 2129 def find_cell_magic(self, magic_name):
2134 2130 """Find and return a cell magic by name.
2135 2131
2136 2132 Returns None if the magic isn't found."""
2137 2133 return self.magics_manager.magics['cell'].get(magic_name)
2138 2134
2139 2135 def find_magic(self, magic_name, magic_kind='line'):
2140 2136 """Find and return a magic of the given type by name.
2141 2137
2142 2138 Returns None if the magic isn't found."""
2143 2139 return self.magics_manager.magics[magic_kind].get(magic_name)
2144 2140
2145 2141 def magic(self, arg_s):
2146 2142 """DEPRECATED. Use run_line_magic() instead.
2147 2143
2148 2144 Call a magic function by name.
2149 2145
2150 2146 Input: a string containing the name of the magic function to call and
2151 2147 any additional arguments to be passed to the magic.
2152 2148
2153 2149 magic('name -opt foo bar') is equivalent to typing at the ipython
2154 2150 prompt:
2155 2151
2156 2152 In[1]: %name -opt foo bar
2157 2153
2158 2154 To call a magic without arguments, simply use magic('name').
2159 2155
2160 2156 This provides a proper Python function to call IPython's magics in any
2161 2157 valid Python code you can type at the interpreter, including loops and
2162 2158 compound statements.
2163 2159 """
2164 2160 # TODO: should we issue a loud deprecation warning here?
2165 2161 magic_name, _, magic_arg_s = arg_s.partition(' ')
2166 2162 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2167 return self.run_line_magic(magic_name, magic_arg_s, back_compat=True)
2163 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2168 2164
2169 2165 #-------------------------------------------------------------------------
2170 2166 # Things related to macros
2171 2167 #-------------------------------------------------------------------------
2172 2168
2173 2169 def define_macro(self, name, themacro):
2174 2170 """Define a new macro
2175 2171
2176 2172 Parameters
2177 2173 ----------
2178 2174 name : str
2179 2175 The name of the macro.
2180 2176 themacro : str or Macro
2181 2177 The action to do upon invoking the macro. If a string, a new
2182 2178 Macro object is created by passing the string to it.
2183 2179 """
2184 2180
2185 2181 from IPython.core import macro
2186 2182
2187 2183 if isinstance(themacro, str):
2188 2184 themacro = macro.Macro(themacro)
2189 2185 if not isinstance(themacro, macro.Macro):
2190 2186 raise ValueError('A macro must be a string or a Macro instance.')
2191 2187 self.user_ns[name] = themacro
2192 2188
2193 2189 #-------------------------------------------------------------------------
2194 2190 # Things related to the running of system commands
2195 2191 #-------------------------------------------------------------------------
2196 2192
2197 2193 def system_piped(self, cmd):
2198 2194 """Call the given cmd in a subprocess, piping stdout/err
2199 2195
2200 2196 Parameters
2201 2197 ----------
2202 2198 cmd : str
2203 2199 Command to execute (can not end in '&', as background processes are
2204 2200 not supported. Should not be a command that expects input
2205 2201 other than simple text.
2206 2202 """
2207 2203 if cmd.rstrip().endswith('&'):
2208 2204 # this is *far* from a rigorous test
2209 2205 # We do not support backgrounding processes because we either use
2210 2206 # pexpect or pipes to read from. Users can always just call
2211 2207 # os.system() or use ip.system=ip.system_raw
2212 2208 # if they really want a background process.
2213 2209 raise OSError("Background processes not supported.")
2214 2210
2215 2211 # we explicitly do NOT return the subprocess status code, because
2216 2212 # a non-None value would trigger :func:`sys.displayhook` calls.
2217 2213 # Instead, we store the exit_code in user_ns.
2218 2214 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2219 2215
2220 2216 def system_raw(self, cmd):
2221 2217 """Call the given cmd in a subprocess using os.system on Windows or
2222 2218 subprocess.call using the system shell on other platforms.
2223 2219
2224 2220 Parameters
2225 2221 ----------
2226 2222 cmd : str
2227 2223 Command to execute.
2228 2224 """
2229 2225 cmd = self.var_expand(cmd, depth=1)
2230 2226 # protect os.system from UNC paths on Windows, which it can't handle:
2231 2227 if sys.platform == 'win32':
2232 2228 from IPython.utils._process_win32 import AvoidUNCPath
2233 2229 with AvoidUNCPath() as path:
2234 2230 if path is not None:
2235 2231 cmd = '"pushd %s &&"%s' % (path, cmd)
2236 2232 try:
2237 2233 ec = os.system(cmd)
2238 2234 except KeyboardInterrupt:
2239 2235 print('\n' + self.get_exception_only(), file=sys.stderr)
2240 2236 ec = -2
2241 2237 else:
2242 2238 # For posix the result of the subprocess.call() below is an exit
2243 2239 # code, which by convention is zero for success, positive for
2244 2240 # program failure. Exit codes above 128 are reserved for signals,
2245 2241 # and the formula for converting a signal to an exit code is usually
2246 2242 # signal_number+128. To more easily differentiate between exit
2247 2243 # codes and signals, ipython uses negative numbers. For instance
2248 2244 # since control-c is signal 2 but exit code 130, ipython's
2249 2245 # _exit_code variable will read -2. Note that some shells like
2250 2246 # csh and fish don't follow sh/bash conventions for exit codes.
2251 2247 executable = os.environ.get('SHELL', None)
2252 2248 try:
2253 2249 # Use env shell instead of default /bin/sh
2254 2250 ec = subprocess.call(cmd, shell=True, executable=executable)
2255 2251 except KeyboardInterrupt:
2256 2252 # intercept control-C; a long traceback is not useful here
2257 2253 print('\n' + self.get_exception_only(), file=sys.stderr)
2258 2254 ec = 130
2259 2255 if ec > 128:
2260 2256 ec = -(ec - 128)
2261 2257
2262 2258 # We explicitly do NOT return the subprocess status code, because
2263 2259 # a non-None value would trigger :func:`sys.displayhook` calls.
2264 2260 # Instead, we store the exit_code in user_ns. Note the semantics
2265 2261 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2266 2262 # but raising SystemExit(_exit_code) will give status 254!
2267 2263 self.user_ns['_exit_code'] = ec
2268 2264
2269 2265 # use piped system by default, because it is better behaved
2270 2266 system = system_piped
2271 2267
2272 2268 def getoutput(self, cmd, split=True, depth=0):
2273 2269 """Get output (possibly including stderr) from a subprocess.
2274 2270
2275 2271 Parameters
2276 2272 ----------
2277 2273 cmd : str
2278 2274 Command to execute (can not end in '&', as background processes are
2279 2275 not supported.
2280 2276 split : bool, optional
2281 2277 If True, split the output into an IPython SList. Otherwise, an
2282 2278 IPython LSString is returned. These are objects similar to normal
2283 2279 lists and strings, with a few convenience attributes for easier
2284 2280 manipulation of line-based output. You can use '?' on them for
2285 2281 details.
2286 2282 depth : int, optional
2287 2283 How many frames above the caller are the local variables which should
2288 2284 be expanded in the command string? The default (0) assumes that the
2289 2285 expansion variables are in the stack frame calling this function.
2290 2286 """
2291 2287 if cmd.rstrip().endswith('&'):
2292 2288 # this is *far* from a rigorous test
2293 2289 raise OSError("Background processes not supported.")
2294 2290 out = getoutput(self.var_expand(cmd, depth=depth+1))
2295 2291 if split:
2296 2292 out = SList(out.splitlines())
2297 2293 else:
2298 2294 out = LSString(out)
2299 2295 return out
2300 2296
2301 2297 #-------------------------------------------------------------------------
2302 2298 # Things related to aliases
2303 2299 #-------------------------------------------------------------------------
2304 2300
2305 2301 def init_alias(self):
2306 2302 self.alias_manager = AliasManager(shell=self, parent=self)
2307 2303 self.configurables.append(self.alias_manager)
2308 2304
2309 2305 #-------------------------------------------------------------------------
2310 2306 # Things related to extensions
2311 2307 #-------------------------------------------------------------------------
2312 2308
2313 2309 def init_extension_manager(self):
2314 2310 self.extension_manager = ExtensionManager(shell=self, parent=self)
2315 2311 self.configurables.append(self.extension_manager)
2316 2312
2317 2313 #-------------------------------------------------------------------------
2318 2314 # Things related to payloads
2319 2315 #-------------------------------------------------------------------------
2320 2316
2321 2317 def init_payload(self):
2322 2318 self.payload_manager = PayloadManager(parent=self)
2323 2319 self.configurables.append(self.payload_manager)
2324 2320
2325 2321 #-------------------------------------------------------------------------
2326 2322 # Things related to the prefilter
2327 2323 #-------------------------------------------------------------------------
2328 2324
2329 2325 def init_prefilter(self):
2330 2326 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2331 2327 self.configurables.append(self.prefilter_manager)
2332 2328 # Ultimately this will be refactored in the new interpreter code, but
2333 2329 # for now, we should expose the main prefilter method (there's legacy
2334 2330 # code out there that may rely on this).
2335 2331 self.prefilter = self.prefilter_manager.prefilter_lines
2336 2332
2337 2333 def auto_rewrite_input(self, cmd):
2338 2334 """Print to the screen the rewritten form of the user's command.
2339 2335
2340 2336 This shows visual feedback by rewriting input lines that cause
2341 2337 automatic calling to kick in, like::
2342 2338
2343 2339 /f x
2344 2340
2345 2341 into::
2346 2342
2347 2343 ------> f(x)
2348 2344
2349 2345 after the user's input prompt. This helps the user understand that the
2350 2346 input line was transformed automatically by IPython.
2351 2347 """
2352 2348 if not self.show_rewritten_input:
2353 2349 return
2354 2350
2355 2351 # This is overridden in TerminalInteractiveShell to use fancy prompts
2356 2352 print("------> " + cmd)
2357 2353
2358 2354 #-------------------------------------------------------------------------
2359 2355 # Things related to extracting values/expressions from kernel and user_ns
2360 2356 #-------------------------------------------------------------------------
2361 2357
2362 2358 def _user_obj_error(self):
2363 2359 """return simple exception dict
2364 2360
2365 2361 for use in user_expressions
2366 2362 """
2367 2363
2368 2364 etype, evalue, tb = self._get_exc_info()
2369 2365 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2370 2366
2371 2367 exc_info = {
2372 2368 u'status' : 'error',
2373 2369 u'traceback' : stb,
2374 2370 u'ename' : etype.__name__,
2375 2371 u'evalue' : py3compat.safe_unicode(evalue),
2376 2372 }
2377 2373
2378 2374 return exc_info
2379 2375
2380 2376 def _format_user_obj(self, obj):
2381 2377 """format a user object to display dict
2382 2378
2383 2379 for use in user_expressions
2384 2380 """
2385 2381
2386 2382 data, md = self.display_formatter.format(obj)
2387 2383 value = {
2388 2384 'status' : 'ok',
2389 2385 'data' : data,
2390 2386 'metadata' : md,
2391 2387 }
2392 2388 return value
2393 2389
2394 2390 def user_expressions(self, expressions):
2395 2391 """Evaluate a dict of expressions in the user's namespace.
2396 2392
2397 2393 Parameters
2398 2394 ----------
2399 2395 expressions : dict
2400 2396 A dict with string keys and string values. The expression values
2401 2397 should be valid Python expressions, each of which will be evaluated
2402 2398 in the user namespace.
2403 2399
2404 2400 Returns
2405 2401 -------
2406 2402 A dict, keyed like the input expressions dict, with the rich mime-typed
2407 2403 display_data of each value.
2408 2404 """
2409 2405 out = {}
2410 2406 user_ns = self.user_ns
2411 2407 global_ns = self.user_global_ns
2412 2408
2413 2409 for key, expr in expressions.items():
2414 2410 try:
2415 2411 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2416 2412 except:
2417 2413 value = self._user_obj_error()
2418 2414 out[key] = value
2419 2415 return out
2420 2416
2421 2417 #-------------------------------------------------------------------------
2422 2418 # Things related to the running of code
2423 2419 #-------------------------------------------------------------------------
2424 2420
2425 2421 def ex(self, cmd):
2426 2422 """Execute a normal python statement in user namespace."""
2427 2423 with self.builtin_trap:
2428 2424 exec(cmd, self.user_global_ns, self.user_ns)
2429 2425
2430 2426 def ev(self, expr):
2431 2427 """Evaluate python expression expr in user namespace.
2432 2428
2433 2429 Returns the result of evaluation
2434 2430 """
2435 2431 with self.builtin_trap:
2436 2432 return eval(expr, self.user_global_ns, self.user_ns)
2437 2433
2438 2434 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2439 2435 """A safe version of the builtin execfile().
2440 2436
2441 2437 This version will never throw an exception, but instead print
2442 2438 helpful error messages to the screen. This only works on pure
2443 2439 Python files with the .py extension.
2444 2440
2445 2441 Parameters
2446 2442 ----------
2447 2443 fname : string
2448 2444 The name of the file to be executed.
2449 2445 where : tuple
2450 2446 One or two namespaces, passed to execfile() as (globals,locals).
2451 2447 If only one is given, it is passed as both.
2452 2448 exit_ignore : bool (False)
2453 2449 If True, then silence SystemExit for non-zero status (it is always
2454 2450 silenced for zero status, as it is so common).
2455 2451 raise_exceptions : bool (False)
2456 2452 If True raise exceptions everywhere. Meant for testing.
2457 2453 shell_futures : bool (False)
2458 2454 If True, the code will share future statements with the interactive
2459 2455 shell. It will both be affected by previous __future__ imports, and
2460 2456 any __future__ imports in the code will affect the shell. If False,
2461 2457 __future__ imports are not shared in either direction.
2462 2458
2463 2459 """
2464 2460 fname = os.path.abspath(os.path.expanduser(fname))
2465 2461
2466 2462 # Make sure we can open the file
2467 2463 try:
2468 2464 with open(fname):
2469 2465 pass
2470 2466 except:
2471 2467 warn('Could not open file <%s> for safe execution.' % fname)
2472 2468 return
2473 2469
2474 2470 # Find things also in current directory. This is needed to mimic the
2475 2471 # behavior of running a script from the system command line, where
2476 2472 # Python inserts the script's directory into sys.path
2477 2473 dname = os.path.dirname(fname)
2478 2474
2479 2475 with prepended_to_syspath(dname), self.builtin_trap:
2480 2476 try:
2481 2477 glob, loc = (where + (None, ))[:2]
2482 2478 py3compat.execfile(
2483 2479 fname, glob, loc,
2484 2480 self.compile if shell_futures else None)
2485 2481 except SystemExit as status:
2486 2482 # If the call was made with 0 or None exit status (sys.exit(0)
2487 2483 # or sys.exit() ), don't bother showing a traceback, as both of
2488 2484 # these are considered normal by the OS:
2489 2485 # > python -c'import sys;sys.exit(0)'; echo $?
2490 2486 # 0
2491 2487 # > python -c'import sys;sys.exit()'; echo $?
2492 2488 # 0
2493 2489 # For other exit status, we show the exception unless
2494 2490 # explicitly silenced, but only in short form.
2495 2491 if status.code:
2496 2492 if raise_exceptions:
2497 2493 raise
2498 2494 if not exit_ignore:
2499 2495 self.showtraceback(exception_only=True)
2500 2496 except:
2501 2497 if raise_exceptions:
2502 2498 raise
2503 2499 # tb offset is 2 because we wrap execfile
2504 2500 self.showtraceback(tb_offset=2)
2505 2501
2506 2502 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2507 2503 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2508 2504
2509 2505 Parameters
2510 2506 ----------
2511 2507 fname : str
2512 2508 The name of the file to execute. The filename must have a
2513 2509 .ipy or .ipynb extension.
2514 2510 shell_futures : bool (False)
2515 2511 If True, the code will share future statements with the interactive
2516 2512 shell. It will both be affected by previous __future__ imports, and
2517 2513 any __future__ imports in the code will affect the shell. If False,
2518 2514 __future__ imports are not shared in either direction.
2519 2515 raise_exceptions : bool (False)
2520 2516 If True raise exceptions everywhere. Meant for testing.
2521 2517 """
2522 2518 fname = os.path.abspath(os.path.expanduser(fname))
2523 2519
2524 2520 # Make sure we can open the file
2525 2521 try:
2526 2522 with open(fname):
2527 2523 pass
2528 2524 except:
2529 2525 warn('Could not open file <%s> for safe execution.' % fname)
2530 2526 return
2531 2527
2532 2528 # Find things also in current directory. This is needed to mimic the
2533 2529 # behavior of running a script from the system command line, where
2534 2530 # Python inserts the script's directory into sys.path
2535 2531 dname = os.path.dirname(fname)
2536 2532
2537 2533 def get_cells():
2538 2534 """generator for sequence of code blocks to run"""
2539 2535 if fname.endswith('.ipynb'):
2540 2536 from nbformat import read
2541 2537 nb = read(fname, as_version=4)
2542 2538 if not nb.cells:
2543 2539 return
2544 2540 for cell in nb.cells:
2545 2541 if cell.cell_type == 'code':
2546 2542 yield cell.source
2547 2543 else:
2548 2544 with open(fname) as f:
2549 2545 yield f.read()
2550 2546
2551 2547 with prepended_to_syspath(dname):
2552 2548 try:
2553 2549 for cell in get_cells():
2554 2550 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2555 2551 if raise_exceptions:
2556 2552 result.raise_error()
2557 2553 elif not result.success:
2558 2554 break
2559 2555 except:
2560 2556 if raise_exceptions:
2561 2557 raise
2562 2558 self.showtraceback()
2563 2559 warn('Unknown failure executing file: <%s>' % fname)
2564 2560
2565 2561 def safe_run_module(self, mod_name, where):
2566 2562 """A safe version of runpy.run_module().
2567 2563
2568 2564 This version will never throw an exception, but instead print
2569 2565 helpful error messages to the screen.
2570 2566
2571 2567 `SystemExit` exceptions with status code 0 or None are ignored.
2572 2568
2573 2569 Parameters
2574 2570 ----------
2575 2571 mod_name : string
2576 2572 The name of the module to be executed.
2577 2573 where : dict
2578 2574 The globals namespace.
2579 2575 """
2580 2576 try:
2581 2577 try:
2582 2578 where.update(
2583 2579 runpy.run_module(str(mod_name), run_name="__main__",
2584 2580 alter_sys=True)
2585 2581 )
2586 2582 except SystemExit as status:
2587 2583 if status.code:
2588 2584 raise
2589 2585 except:
2590 2586 self.showtraceback()
2591 2587 warn('Unknown failure executing module: <%s>' % mod_name)
2592 2588
2593 2589 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2594 2590 """Run a complete IPython cell.
2595 2591
2596 2592 Parameters
2597 2593 ----------
2598 2594 raw_cell : str
2599 2595 The code (including IPython code such as %magic functions) to run.
2600 2596 store_history : bool
2601 2597 If True, the raw and translated cell will be stored in IPython's
2602 2598 history. For user code calling back into IPython's machinery, this
2603 2599 should be set to False.
2604 2600 silent : bool
2605 2601 If True, avoid side-effects, such as implicit displayhooks and
2606 2602 and logging. silent=True forces store_history=False.
2607 2603 shell_futures : bool
2608 2604 If True, the code will share future statements with the interactive
2609 2605 shell. It will both be affected by previous __future__ imports, and
2610 2606 any __future__ imports in the code will affect the shell. If False,
2611 2607 __future__ imports are not shared in either direction.
2612 2608
2613 2609 Returns
2614 2610 -------
2615 2611 result : :class:`ExecutionResult`
2616 2612 """
2617 2613 result = ExecutionResult()
2618 2614
2619 2615 if (not raw_cell) or raw_cell.isspace():
2620 2616 self.last_execution_succeeded = True
2621 2617 return result
2622 2618
2623 2619 if silent:
2624 2620 store_history = False
2625 2621
2626 2622 if store_history:
2627 2623 result.execution_count = self.execution_count
2628 2624
2629 2625 def error_before_exec(value):
2630 2626 result.error_before_exec = value
2631 2627 self.last_execution_succeeded = False
2632 2628 return result
2633 2629
2634 2630 self.events.trigger('pre_execute')
2635 2631 if not silent:
2636 2632 self.events.trigger('pre_run_cell')
2637 2633
2638 2634 # If any of our input transformation (input_transformer_manager or
2639 2635 # prefilter_manager) raises an exception, we store it in this variable
2640 2636 # so that we can display the error after logging the input and storing
2641 2637 # it in the history.
2642 2638 preprocessing_exc_tuple = None
2643 2639 try:
2644 2640 # Static input transformations
2645 2641 cell = self.input_transformer_manager.transform_cell(raw_cell)
2646 2642 except SyntaxError:
2647 2643 preprocessing_exc_tuple = sys.exc_info()
2648 2644 cell = raw_cell # cell has to exist so it can be stored/logged
2649 2645 else:
2650 2646 if len(cell.splitlines()) == 1:
2651 2647 # Dynamic transformations - only applied for single line commands
2652 2648 with self.builtin_trap:
2653 2649 try:
2654 2650 # use prefilter_lines to handle trailing newlines
2655 2651 # restore trailing newline for ast.parse
2656 2652 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2657 2653 except Exception:
2658 2654 # don't allow prefilter errors to crash IPython
2659 2655 preprocessing_exc_tuple = sys.exc_info()
2660 2656
2661 2657 # Store raw and processed history
2662 2658 if store_history:
2663 2659 self.history_manager.store_inputs(self.execution_count,
2664 2660 cell, raw_cell)
2665 2661 if not silent:
2666 2662 self.logger.log(cell, raw_cell)
2667 2663
2668 2664 # Display the exception if input processing failed.
2669 2665 if preprocessing_exc_tuple is not None:
2670 2666 self.showtraceback(preprocessing_exc_tuple)
2671 2667 if store_history:
2672 2668 self.execution_count += 1
2673 2669 return error_before_exec(preprocessing_exc_tuple[2])
2674 2670
2675 2671 # Our own compiler remembers the __future__ environment. If we want to
2676 2672 # run code with a separate __future__ environment, use the default
2677 2673 # compiler
2678 2674 compiler = self.compile if shell_futures else CachingCompiler()
2679 2675
2680 2676 with self.builtin_trap:
2681 2677 cell_name = self.compile.cache(cell, self.execution_count)
2682 2678
2683 2679 with self.display_trap:
2684 2680 # Compile to bytecode
2685 2681 try:
2686 2682 code_ast = compiler.ast_parse(cell, filename=cell_name)
2687 2683 except self.custom_exceptions as e:
2688 2684 etype, value, tb = sys.exc_info()
2689 2685 self.CustomTB(etype, value, tb)
2690 2686 return error_before_exec(e)
2691 2687 except IndentationError as e:
2692 2688 self.showindentationerror()
2693 2689 if store_history:
2694 2690 self.execution_count += 1
2695 2691 return error_before_exec(e)
2696 2692 except (OverflowError, SyntaxError, ValueError, TypeError,
2697 2693 MemoryError) as e:
2698 2694 self.showsyntaxerror()
2699 2695 if store_history:
2700 2696 self.execution_count += 1
2701 2697 return error_before_exec(e)
2702 2698
2703 2699 # Apply AST transformations
2704 2700 try:
2705 2701 code_ast = self.transform_ast(code_ast)
2706 2702 except InputRejected as e:
2707 2703 self.showtraceback()
2708 2704 if store_history:
2709 2705 self.execution_count += 1
2710 2706 return error_before_exec(e)
2711 2707
2712 2708 # Give the displayhook a reference to our ExecutionResult so it
2713 2709 # can fill in the output value.
2714 2710 self.displayhook.exec_result = result
2715 2711
2716 2712 # Execute the user code
2717 2713 interactivity = "none" if silent else self.ast_node_interactivity
2718 2714 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2719 2715 interactivity=interactivity, compiler=compiler, result=result)
2720 2716
2721 2717 self.last_execution_succeeded = not has_raised
2722 2718
2723 2719 # Reset this so later displayed values do not modify the
2724 2720 # ExecutionResult
2725 2721 self.displayhook.exec_result = None
2726 2722
2727 2723 self.events.trigger('post_execute')
2728 2724 if not silent:
2729 2725 self.events.trigger('post_run_cell')
2730 2726
2731 2727 if store_history:
2732 2728 # Write output to the database. Does nothing unless
2733 2729 # history output logging is enabled.
2734 2730 self.history_manager.store_output(self.execution_count)
2735 2731 # Each cell is a *single* input, regardless of how many lines it has
2736 2732 self.execution_count += 1
2737 2733
2738 2734 return result
2739 2735
2740 2736 def transform_ast(self, node):
2741 2737 """Apply the AST transformations from self.ast_transformers
2742 2738
2743 2739 Parameters
2744 2740 ----------
2745 2741 node : ast.Node
2746 2742 The root node to be transformed. Typically called with the ast.Module
2747 2743 produced by parsing user input.
2748 2744
2749 2745 Returns
2750 2746 -------
2751 2747 An ast.Node corresponding to the node it was called with. Note that it
2752 2748 may also modify the passed object, so don't rely on references to the
2753 2749 original AST.
2754 2750 """
2755 2751 for transformer in self.ast_transformers:
2756 2752 try:
2757 2753 node = transformer.visit(node)
2758 2754 except InputRejected:
2759 2755 # User-supplied AST transformers can reject an input by raising
2760 2756 # an InputRejected. Short-circuit in this case so that we
2761 2757 # don't unregister the transform.
2762 2758 raise
2763 2759 except Exception:
2764 2760 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2765 2761 self.ast_transformers.remove(transformer)
2766 2762
2767 2763 if self.ast_transformers:
2768 2764 ast.fix_missing_locations(node)
2769 2765 return node
2770 2766
2771 2767
2772 2768 def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
2773 2769 compiler=compile, result=None):
2774 2770 """Run a sequence of AST nodes. The execution mode depends on the
2775 2771 interactivity parameter.
2776 2772
2777 2773 Parameters
2778 2774 ----------
2779 2775 nodelist : list
2780 2776 A sequence of AST nodes to run.
2781 2777 cell_name : str
2782 2778 Will be passed to the compiler as the filename of the cell. Typically
2783 2779 the value returned by ip.compile.cache(cell).
2784 2780 interactivity : str
2785 2781 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
2786 2782 specifying which nodes should be run interactively (displaying output
2787 2783 from expressions). 'last_expr' will run the last node interactively
2788 2784 only if it is an expression (i.e. expressions in loops or other blocks
2789 2785 are not displayed) 'last_expr_or_assign' will run the last expression
2790 2786 or the last assignment. Other values for this parameter will raise a
2791 2787 ValueError.
2792 2788 compiler : callable
2793 2789 A function with the same interface as the built-in compile(), to turn
2794 2790 the AST nodes into code objects. Default is the built-in compile().
2795 2791 result : ExecutionResult, optional
2796 2792 An object to store exceptions that occur during execution.
2797 2793
2798 2794 Returns
2799 2795 -------
2800 2796 True if an exception occurred while running code, False if it finished
2801 2797 running.
2802 2798 """
2803 2799 if not nodelist:
2804 2800 return
2805 2801
2806 2802 if interactivity == 'last_expr_or_assign':
2807 2803 if isinstance(nodelist[-1], _assign_nodes):
2808 2804 asg = nodelist[-1]
2809 2805 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
2810 2806 target = asg.targets[0]
2811 2807 elif isinstance(asg, _single_targets_nodes):
2812 2808 target = asg.target
2813 2809 else:
2814 2810 target = None
2815 2811 if isinstance(target, ast.Name):
2816 2812 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
2817 2813 ast.fix_missing_locations(nnode)
2818 2814 nodelist.append(nnode)
2819 2815 interactivity = 'last_expr'
2820 2816
2821 2817 if interactivity == 'last_expr':
2822 2818 if isinstance(nodelist[-1], ast.Expr):
2823 2819 interactivity = "last"
2824 2820 else:
2825 2821 interactivity = "none"
2826 2822
2827 2823 if interactivity == 'none':
2828 2824 to_run_exec, to_run_interactive = nodelist, []
2829 2825 elif interactivity == 'last':
2830 2826 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2831 2827 elif interactivity == 'all':
2832 2828 to_run_exec, to_run_interactive = [], nodelist
2833 2829 else:
2834 2830 raise ValueError("Interactivity was %r" % interactivity)
2835 2831
2836 2832 try:
2837 2833 for i, node in enumerate(to_run_exec):
2838 2834 mod = ast.Module([node])
2839 2835 code = compiler(mod, cell_name, "exec")
2840 2836 if self.run_code(code, result):
2841 2837 return True
2842 2838
2843 2839 for i, node in enumerate(to_run_interactive):
2844 2840 mod = ast.Interactive([node])
2845 2841 code = compiler(mod, cell_name, "single")
2846 2842 if self.run_code(code, result):
2847 2843 return True
2848 2844
2849 2845 # Flush softspace
2850 2846 if softspace(sys.stdout, 0):
2851 2847 print()
2852 2848
2853 2849 except:
2854 2850 # It's possible to have exceptions raised here, typically by
2855 2851 # compilation of odd code (such as a naked 'return' outside a
2856 2852 # function) that did parse but isn't valid. Typically the exception
2857 2853 # is a SyntaxError, but it's safest just to catch anything and show
2858 2854 # the user a traceback.
2859 2855
2860 2856 # We do only one try/except outside the loop to minimize the impact
2861 2857 # on runtime, and also because if any node in the node list is
2862 2858 # broken, we should stop execution completely.
2863 2859 if result:
2864 2860 result.error_before_exec = sys.exc_info()[1]
2865 2861 self.showtraceback()
2866 2862 return True
2867 2863
2868 2864 return False
2869 2865
2870 2866 def run_code(self, code_obj, result=None):
2871 2867 """Execute a code object.
2872 2868
2873 2869 When an exception occurs, self.showtraceback() is called to display a
2874 2870 traceback.
2875 2871
2876 2872 Parameters
2877 2873 ----------
2878 2874 code_obj : code object
2879 2875 A compiled code object, to be executed
2880 2876 result : ExecutionResult, optional
2881 2877 An object to store exceptions that occur during execution.
2882 2878
2883 2879 Returns
2884 2880 -------
2885 2881 False : successful execution.
2886 2882 True : an error occurred.
2887 2883 """
2888 2884 # Set our own excepthook in case the user code tries to call it
2889 2885 # directly, so that the IPython crash handler doesn't get triggered
2890 2886 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2891 2887
2892 2888 # we save the original sys.excepthook in the instance, in case config
2893 2889 # code (such as magics) needs access to it.
2894 2890 self.sys_excepthook = old_excepthook
2895 2891 outflag = True # happens in more places, so it's easier as default
2896 2892 try:
2897 2893 try:
2898 2894 self.hooks.pre_run_code_hook()
2899 2895 #rprint('Running code', repr(code_obj)) # dbg
2900 2896 exec(code_obj, self.user_global_ns, self.user_ns)
2901 2897 finally:
2902 2898 # Reset our crash handler in place
2903 2899 sys.excepthook = old_excepthook
2904 2900 except SystemExit as e:
2905 2901 if result is not None:
2906 2902 result.error_in_exec = e
2907 2903 self.showtraceback(exception_only=True)
2908 2904 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2909 2905 except self.custom_exceptions:
2910 2906 etype, value, tb = sys.exc_info()
2911 2907 if result is not None:
2912 2908 result.error_in_exec = value
2913 2909 self.CustomTB(etype, value, tb)
2914 2910 except:
2915 2911 if result is not None:
2916 2912 result.error_in_exec = sys.exc_info()[1]
2917 2913 self.showtraceback(running_compiled_code=True)
2918 2914 else:
2919 2915 outflag = False
2920 2916 return outflag
2921 2917
2922 2918 # For backwards compatibility
2923 2919 runcode = run_code
2924 2920
2925 2921 #-------------------------------------------------------------------------
2926 2922 # Things related to GUI support and pylab
2927 2923 #-------------------------------------------------------------------------
2928 2924
2929 2925 active_eventloop = None
2930 2926
2931 2927 def enable_gui(self, gui=None):
2932 2928 raise NotImplementedError('Implement enable_gui in a subclass')
2933 2929
2934 2930 def enable_matplotlib(self, gui=None):
2935 2931 """Enable interactive matplotlib and inline figure support.
2936 2932
2937 2933 This takes the following steps:
2938 2934
2939 2935 1. select the appropriate eventloop and matplotlib backend
2940 2936 2. set up matplotlib for interactive use with that backend
2941 2937 3. configure formatters for inline figure display
2942 2938 4. enable the selected gui eventloop
2943 2939
2944 2940 Parameters
2945 2941 ----------
2946 2942 gui : optional, string
2947 2943 If given, dictates the choice of matplotlib GUI backend to use
2948 2944 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2949 2945 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2950 2946 matplotlib (as dictated by the matplotlib build-time options plus the
2951 2947 user's matplotlibrc configuration file). Note that not all backends
2952 2948 make sense in all contexts, for example a terminal ipython can't
2953 2949 display figures inline.
2954 2950 """
2955 2951 from IPython.core import pylabtools as pt
2956 2952 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2957 2953
2958 2954 if gui != 'inline':
2959 2955 # If we have our first gui selection, store it
2960 2956 if self.pylab_gui_select is None:
2961 2957 self.pylab_gui_select = gui
2962 2958 # Otherwise if they are different
2963 2959 elif gui != self.pylab_gui_select:
2964 2960 print('Warning: Cannot change to a different GUI toolkit: %s.'
2965 2961 ' Using %s instead.' % (gui, self.pylab_gui_select))
2966 2962 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2967 2963
2968 2964 pt.activate_matplotlib(backend)
2969 2965 pt.configure_inline_support(self, backend)
2970 2966
2971 2967 # Now we must activate the gui pylab wants to use, and fix %run to take
2972 2968 # plot updates into account
2973 2969 self.enable_gui(gui)
2974 2970 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2975 2971 pt.mpl_runner(self.safe_execfile)
2976 2972
2977 2973 return gui, backend
2978 2974
2979 2975 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2980 2976 """Activate pylab support at runtime.
2981 2977
2982 2978 This turns on support for matplotlib, preloads into the interactive
2983 2979 namespace all of numpy and pylab, and configures IPython to correctly
2984 2980 interact with the GUI event loop. The GUI backend to be used can be
2985 2981 optionally selected with the optional ``gui`` argument.
2986 2982
2987 2983 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2988 2984
2989 2985 Parameters
2990 2986 ----------
2991 2987 gui : optional, string
2992 2988 If given, dictates the choice of matplotlib GUI backend to use
2993 2989 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2994 2990 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2995 2991 matplotlib (as dictated by the matplotlib build-time options plus the
2996 2992 user's matplotlibrc configuration file). Note that not all backends
2997 2993 make sense in all contexts, for example a terminal ipython can't
2998 2994 display figures inline.
2999 2995 import_all : optional, bool, default: True
3000 2996 Whether to do `from numpy import *` and `from pylab import *`
3001 2997 in addition to module imports.
3002 2998 welcome_message : deprecated
3003 2999 This argument is ignored, no welcome message will be displayed.
3004 3000 """
3005 3001 from IPython.core.pylabtools import import_pylab
3006 3002
3007 3003 gui, backend = self.enable_matplotlib(gui)
3008 3004
3009 3005 # We want to prevent the loading of pylab to pollute the user's
3010 3006 # namespace as shown by the %who* magics, so we execute the activation
3011 3007 # code in an empty namespace, and we update *both* user_ns and
3012 3008 # user_ns_hidden with this information.
3013 3009 ns = {}
3014 3010 import_pylab(ns, import_all)
3015 3011 # warn about clobbered names
3016 3012 ignored = {"__builtins__"}
3017 3013 both = set(ns).intersection(self.user_ns).difference(ignored)
3018 3014 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3019 3015 self.user_ns.update(ns)
3020 3016 self.user_ns_hidden.update(ns)
3021 3017 return gui, backend, clobbered
3022 3018
3023 3019 #-------------------------------------------------------------------------
3024 3020 # Utilities
3025 3021 #-------------------------------------------------------------------------
3026 3022
3027 3023 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3028 3024 """Expand python variables in a string.
3029 3025
3030 3026 The depth argument indicates how many frames above the caller should
3031 3027 be walked to look for the local namespace where to expand variables.
3032 3028
3033 3029 The global namespace for expansion is always the user's interactive
3034 3030 namespace.
3035 3031 """
3036 3032 ns = self.user_ns.copy()
3037 3033 try:
3038 3034 frame = sys._getframe(depth+1)
3039 3035 except ValueError:
3040 3036 # This is thrown if there aren't that many frames on the stack,
3041 3037 # e.g. if a script called run_line_magic() directly.
3042 3038 pass
3043 3039 else:
3044 3040 ns.update(frame.f_locals)
3045 3041
3046 3042 try:
3047 3043 # We have to use .vformat() here, because 'self' is a valid and common
3048 3044 # name, and expanding **ns for .format() would make it collide with
3049 3045 # the 'self' argument of the method.
3050 3046 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3051 3047 except Exception:
3052 3048 # if formatter couldn't format, just let it go untransformed
3053 3049 pass
3054 3050 return cmd
3055 3051
3056 3052 def mktempfile(self, data=None, prefix='ipython_edit_'):
3057 3053 """Make a new tempfile and return its filename.
3058 3054
3059 3055 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3060 3056 but it registers the created filename internally so ipython cleans it up
3061 3057 at exit time.
3062 3058
3063 3059 Optional inputs:
3064 3060
3065 3061 - data(None): if data is given, it gets written out to the temp file
3066 3062 immediately, and the file is closed again."""
3067 3063
3068 3064 dirname = tempfile.mkdtemp(prefix=prefix)
3069 3065 self.tempdirs.append(dirname)
3070 3066
3071 3067 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3072 3068 os.close(handle) # On Windows, there can only be one open handle on a file
3073 3069 self.tempfiles.append(filename)
3074 3070
3075 3071 if data:
3076 3072 tmp_file = open(filename,'w')
3077 3073 tmp_file.write(data)
3078 3074 tmp_file.close()
3079 3075 return filename
3080 3076
3081 3077 @undoc
3082 3078 def write(self,data):
3083 3079 """DEPRECATED: Write a string to the default output"""
3084 3080 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3085 3081 DeprecationWarning, stacklevel=2)
3086 3082 sys.stdout.write(data)
3087 3083
3088 3084 @undoc
3089 3085 def write_err(self,data):
3090 3086 """DEPRECATED: Write a string to the default error output"""
3091 3087 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3092 3088 DeprecationWarning, stacklevel=2)
3093 3089 sys.stderr.write(data)
3094 3090
3095 3091 def ask_yes_no(self, prompt, default=None, interrupt=None):
3096 3092 if self.quiet:
3097 3093 return True
3098 3094 return ask_yes_no(prompt,default,interrupt)
3099 3095
3100 3096 def show_usage(self):
3101 3097 """Show a usage message"""
3102 3098 page.page(IPython.core.usage.interactive_usage)
3103 3099
3104 3100 def extract_input_lines(self, range_str, raw=False):
3105 3101 """Return as a string a set of input history slices.
3106 3102
3107 3103 Parameters
3108 3104 ----------
3109 3105 range_str : string
3110 3106 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3111 3107 since this function is for use by magic functions which get their
3112 3108 arguments as strings. The number before the / is the session
3113 3109 number: ~n goes n back from the current session.
3114 3110
3115 3111 raw : bool, optional
3116 3112 By default, the processed input is used. If this is true, the raw
3117 3113 input history is used instead.
3118 3114
3119 3115 Notes
3120 3116 -----
3121 3117
3122 3118 Slices can be described with two notations:
3123 3119
3124 3120 * ``N:M`` -> standard python form, means including items N...(M-1).
3125 3121 * ``N-M`` -> include items N..M (closed endpoint).
3126 3122 """
3127 3123 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3128 3124 return "\n".join(x for _, _, x in lines)
3129 3125
3130 3126 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3131 3127 """Get a code string from history, file, url, or a string or macro.
3132 3128
3133 3129 This is mainly used by magic functions.
3134 3130
3135 3131 Parameters
3136 3132 ----------
3137 3133
3138 3134 target : str
3139 3135
3140 3136 A string specifying code to retrieve. This will be tried respectively
3141 3137 as: ranges of input history (see %history for syntax), url,
3142 3138 corresponding .py file, filename, or an expression evaluating to a
3143 3139 string or Macro in the user namespace.
3144 3140
3145 3141 raw : bool
3146 3142 If true (default), retrieve raw history. Has no effect on the other
3147 3143 retrieval mechanisms.
3148 3144
3149 3145 py_only : bool (default False)
3150 3146 Only try to fetch python code, do not try alternative methods to decode file
3151 3147 if unicode fails.
3152 3148
3153 3149 Returns
3154 3150 -------
3155 3151 A string of code.
3156 3152
3157 3153 ValueError is raised if nothing is found, and TypeError if it evaluates
3158 3154 to an object of another type. In each case, .args[0] is a printable
3159 3155 message.
3160 3156 """
3161 3157 code = self.extract_input_lines(target, raw=raw) # Grab history
3162 3158 if code:
3163 3159 return code
3164 3160 try:
3165 3161 if target.startswith(('http://', 'https://')):
3166 3162 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3167 3163 except UnicodeDecodeError:
3168 3164 if not py_only :
3169 3165 # Deferred import
3170 3166 from urllib.request import urlopen
3171 3167 response = urlopen(target)
3172 3168 return response.read().decode('latin1')
3173 3169 raise ValueError(("'%s' seem to be unreadable.") % target)
3174 3170
3175 3171 potential_target = [target]
3176 3172 try :
3177 3173 potential_target.insert(0,get_py_filename(target))
3178 3174 except IOError:
3179 3175 pass
3180 3176
3181 3177 for tgt in potential_target :
3182 3178 if os.path.isfile(tgt): # Read file
3183 3179 try :
3184 3180 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3185 3181 except UnicodeDecodeError :
3186 3182 if not py_only :
3187 3183 with io_open(tgt,'r', encoding='latin1') as f :
3188 3184 return f.read()
3189 3185 raise ValueError(("'%s' seem to be unreadable.") % target)
3190 3186 elif os.path.isdir(os.path.expanduser(tgt)):
3191 3187 raise ValueError("'%s' is a directory, not a regular file." % target)
3192 3188
3193 3189 if search_ns:
3194 3190 # Inspect namespace to load object source
3195 3191 object_info = self.object_inspect(target, detail_level=1)
3196 3192 if object_info['found'] and object_info['source']:
3197 3193 return object_info['source']
3198 3194
3199 3195 try: # User namespace
3200 3196 codeobj = eval(target, self.user_ns)
3201 3197 except Exception:
3202 3198 raise ValueError(("'%s' was not found in history, as a file, url, "
3203 3199 "nor in the user namespace.") % target)
3204 3200
3205 3201 if isinstance(codeobj, str):
3206 3202 return codeobj
3207 3203 elif isinstance(codeobj, Macro):
3208 3204 return codeobj.value
3209 3205
3210 3206 raise TypeError("%s is neither a string nor a macro." % target,
3211 3207 codeobj)
3212 3208
3213 3209 #-------------------------------------------------------------------------
3214 3210 # Things related to IPython exiting
3215 3211 #-------------------------------------------------------------------------
3216 3212 def atexit_operations(self):
3217 3213 """This will be executed at the time of exit.
3218 3214
3219 3215 Cleanup operations and saving of persistent data that is done
3220 3216 unconditionally by IPython should be performed here.
3221 3217
3222 3218 For things that may depend on startup flags or platform specifics (such
3223 3219 as having readline or not), register a separate atexit function in the
3224 3220 code that has the appropriate information, rather than trying to
3225 3221 clutter
3226 3222 """
3227 3223 # Close the history session (this stores the end time and line count)
3228 3224 # this must be *before* the tempfile cleanup, in case of temporary
3229 3225 # history db
3230 3226 self.history_manager.end_session()
3231 3227
3232 3228 # Cleanup all tempfiles and folders left around
3233 3229 for tfile in self.tempfiles:
3234 3230 try:
3235 3231 os.unlink(tfile)
3236 3232 except OSError:
3237 3233 pass
3238 3234
3239 3235 for tdir in self.tempdirs:
3240 3236 try:
3241 3237 os.rmdir(tdir)
3242 3238 except OSError:
3243 3239 pass
3244 3240
3245 3241 # Clear all user namespaces to release all references cleanly.
3246 3242 self.reset(new_session=False)
3247 3243
3248 3244 # Run user hooks
3249 3245 self.hooks.shutdown_hook()
3250 3246
3251 3247 def cleanup(self):
3252 3248 self.restore_sys_module_state()
3253 3249
3254 3250
3255 3251 # Overridden in terminal subclass to change prompts
3256 3252 def switch_doctest_mode(self, mode):
3257 3253 pass
3258 3254
3259 3255
3260 3256 class InteractiveShellABC(metaclass=abc.ABCMeta):
3261 3257 """An abstract base class for InteractiveShell."""
3262 3258
3263 3259 InteractiveShellABC.register(InteractiveShell)
@@ -1,97 +1,97 b''
1 1 """Tests for input handlers.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Module imports
5 5 #-----------------------------------------------------------------------------
6 6
7 7 # third party
8 8 import nose.tools as nt
9 9
10 10 # our own packages
11 11 from IPython.core import autocall
12 12 from IPython.testing import tools as tt
13 13 from IPython.testing.globalipapp import get_ipython
14 14 from IPython.utils import py3compat
15 15
16 16 #-----------------------------------------------------------------------------
17 17 # Globals
18 18 #-----------------------------------------------------------------------------
19 19
20 20 # Get the public instance of IPython
21 21 ip = get_ipython()
22 22
23 23 failures = []
24 24 num_tests = 0
25 25
26 26 #-----------------------------------------------------------------------------
27 27 # Test functions
28 28 #-----------------------------------------------------------------------------
29 29
30 30 class CallableIndexable(object):
31 31 def __getitem__(self, idx): return True
32 32 def __call__(self, *args, **kws): return True
33 33
34 34
35 35 class Autocallable(autocall.IPyAutocall):
36 36 def __call__(self):
37 37 return "called"
38 38
39 39
40 40 def run(tests):
41 41 """Loop through a list of (pre, post) inputs, where pre is the string
42 42 handed to ipython, and post is how that string looks after it's been
43 43 transformed (i.e. ipython's notion of _i)"""
44 44 tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests)
45 45
46 46
47 47 def test_handlers():
48 48 call_idx = CallableIndexable()
49 49 ip.user_ns['call_idx'] = call_idx
50 50
51 51 # For many of the below, we're also checking that leading whitespace
52 52 # turns off the esc char, which it should unless there is a continuation
53 53 # line.
54 54 run([(i,py3compat.u_format(o)) for i,o in \
55 55 [('"no change"', '"no change"'), # normal
56 (u"lsmagic", "get_ipython().run_line_magic({u}'lsmagic', {u}'')"), # magic
56 (u"lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), # magic
57 57 #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
58 58 ]])
59 59
60 60 # Objects which are instances of IPyAutocall are *always* autocalled
61 61 autocallable = Autocallable()
62 62 ip.user_ns['autocallable'] = autocallable
63 63
64 64 # auto
65 65 ip.magic('autocall 0')
66 66 # Only explicit escapes or instances of IPyAutocallable should get
67 67 # expanded
68 68 run([
69 69 ('len "abc"', 'len "abc"'),
70 70 ('autocallable', 'autocallable()'),
71 71 # Don't add extra brackets (gh-1117)
72 72 ('autocallable()', 'autocallable()'),
73 73 ])
74 74 ip.magic('autocall 1')
75 75 run([
76 76 ('len "abc"', 'len("abc")'),
77 77 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
78 78 # Autocall is turned off if first arg is [] and the object
79 79 # is both callable and indexable. Like so:
80 80 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
81 81 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
82 82 ('call_idx 1', 'call_idx(1)'),
83 83 ('len', 'len'), # only at 2 does it auto-call on single args
84 84 ])
85 85 ip.magic('autocall 2')
86 86 run([
87 87 ('len "abc"', 'len("abc")'),
88 88 ('len "abc";', 'len("abc");'),
89 89 ('len [1,2]', 'len([1,2])'),
90 90 ('call_idx [1]', 'call_idx [1]'),
91 91 ('call_idx 1', 'call_idx(1)'),
92 92 # This is what's different:
93 93 ('len', 'len()'), # only at 2 does it auto-call on single args
94 94 ])
95 95 ip.magic('autocall 1')
96 96
97 97 nt.assert_equal(failures, [])
@@ -1,641 +1,641 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tests for the inputsplitter module."""
3 3
4 4
5 5 # Copyright (c) IPython Development Team.
6 6 # Distributed under the terms of the Modified BSD License.
7 7
8 8 import unittest
9 9 import sys
10 10
11 11 import nose.tools as nt
12 12
13 13 from IPython.core import inputsplitter as isp
14 14 from IPython.core.inputtransformer import InputTransformer
15 15 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
16 16 from IPython.testing import tools as tt
17 17 from IPython.utils import py3compat
18 18 from IPython.utils.py3compat import input
19 19
20 20 #-----------------------------------------------------------------------------
21 21 # Semi-complete examples (also used as tests)
22 22 #-----------------------------------------------------------------------------
23 23
24 24 # Note: at the bottom, there's a slightly more complete version of this that
25 25 # can be useful during development of code here.
26 26
27 27 def mini_interactive_loop(input_func):
28 28 """Minimal example of the logic of an interactive interpreter loop.
29 29
30 30 This serves as an example, and it is used by the test system with a fake
31 31 raw_input that simulates interactive input."""
32 32
33 33 from IPython.core.inputsplitter import InputSplitter
34 34
35 35 isp = InputSplitter()
36 36 # In practice, this input loop would be wrapped in an outside loop to read
37 37 # input indefinitely, until some exit/quit command was issued. Here we
38 38 # only illustrate the basic inner loop.
39 39 while isp.push_accepts_more():
40 40 indent = ' '*isp.indent_spaces
41 41 prompt = '>>> ' + indent
42 42 line = indent + input_func(prompt)
43 43 isp.push(line)
44 44
45 45 # Here we just return input so we can use it in a test suite, but a real
46 46 # interpreter would instead send it for execution somewhere.
47 47 src = isp.source_reset()
48 48 #print 'Input source was:\n', src # dbg
49 49 return src
50 50
51 51 #-----------------------------------------------------------------------------
52 52 # Test utilities, just for local use
53 53 #-----------------------------------------------------------------------------
54 54
55 55 def assemble(block):
56 56 """Assemble a block into multi-line sub-blocks."""
57 57 return ['\n'.join(sub_block)+'\n' for sub_block in block]
58 58
59 59
60 60 def pseudo_input(lines):
61 61 """Return a function that acts like raw_input but feeds the input list."""
62 62 ilines = iter(lines)
63 63 def raw_in(prompt):
64 64 try:
65 65 return next(ilines)
66 66 except StopIteration:
67 67 return ''
68 68 return raw_in
69 69
70 70 #-----------------------------------------------------------------------------
71 71 # Tests
72 72 #-----------------------------------------------------------------------------
73 73 def test_spaces():
74 74 tests = [('', 0),
75 75 (' ', 1),
76 76 ('\n', 0),
77 77 (' \n', 1),
78 78 ('x', 0),
79 79 (' x', 1),
80 80 (' x',2),
81 81 (' x',4),
82 82 # Note: tabs are counted as a single whitespace!
83 83 ('\tx', 1),
84 84 ('\t x', 2),
85 85 ]
86 86 tt.check_pairs(isp.num_ini_spaces, tests)
87 87
88 88
89 89 def test_remove_comments():
90 90 tests = [('text', 'text'),
91 91 ('text # comment', 'text '),
92 92 ('text # comment\n', 'text \n'),
93 93 ('text # comment \n', 'text \n'),
94 94 ('line # c \nline\n','line \nline\n'),
95 95 ('line # c \nline#c2 \nline\nline #c\n\n',
96 96 'line \nline\nline\nline \n\n'),
97 97 ]
98 98 tt.check_pairs(isp.remove_comments, tests)
99 99
100 100
101 101 def test_get_input_encoding():
102 102 encoding = isp.get_input_encoding()
103 103 nt.assert_true(isinstance(encoding, str))
104 104 # simple-minded check that at least encoding a simple string works with the
105 105 # encoding we got.
106 106 nt.assert_equal(u'test'.encode(encoding), b'test')
107 107
108 108
109 109 class NoInputEncodingTestCase(unittest.TestCase):
110 110 def setUp(self):
111 111 self.old_stdin = sys.stdin
112 112 class X: pass
113 113 fake_stdin = X()
114 114 sys.stdin = fake_stdin
115 115
116 116 def test(self):
117 117 # Verify that if sys.stdin has no 'encoding' attribute we do the right
118 118 # thing
119 119 enc = isp.get_input_encoding()
120 120 self.assertEqual(enc, 'ascii')
121 121
122 122 def tearDown(self):
123 123 sys.stdin = self.old_stdin
124 124
125 125
126 126 class InputSplitterTestCase(unittest.TestCase):
127 127 def setUp(self):
128 128 self.isp = isp.InputSplitter()
129 129
130 130 def test_reset(self):
131 131 isp = self.isp
132 132 isp.push('x=1')
133 133 isp.reset()
134 134 self.assertEqual(isp._buffer, [])
135 135 self.assertEqual(isp.indent_spaces, 0)
136 136 self.assertEqual(isp.source, '')
137 137 self.assertEqual(isp.code, None)
138 138 self.assertEqual(isp._is_complete, False)
139 139
140 140 def test_source(self):
141 141 self.isp._store('1')
142 142 self.isp._store('2')
143 143 self.assertEqual(self.isp.source, '1\n2\n')
144 144 self.assertEqual(len(self.isp._buffer)>0, True)
145 145 self.assertEqual(self.isp.source_reset(), '1\n2\n')
146 146 self.assertEqual(self.isp._buffer, [])
147 147 self.assertEqual(self.isp.source, '')
148 148
149 149 def test_indent(self):
150 150 isp = self.isp # shorthand
151 151 isp.push('x=1')
152 152 self.assertEqual(isp.indent_spaces, 0)
153 153 isp.push('if 1:\n x=1')
154 154 self.assertEqual(isp.indent_spaces, 4)
155 155 isp.push('y=2\n')
156 156 self.assertEqual(isp.indent_spaces, 0)
157 157
158 158 def test_indent2(self):
159 159 isp = self.isp
160 160 isp.push('if 1:')
161 161 self.assertEqual(isp.indent_spaces, 4)
162 162 isp.push(' x=1')
163 163 self.assertEqual(isp.indent_spaces, 4)
164 164 # Blank lines shouldn't change the indent level
165 165 isp.push(' '*2)
166 166 self.assertEqual(isp.indent_spaces, 4)
167 167
168 168 def test_indent3(self):
169 169 isp = self.isp
170 170 # When a multiline statement contains parens or multiline strings, we
171 171 # shouldn't get confused.
172 172 isp.push("if 1:")
173 173 isp.push(" x = (1+\n 2)")
174 174 self.assertEqual(isp.indent_spaces, 4)
175 175
176 176 def test_indent4(self):
177 177 isp = self.isp
178 178 # whitespace after ':' should not screw up indent level
179 179 isp.push('if 1: \n x=1')
180 180 self.assertEqual(isp.indent_spaces, 4)
181 181 isp.push('y=2\n')
182 182 self.assertEqual(isp.indent_spaces, 0)
183 183 isp.push('if 1:\t\n x=1')
184 184 self.assertEqual(isp.indent_spaces, 4)
185 185 isp.push('y=2\n')
186 186 self.assertEqual(isp.indent_spaces, 0)
187 187
188 188 def test_dedent_pass(self):
189 189 isp = self.isp # shorthand
190 190 # should NOT cause dedent
191 191 isp.push('if 1:\n passes = 5')
192 192 self.assertEqual(isp.indent_spaces, 4)
193 193 isp.push('if 1:\n pass')
194 194 self.assertEqual(isp.indent_spaces, 0)
195 195 isp.push('if 1:\n pass ')
196 196 self.assertEqual(isp.indent_spaces, 0)
197 197
198 198 def test_dedent_break(self):
199 199 isp = self.isp # shorthand
200 200 # should NOT cause dedent
201 201 isp.push('while 1:\n breaks = 5')
202 202 self.assertEqual(isp.indent_spaces, 4)
203 203 isp.push('while 1:\n break')
204 204 self.assertEqual(isp.indent_spaces, 0)
205 205 isp.push('while 1:\n break ')
206 206 self.assertEqual(isp.indent_spaces, 0)
207 207
208 208 def test_dedent_continue(self):
209 209 isp = self.isp # shorthand
210 210 # should NOT cause dedent
211 211 isp.push('while 1:\n continues = 5')
212 212 self.assertEqual(isp.indent_spaces, 4)
213 213 isp.push('while 1:\n continue')
214 214 self.assertEqual(isp.indent_spaces, 0)
215 215 isp.push('while 1:\n continue ')
216 216 self.assertEqual(isp.indent_spaces, 0)
217 217
218 218 def test_dedent_raise(self):
219 219 isp = self.isp # shorthand
220 220 # should NOT cause dedent
221 221 isp.push('if 1:\n raised = 4')
222 222 self.assertEqual(isp.indent_spaces, 4)
223 223 isp.push('if 1:\n raise TypeError()')
224 224 self.assertEqual(isp.indent_spaces, 0)
225 225 isp.push('if 1:\n raise')
226 226 self.assertEqual(isp.indent_spaces, 0)
227 227 isp.push('if 1:\n raise ')
228 228 self.assertEqual(isp.indent_spaces, 0)
229 229
230 230 def test_dedent_return(self):
231 231 isp = self.isp # shorthand
232 232 # should NOT cause dedent
233 233 isp.push('if 1:\n returning = 4')
234 234 self.assertEqual(isp.indent_spaces, 4)
235 235 isp.push('if 1:\n return 5 + 493')
236 236 self.assertEqual(isp.indent_spaces, 0)
237 237 isp.push('if 1:\n return')
238 238 self.assertEqual(isp.indent_spaces, 0)
239 239 isp.push('if 1:\n return ')
240 240 self.assertEqual(isp.indent_spaces, 0)
241 241 isp.push('if 1:\n return(0)')
242 242 self.assertEqual(isp.indent_spaces, 0)
243 243
244 244 def test_push(self):
245 245 isp = self.isp
246 246 self.assertEqual(isp.push('x=1'), True)
247 247
248 248 def test_push2(self):
249 249 isp = self.isp
250 250 self.assertEqual(isp.push('if 1:'), False)
251 251 for line in [' x=1', '# a comment', ' y=2']:
252 252 print(line)
253 253 self.assertEqual(isp.push(line), True)
254 254
255 255 def test_push3(self):
256 256 isp = self.isp
257 257 isp.push('if True:')
258 258 isp.push(' a = 1')
259 259 self.assertEqual(isp.push('b = [1,'), False)
260 260
261 261 def test_push_accepts_more(self):
262 262 isp = self.isp
263 263 isp.push('x=1')
264 264 self.assertEqual(isp.push_accepts_more(), False)
265 265
266 266 def test_push_accepts_more2(self):
267 267 isp = self.isp
268 268 isp.push('if 1:')
269 269 self.assertEqual(isp.push_accepts_more(), True)
270 270 isp.push(' x=1')
271 271 self.assertEqual(isp.push_accepts_more(), True)
272 272 isp.push('')
273 273 self.assertEqual(isp.push_accepts_more(), False)
274 274
275 275 def test_push_accepts_more3(self):
276 276 isp = self.isp
277 277 isp.push("x = (2+\n3)")
278 278 self.assertEqual(isp.push_accepts_more(), False)
279 279
280 280 def test_push_accepts_more4(self):
281 281 isp = self.isp
282 282 # When a multiline statement contains parens or multiline strings, we
283 283 # shouldn't get confused.
284 284 # FIXME: we should be able to better handle de-dents in statements like
285 285 # multiline strings and multiline expressions (continued with \ or
286 286 # parens). Right now we aren't handling the indentation tracking quite
287 287 # correctly with this, though in practice it may not be too much of a
288 288 # problem. We'll need to see.
289 289 isp.push("if 1:")
290 290 isp.push(" x = (2+")
291 291 isp.push(" 3)")
292 292 self.assertEqual(isp.push_accepts_more(), True)
293 293 isp.push(" y = 3")
294 294 self.assertEqual(isp.push_accepts_more(), True)
295 295 isp.push('')
296 296 self.assertEqual(isp.push_accepts_more(), False)
297 297
298 298 def test_push_accepts_more5(self):
299 299 isp = self.isp
300 300 isp.push('try:')
301 301 isp.push(' a = 5')
302 302 isp.push('except:')
303 303 isp.push(' raise')
304 304 # We want to be able to add an else: block at this point, so it should
305 305 # wait for a blank line.
306 306 self.assertEqual(isp.push_accepts_more(), True)
307 307
308 308 def test_continuation(self):
309 309 isp = self.isp
310 310 isp.push("import os, \\")
311 311 self.assertEqual(isp.push_accepts_more(), True)
312 312 isp.push("sys")
313 313 self.assertEqual(isp.push_accepts_more(), False)
314 314
315 315 def test_syntax_error(self):
316 316 isp = self.isp
317 317 # Syntax errors immediately produce a 'ready' block, so the invalid
318 318 # Python can be sent to the kernel for evaluation with possible ipython
319 319 # special-syntax conversion.
320 320 isp.push('run foo')
321 321 self.assertEqual(isp.push_accepts_more(), False)
322 322
323 323 def test_unicode(self):
324 324 self.isp.push(u"Pérez")
325 325 self.isp.push(u'\xc3\xa9')
326 326 self.isp.push(u"u'\xc3\xa9'")
327 327
328 328 def test_line_continuation(self):
329 329 """ Test issue #2108."""
330 330 isp = self.isp
331 331 # A blank line after a line continuation should not accept more
332 332 isp.push("1 \\\n\n")
333 333 self.assertEqual(isp.push_accepts_more(), False)
334 334 # Whitespace after a \ is a SyntaxError. The only way to test that
335 335 # here is to test that push doesn't accept more (as with
336 336 # test_syntax_error() above).
337 337 isp.push(r"1 \ ")
338 338 self.assertEqual(isp.push_accepts_more(), False)
339 339 # Even if the line is continuable (c.f. the regular Python
340 340 # interpreter)
341 341 isp.push(r"(1 \ ")
342 342 self.assertEqual(isp.push_accepts_more(), False)
343 343
344 344 def test_check_complete(self):
345 345 isp = self.isp
346 346 self.assertEqual(isp.check_complete("a = 1"), ('complete', None))
347 347 self.assertEqual(isp.check_complete("for a in range(5):"), ('incomplete', 4))
348 348 self.assertEqual(isp.check_complete("raise = 2"), ('invalid', None))
349 349 self.assertEqual(isp.check_complete("a = [1,\n2,"), ('incomplete', 0))
350 350 self.assertEqual(isp.check_complete("def a():\n x=1\n global x"), ('invalid', None))
351 351
352 352 class InteractiveLoopTestCase(unittest.TestCase):
353 353 """Tests for an interactive loop like a python shell.
354 354 """
355 355 def check_ns(self, lines, ns):
356 356 """Validate that the given input lines produce the resulting namespace.
357 357
358 358 Note: the input lines are given exactly as they would be typed in an
359 359 auto-indenting environment, as mini_interactive_loop above already does
360 360 auto-indenting and prepends spaces to the input.
361 361 """
362 362 src = mini_interactive_loop(pseudo_input(lines))
363 363 test_ns = {}
364 364 exec(src, test_ns)
365 365 # We can't check that the provided ns is identical to the test_ns,
366 366 # because Python fills test_ns with extra keys (copyright, etc). But
367 367 # we can check that the given dict is *contained* in test_ns
368 368 for k,v in ns.items():
369 369 self.assertEqual(test_ns[k], v)
370 370
371 371 def test_simple(self):
372 372 self.check_ns(['x=1'], dict(x=1))
373 373
374 374 def test_simple2(self):
375 375 self.check_ns(['if 1:', 'x=2'], dict(x=2))
376 376
377 377 def test_xy(self):
378 378 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
379 379
380 380 def test_abc(self):
381 381 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
382 382
383 383 def test_multi(self):
384 384 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
385 385
386 386
387 387 class IPythonInputTestCase(InputSplitterTestCase):
388 388 """By just creating a new class whose .isp is a different instance, we
389 389 re-run the same test battery on the new input splitter.
390 390
391 391 In addition, this runs the tests over the syntax and syntax_ml dicts that
392 392 were tested by individual functions, as part of the OO interface.
393 393
394 394 It also makes some checks on the raw buffer storage.
395 395 """
396 396
397 397 def setUp(self):
398 398 self.isp = isp.IPythonInputSplitter()
399 399
400 400 def test_syntax(self):
401 401 """Call all single-line syntax tests from the main object"""
402 402 isp = self.isp
403 403 for example in syntax.values():
404 404 for raw, out_t in example:
405 405 if raw.startswith(' '):
406 406 continue
407 407
408 408 isp.push(raw+'\n')
409 409 out_raw = isp.source_raw
410 410 out = isp.source_reset()
411 411 self.assertEqual(out.rstrip(), out_t,
412 412 tt.pair_fail_msg.format("inputsplitter",raw, out_t, out))
413 413 self.assertEqual(out_raw.rstrip(), raw.rstrip())
414 414
415 415 def test_syntax_multiline(self):
416 416 isp = self.isp
417 417 for example in syntax_ml.values():
418 418 for line_pairs in example:
419 419 out_t_parts = []
420 420 raw_parts = []
421 421 for lraw, out_t_part in line_pairs:
422 422 if out_t_part is not None:
423 423 out_t_parts.append(out_t_part)
424 424
425 425 if lraw is not None:
426 426 isp.push(lraw)
427 427 raw_parts.append(lraw)
428 428
429 429 out_raw = isp.source_raw
430 430 out = isp.source_reset()
431 431 out_t = '\n'.join(out_t_parts).rstrip()
432 432 raw = '\n'.join(raw_parts).rstrip()
433 433 self.assertEqual(out.rstrip(), out_t)
434 434 self.assertEqual(out_raw.rstrip(), raw)
435 435
436 436 def test_syntax_multiline_cell(self):
437 437 isp = self.isp
438 438 for example in syntax_ml.values():
439 439
440 440 out_t_parts = []
441 441 for line_pairs in example:
442 442 raw = '\n'.join(r for r, _ in line_pairs if r is not None)
443 443 out_t = '\n'.join(t for _,t in line_pairs if t is not None)
444 444 out = isp.transform_cell(raw)
445 445 # Match ignoring trailing whitespace
446 446 self.assertEqual(out.rstrip(), out_t.rstrip())
447 447
448 448 def test_cellmagic_preempt(self):
449 449 isp = self.isp
450 450 for raw, name, line, cell in [
451 451 ("%%cellm a\nIn[1]:", u'cellm', u'a', u'In[1]:'),
452 452 ("%%cellm \nline\n>>> hi", u'cellm', u'', u'line\n>>> hi'),
453 453 (">>> %%cellm \nline\n>>> hi", u'cellm', u'', u'line\nhi'),
454 454 ("%%cellm \n>>> hi", u'cellm', u'', u'>>> hi'),
455 455 ("%%cellm \nline1\nline2", u'cellm', u'', u'line1\nline2'),
456 456 ("%%cellm \nline1\\\\\nline2", u'cellm', u'', u'line1\\\\\nline2'),
457 457 ]:
458 458 expected = "get_ipython().run_cell_magic(%r, %r, %r)" % (
459 459 name, line, cell
460 460 )
461 461 out = isp.transform_cell(raw)
462 462 self.assertEqual(out.rstrip(), expected.rstrip())
463 463
464 464 def test_multiline_passthrough(self):
465 465 isp = self.isp
466 466 class CommentTransformer(InputTransformer):
467 467 def __init__(self):
468 468 self._lines = []
469 469
470 470 def push(self, line):
471 471 self._lines.append(line + '#')
472 472
473 473 def reset(self):
474 474 text = '\n'.join(self._lines)
475 475 self._lines = []
476 476 return text
477 477
478 478 isp.physical_line_transforms.insert(0, CommentTransformer())
479 479
480 480 for raw, expected in [
481 481 ("a=5", "a=5#"),
482 482 ("%ls foo", "get_ipython().run_line_magic(%r, %r)" % (u'ls', u'foo#')),
483 483 ("!ls foo\n%ls bar", "get_ipython().system(%r)\nget_ipython().run_line_magic(%r, %r)" % (
484 484 u'ls foo#', u'ls', u'bar#'
485 485 )),
486 486 ("1\n2\n3\n%ls foo\n4\n5", "1#\n2#\n3#\nget_ipython().run_line_magic(%r, %r)\n4#\n5#" % (u'ls', u'foo#')),
487 487 ]:
488 488 out = isp.transform_cell(raw)
489 489 self.assertEqual(out.rstrip(), expected.rstrip())
490 490
491 491 #-----------------------------------------------------------------------------
492 492 # Main - use as a script, mostly for developer experiments
493 493 #-----------------------------------------------------------------------------
494 494
495 495 if __name__ == '__main__':
496 496 # A simple demo for interactive experimentation. This code will not get
497 497 # picked up by any test suite.
498 498 from IPython.core.inputsplitter import IPythonInputSplitter
499 499
500 500 # configure here the syntax to use, prompt and whether to autoindent
501 501 #isp, start_prompt = InputSplitter(), '>>> '
502 502 isp, start_prompt = IPythonInputSplitter(), 'In> '
503 503
504 504 autoindent = True
505 505 #autoindent = False
506 506
507 507 try:
508 508 while True:
509 509 prompt = start_prompt
510 510 while isp.push_accepts_more():
511 511 indent = ' '*isp.indent_spaces
512 512 if autoindent:
513 513 line = indent + input(prompt+indent)
514 514 else:
515 515 line = input(prompt)
516 516 isp.push(line)
517 517 prompt = '... '
518 518
519 519 # Here we just return input so we can use it in a test suite, but a
520 520 # real interpreter would instead send it for execution somewhere.
521 521 #src = isp.source; raise EOFError # dbg
522 522 raw = isp.source_raw
523 523 src = isp.source_reset()
524 524 print('Input source was:\n', src)
525 525 print('Raw source was:\n', raw)
526 526 except EOFError:
527 527 print('Bye')
528 528
529 529 # Tests for cell magics support
530 530
531 531 def test_last_blank():
532 532 nt.assert_false(isp.last_blank(''))
533 533 nt.assert_false(isp.last_blank('abc'))
534 534 nt.assert_false(isp.last_blank('abc\n'))
535 535 nt.assert_false(isp.last_blank('abc\na'))
536 536
537 537 nt.assert_true(isp.last_blank('\n'))
538 538 nt.assert_true(isp.last_blank('\n '))
539 539 nt.assert_true(isp.last_blank('abc\n '))
540 540 nt.assert_true(isp.last_blank('abc\n\n'))
541 541 nt.assert_true(isp.last_blank('abc\nd\n\n'))
542 542 nt.assert_true(isp.last_blank('abc\nd\ne\n\n'))
543 543 nt.assert_true(isp.last_blank('abc \n \n \n\n'))
544 544
545 545
546 546 def test_last_two_blanks():
547 547 nt.assert_false(isp.last_two_blanks(''))
548 548 nt.assert_false(isp.last_two_blanks('abc'))
549 549 nt.assert_false(isp.last_two_blanks('abc\n'))
550 550 nt.assert_false(isp.last_two_blanks('abc\n\na'))
551 551 nt.assert_false(isp.last_two_blanks('abc\n \n'))
552 552 nt.assert_false(isp.last_two_blanks('abc\n\n'))
553 553
554 554 nt.assert_true(isp.last_two_blanks('\n\n'))
555 555 nt.assert_true(isp.last_two_blanks('\n\n '))
556 556 nt.assert_true(isp.last_two_blanks('\n \n'))
557 557 nt.assert_true(isp.last_two_blanks('abc\n\n '))
558 558 nt.assert_true(isp.last_two_blanks('abc\n\n\n'))
559 559 nt.assert_true(isp.last_two_blanks('abc\n\n \n'))
560 560 nt.assert_true(isp.last_two_blanks('abc\n\n \n '))
561 561 nt.assert_true(isp.last_two_blanks('abc\n\n \n \n'))
562 562 nt.assert_true(isp.last_two_blanks('abc\nd\n\n\n'))
563 563 nt.assert_true(isp.last_two_blanks('abc\nd\ne\nf\n\n\n'))
564 564
565 565
566 566 class CellMagicsCommon(object):
567 567
568 568 def test_whole_cell(self):
569 569 src = "%%cellm line\nbody\n"
570 570 out = self.sp.transform_cell(src)
571 ref = u"get_ipython().run_cell_magic({u}'cellm', {u}'line', {u}'body')\n"
571 ref = u"get_ipython().run_cell_magic('cellm', 'line', 'body')\n"
572 572 nt.assert_equal(out, py3compat.u_format(ref))
573 573
574 574 def test_cellmagic_help(self):
575 575 self.sp.push('%%cellm?')
576 576 nt.assert_false(self.sp.push_accepts_more())
577 577
578 578 def tearDown(self):
579 579 self.sp.reset()
580 580
581 581
582 582 class CellModeCellMagics(CellMagicsCommon, unittest.TestCase):
583 583 sp = isp.IPythonInputSplitter(line_input_checker=False)
584 584
585 585 def test_incremental(self):
586 586 sp = self.sp
587 587 sp.push('%%cellm firstline\n')
588 588 nt.assert_true(sp.push_accepts_more()) #1
589 589 sp.push('line2\n')
590 590 nt.assert_true(sp.push_accepts_more()) #2
591 591 sp.push('\n')
592 592 # This should accept a blank line and carry on until the cell is reset
593 593 nt.assert_true(sp.push_accepts_more()) #3
594 594
595 595 def test_no_strip_coding(self):
596 596 src = '\n'.join([
597 597 '%%writefile foo.py',
598 598 '# coding: utf-8',
599 599 'print(u"üñîçø∂é")',
600 600 ])
601 601 out = self.sp.transform_cell(src)
602 602 nt.assert_in('# coding: utf-8', out)
603 603
604 604
605 605 class LineModeCellMagics(CellMagicsCommon, unittest.TestCase):
606 606 sp = isp.IPythonInputSplitter(line_input_checker=True)
607 607
608 608 def test_incremental(self):
609 609 sp = self.sp
610 610 sp.push('%%cellm line2\n')
611 611 nt.assert_true(sp.push_accepts_more()) #1
612 612 sp.push('\n')
613 613 # In this case, a blank line should end the cell magic
614 614 nt.assert_false(sp.push_accepts_more()) #2
615 615
616 616 indentation_samples = [
617 617 ('a = 1', 0),
618 618 ('for a in b:', 4),
619 619 ('def f():', 4),
620 620 ('def f(): #comment', 4),
621 621 ('a = ":#not a comment"', 0),
622 622 ('def f():\n a = 1', 4),
623 623 ('def f():\n return 1', 0),
624 624 ('for a in b:\n'
625 625 ' if a < 0:'
626 626 ' continue', 3),
627 627 ('a = {', 4),
628 628 ('a = {\n'
629 629 ' 1,', 5),
630 630 ('b = """123', 0),
631 631 ('', 0),
632 632 ('def f():\n pass', 0),
633 633 ('class Bar:\n def f():\n pass', 4),
634 634 ('class Bar:\n def f():\n raise', 4),
635 635 ]
636 636
637 637 def test_find_next_indent():
638 638 for code, exp in indentation_samples:
639 639 res = isp.find_next_indent(code)
640 640 msg = "{!r} != {!r} (expected)\n Code: {!r}".format(res, exp, code)
641 641 assert res == exp, msg
@@ -1,494 +1,494 b''
1 1 import tokenize
2 2 import nose.tools as nt
3 3
4 4 from IPython.testing import tools as tt
5 5 from IPython.utils import py3compat
6 6 u_fmt = py3compat.u_format
7 7
8 8 from IPython.core import inputtransformer as ipt
9 9
10 10 def transform_and_reset(transformer):
11 11 transformer = transformer()
12 12 def transform(inp):
13 13 try:
14 14 return transformer.push(inp)
15 15 finally:
16 16 transformer.reset()
17 17
18 18 return transform
19 19
20 20 # Transformer tests
21 21 def transform_checker(tests, transformer, **kwargs):
22 22 """Utility to loop over test inputs"""
23 23 transformer = transformer(**kwargs)
24 24 try:
25 25 for inp, tr in tests:
26 26 if inp is None:
27 27 out = transformer.reset()
28 28 else:
29 29 out = transformer.push(inp)
30 30 nt.assert_equal(out, tr)
31 31 finally:
32 32 transformer.reset()
33 33
34 34 # Data for all the syntax tests in the form of lists of pairs of
35 35 # raw/transformed input. We store it here as a global dict so that we can use
36 36 # it both within single-function tests and also to validate the behavior of the
37 37 # larger objects
38 38
39 39 syntax = \
40 40 dict(assign_system =
41 41 [(i,py3compat.u_format(o)) for i,o in \
42 [(u'a =! ls', "a = get_ipython().getoutput({u}'ls')"),
43 (u'b = !ls', "b = get_ipython().getoutput({u}'ls')"),
44 (u'c= !ls', "c = get_ipython().getoutput({u}'ls')"),
42 [(u'a =! ls', "a = get_ipython().getoutput('ls')"),
43 (u'b = !ls', "b = get_ipython().getoutput('ls')"),
44 (u'c= !ls', "c = get_ipython().getoutput('ls')"),
45 45 (u'd == !ls', u'd == !ls'), # Invalid syntax, but we leave == alone.
46 46 ('x=1', 'x=1'), # normal input is unmodified
47 47 (' ',' '), # blank lines are kept intact
48 48 # Tuple unpacking
49 (u"a, b = !echo 'a\\nb'", u"a, b = get_ipython().getoutput({u}\"echo 'a\\\\nb'\")"),
50 (u"a,= !echo 'a'", u"a, = get_ipython().getoutput({u}\"echo 'a'\")"),
51 (u"a, *bc = !echo 'a\\nb\\nc'", u"a, *bc = get_ipython().getoutput({u}\"echo 'a\\\\nb\\\\nc'\")"),
49 (u"a, b = !echo 'a\\nb'", u"a, b = get_ipython().getoutput(\"echo 'a\\\\nb'\")"),
50 (u"a,= !echo 'a'", u"a, = get_ipython().getoutput(\"echo 'a'\")"),
51 (u"a, *bc = !echo 'a\\nb\\nc'", u"a, *bc = get_ipython().getoutput(\"echo 'a\\\\nb\\\\nc'\")"),
52 52 # Tuple unpacking with regular Python expressions, not our syntax.
53 53 (u"a, b = range(2)", u"a, b = range(2)"),
54 54 (u"a, = range(1)", u"a, = range(1)"),
55 55 (u"a, *bc = range(3)", u"a, *bc = range(3)"),
56 56 ]],
57 57
58 58 assign_magic =
59 59 [(i,py3compat.u_format(o)) for i,o in \
60 [(u'a =% who', "a = get_ipython().run_line_magic({u}'who', {u}'')"),
61 (u'b = %who', "b = get_ipython().run_line_magic({u}'who', {u}'')"),
62 (u'c= %ls', "c = get_ipython().run_line_magic({u}'ls', {u}'')"),
60 [(u'a =% who', "a = get_ipython().run_line_magic('who', '')"),
61 (u'b = %who', "b = get_ipython().run_line_magic('who', '')"),
62 (u'c= %ls', "c = get_ipython().run_line_magic('ls', '')"),
63 63 (u'd == %ls', u'd == %ls'), # Invalid syntax, but we leave == alone.
64 64 ('x=1', 'x=1'), # normal input is unmodified
65 65 (' ',' '), # blank lines are kept intact
66 (u"a, b = %foo", u"a, b = get_ipython().run_line_magic({u}'foo', {u}'')"),
66 (u"a, b = %foo", u"a, b = get_ipython().run_line_magic('foo', '')"),
67 67 ]],
68 68
69 69 classic_prompt =
70 70 [('>>> x=1', 'x=1'),
71 71 ('x=1', 'x=1'), # normal input is unmodified
72 72 (' ', ' '), # blank lines are kept intact
73 73 ],
74 74
75 75 ipy_prompt =
76 76 [('In [1]: x=1', 'x=1'),
77 77 ('x=1', 'x=1'), # normal input is unmodified
78 78 (' ',' '), # blank lines are kept intact
79 79 ],
80 80
81 81 # Tests for the escape transformer to leave normal code alone
82 82 escaped_noesc =
83 83 [ (' ', ' '),
84 84 ('x=1', 'x=1'),
85 85 ],
86 86
87 87 # System calls
88 88 escaped_shell =
89 89 [(i,py3compat.u_format(o)) for i,o in \
90 [ (u'!ls', "get_ipython().system({u}'ls')"),
90 [ (u'!ls', "get_ipython().system('ls')"),
91 91 # Double-escape shell, this means to capture the output of the
92 92 # subprocess and return it
93 (u'!!ls', "get_ipython().getoutput({u}'ls')"),
93 (u'!!ls', "get_ipython().getoutput('ls')"),
94 94 ]],
95 95
96 96 # Help/object info
97 97 escaped_help =
98 98 [(i,py3compat.u_format(o)) for i,o in \
99 99 [ (u'?', 'get_ipython().show_usage()'),
100 (u'?x1', "get_ipython().run_line_magic({u}'pinfo', {u}'x1')"),
101 (u'??x2', "get_ipython().run_line_magic({u}'pinfo2', {u}'x2')"),
102 (u'?a.*s', "get_ipython().run_line_magic({u}'psearch', {u}'a.*s')"),
103 (u'?%hist1', "get_ipython().run_line_magic({u}'pinfo', {u}'%hist1')"),
104 (u'?%%hist2', "get_ipython().run_line_magic({u}'pinfo', {u}'%%hist2')"),
105 (u'?abc = qwe', "get_ipython().run_line_magic({u}'pinfo', {u}'abc')"),
100 (u'?x1', "get_ipython().run_line_magic('pinfo', 'x1')"),
101 (u'??x2', "get_ipython().run_line_magic('pinfo2', 'x2')"),
102 (u'?a.*s', "get_ipython().run_line_magic('psearch', 'a.*s')"),
103 (u'?%hist1', "get_ipython().run_line_magic('pinfo', '%hist1')"),
104 (u'?%%hist2', "get_ipython().run_line_magic('pinfo', '%%hist2')"),
105 (u'?abc = qwe', "get_ipython().run_line_magic('pinfo', 'abc')"),
106 106 ]],
107 107
108 108 end_help =
109 109 [(i,py3compat.u_format(o)) for i,o in \
110 [ (u'x3?', "get_ipython().run_line_magic({u}'pinfo', {u}'x3')"),
111 (u'x4??', "get_ipython().run_line_magic({u}'pinfo2', {u}'x4')"),
112 (u'%hist1?', "get_ipython().run_line_magic({u}'pinfo', {u}'%hist1')"),
113 (u'%hist2??', "get_ipython().run_line_magic({u}'pinfo2', {u}'%hist2')"),
114 (u'%%hist3?', "get_ipython().run_line_magic({u}'pinfo', {u}'%%hist3')"),
115 (u'%%hist4??', "get_ipython().run_line_magic({u}'pinfo2', {u}'%%hist4')"),
116 (u'f*?', "get_ipython().run_line_magic({u}'psearch', {u}'f*')"),
117 (u'ax.*aspe*?', "get_ipython().run_line_magic({u}'psearch', {u}'ax.*aspe*')"),
118 (u'a = abc?', "get_ipython().set_next_input({u}'a = abc');"
119 "get_ipython().run_line_magic({u}'pinfo', {u}'abc')"),
120 (u'a = abc.qe??', "get_ipython().set_next_input({u}'a = abc.qe');"
121 "get_ipython().run_line_magic({u}'pinfo2', {u}'abc.qe')"),
122 (u'a = *.items?', "get_ipython().set_next_input({u}'a = *.items');"
123 "get_ipython().run_line_magic({u}'psearch', {u}'*.items')"),
124 (u'plot(a?', "get_ipython().set_next_input({u}'plot(a');"
125 "get_ipython().run_line_magic({u}'pinfo', {u}'a')"),
110 [ (u'x3?', "get_ipython().run_line_magic('pinfo', 'x3')"),
111 (u'x4??', "get_ipython().run_line_magic('pinfo2', 'x4')"),
112 (u'%hist1?', "get_ipython().run_line_magic('pinfo', '%hist1')"),
113 (u'%hist2??', "get_ipython().run_line_magic('pinfo2', '%hist2')"),
114 (u'%%hist3?', "get_ipython().run_line_magic('pinfo', '%%hist3')"),
115 (u'%%hist4??', "get_ipython().run_line_magic('pinfo2', '%%hist4')"),
116 (u'f*?', "get_ipython().run_line_magic('psearch', 'f*')"),
117 (u'ax.*aspe*?', "get_ipython().run_line_magic('psearch', 'ax.*aspe*')"),
118 (u'a = abc?', "get_ipython().set_next_input('a = abc');"
119 "get_ipython().run_line_magic('pinfo', 'abc')"),
120 (u'a = abc.qe??', "get_ipython().set_next_input('a = abc.qe');"
121 "get_ipython().run_line_magic('pinfo2', 'abc.qe')"),
122 (u'a = *.items?', "get_ipython().set_next_input('a = *.items');"
123 "get_ipython().run_line_magic('psearch', '*.items')"),
124 (u'plot(a?', "get_ipython().set_next_input('plot(a');"
125 "get_ipython().run_line_magic('pinfo', 'a')"),
126 126 (u'a*2 #comment?', 'a*2 #comment?'),
127 127 ]],
128 128
129 129 # Explicit magic calls
130 130 escaped_magic =
131 131 [(i,py3compat.u_format(o)) for i,o in \
132 [ (u'%cd', "get_ipython().run_line_magic({u}'cd', {u}'')"),
133 (u'%cd /home', "get_ipython().run_line_magic({u}'cd', {u}'/home')"),
132 [ (u'%cd', "get_ipython().run_line_magic('cd', '')"),
133 (u'%cd /home', "get_ipython().run_line_magic('cd', '/home')"),
134 134 # Backslashes need to be escaped.
135 (u'%cd C:\\User', "get_ipython().run_line_magic({u}'cd', {u}'C:\\\\User')"),
136 (u' %magic', " get_ipython().run_line_magic({u}'magic', {u}'')"),
135 (u'%cd C:\\User', "get_ipython().run_line_magic('cd', 'C:\\\\User')"),
136 (u' %magic', " get_ipython().run_line_magic('magic', '')"),
137 137 ]],
138 138
139 139 # Quoting with separate arguments
140 140 escaped_quote =
141 141 [ (',f', 'f("")'),
142 142 (',f x', 'f("x")'),
143 143 (' ,f y', ' f("y")'),
144 144 (',f a b', 'f("a", "b")'),
145 145 ],
146 146
147 147 # Quoting with single argument
148 148 escaped_quote2 =
149 149 [ (';f', 'f("")'),
150 150 (';f x', 'f("x")'),
151 151 (' ;f y', ' f("y")'),
152 152 (';f a b', 'f("a b")'),
153 153 ],
154 154
155 155 # Simply apply parens
156 156 escaped_paren =
157 157 [ ('/f', 'f()'),
158 158 ('/f x', 'f(x)'),
159 159 (' /f y', ' f(y)'),
160 160 ('/f a b', 'f(a, b)'),
161 161 ],
162 162
163 163 # Check that we transform prompts before other transforms
164 164 mixed =
165 165 [(i,py3compat.u_format(o)) for i,o in \
166 [ (u'In [1]: %lsmagic', "get_ipython().run_line_magic({u}'lsmagic', {u}'')"),
167 (u'>>> %lsmagic', "get_ipython().run_line_magic({u}'lsmagic', {u}'')"),
168 (u'In [2]: !ls', "get_ipython().system({u}'ls')"),
169 (u'In [3]: abs?', "get_ipython().run_line_magic({u}'pinfo', {u}'abs')"),
170 (u'In [4]: b = %who', "b = get_ipython().run_line_magic({u}'who', {u}'')"),
166 [ (u'In [1]: %lsmagic', "get_ipython().run_line_magic('lsmagic', '')"),
167 (u'>>> %lsmagic', "get_ipython().run_line_magic('lsmagic', '')"),
168 (u'In [2]: !ls', "get_ipython().system('ls')"),
169 (u'In [3]: abs?', "get_ipython().run_line_magic('pinfo', 'abs')"),
170 (u'In [4]: b = %who', "b = get_ipython().run_line_magic('who', '')"),
171 171 ]],
172 172 )
173 173
174 174 # multiline syntax examples. Each of these should be a list of lists, with
175 175 # each entry itself having pairs of raw/transformed input. The union (with
176 176 # '\n'.join() of the transformed inputs is what the splitter should produce
177 177 # when fed the raw lines one at a time via push.
178 178 syntax_ml = \
179 179 dict(classic_prompt =
180 180 [ [('>>> for i in range(10):','for i in range(10):'),
181 181 ('... print i',' print i'),
182 182 ('... ', ''),
183 183 ],
184 184 [('>>> a="""','a="""'),
185 185 ('... 123"""','123"""'),
186 186 ],
187 187 [('a="""','a="""'),
188 188 ('... 123','123'),
189 189 ('... 456"""','456"""'),
190 190 ],
191 191 [('a="""','a="""'),
192 192 ('>>> 123','123'),
193 193 ('... 456"""','456"""'),
194 194 ],
195 195 [('a="""','a="""'),
196 196 ('123','123'),
197 197 ('... 456"""','... 456"""'),
198 198 ],
199 199 [('....__class__','....__class__'),
200 200 ],
201 201 [('a=5', 'a=5'),
202 202 ('...', ''),
203 203 ],
204 204 [('>>> def f(x):', 'def f(x):'),
205 205 ('...', ''),
206 206 ('... return x', ' return x'),
207 207 ],
208 208 [('board = """....', 'board = """....'),
209 209 ('....', '....'),
210 210 ('...."""', '...."""'),
211 211 ],
212 212 ],
213 213
214 214 ipy_prompt =
215 215 [ [('In [24]: for i in range(10):','for i in range(10):'),
216 216 (' ....: print i',' print i'),
217 217 (' ....: ', ''),
218 218 ],
219 219 [('In [24]: for i in range(10):','for i in range(10):'),
220 220 # Qt console prompts expand with spaces, not dots
221 221 (' ...: print i',' print i'),
222 222 (' ...: ', ''),
223 223 ],
224 224 [('In [24]: for i in range(10):','for i in range(10):'),
225 225 # Sometimes whitespace preceding '...' has been removed
226 226 ('...: print i',' print i'),
227 227 ('...: ', ''),
228 228 ],
229 229 [('In [24]: for i in range(10):','for i in range(10):'),
230 230 # Space after last continuation prompt has been removed (issue #6674)
231 231 ('...: print i',' print i'),
232 232 ('...:', ''),
233 233 ],
234 234 [('In [2]: a="""','a="""'),
235 235 (' ...: 123"""','123"""'),
236 236 ],
237 237 [('a="""','a="""'),
238 238 (' ...: 123','123'),
239 239 (' ...: 456"""','456"""'),
240 240 ],
241 241 [('a="""','a="""'),
242 242 ('In [1]: 123','123'),
243 243 (' ...: 456"""','456"""'),
244 244 ],
245 245 [('a="""','a="""'),
246 246 ('123','123'),
247 247 (' ...: 456"""',' ...: 456"""'),
248 248 ],
249 249 ],
250 250
251 251 multiline_datastructure_prompt =
252 252 [ [('>>> a = [1,','a = [1,'),
253 253 ('... 2]','2]'),
254 254 ],
255 255 ],
256 256
257 257 multiline_datastructure =
258 258 [ [('b = ("%s"', None),
259 259 ('# comment', None),
260 260 ('%foo )', 'b = ("%s"\n# comment\n%foo )'),
261 261 ],
262 262 ],
263 263
264 264 multiline_string =
265 265 [ [("'''foo?", None),
266 266 ("bar'''", "'''foo?\nbar'''"),
267 267 ],
268 268 ],
269 269
270 270 leading_indent =
271 271 [ [(' print "hi"','print "hi"'),
272 272 ],
273 273 [(' for a in range(5):','for a in range(5):'),
274 274 (' a*2',' a*2'),
275 275 ],
276 276 [(' a="""','a="""'),
277 277 (' 123"""','123"""'),
278 278 ],
279 279 [('a="""','a="""'),
280 280 (' 123"""',' 123"""'),
281 281 ],
282 282 ],
283 283
284 284 cellmagic =
285 285 [ [(u'%%foo a', None),
286 (None, u_fmt("get_ipython().run_cell_magic({u}'foo', {u}'a', {u}'')")),
286 (None, u_fmt("get_ipython().run_cell_magic('foo', 'a', '')")),
287 287 ],
288 288 [(u'%%bar 123', None),
289 289 (u'hello', None),
290 (None , u_fmt("get_ipython().run_cell_magic({u}'bar', {u}'123', {u}'hello')")),
290 (None , u_fmt("get_ipython().run_cell_magic('bar', '123', 'hello')")),
291 291 ],
292 292 [(u'a=5', 'a=5'),
293 293 (u'%%cellmagic', '%%cellmagic'),
294 294 ],
295 295 ],
296 296
297 297 escaped =
298 298 [ [('%abc def \\', None),
299 ('ghi', u_fmt("get_ipython().run_line_magic({u}'abc', {u}'def ghi')")),
299 ('ghi', u_fmt("get_ipython().run_line_magic('abc', 'def ghi')")),
300 300 ],
301 301 [('%abc def \\', None),
302 302 ('ghi\\', None),
303 (None, u_fmt("get_ipython().run_line_magic({u}'abc', {u}'def ghi')")),
303 (None, u_fmt("get_ipython().run_line_magic('abc', 'def ghi')")),
304 304 ],
305 305 ],
306 306
307 307 assign_magic =
308 308 [ [(u'a = %bc de \\', None),
309 (u'fg', u_fmt("a = get_ipython().run_line_magic({u}'bc', {u}'de fg')")),
309 (u'fg', u_fmt("a = get_ipython().run_line_magic('bc', 'de fg')")),
310 310 ],
311 311 [(u'a = %bc de \\', None),
312 312 (u'fg\\', None),
313 (None, u_fmt("a = get_ipython().run_line_magic({u}'bc', {u}'de fg')")),
313 (None, u_fmt("a = get_ipython().run_line_magic('bc', 'de fg')")),
314 314 ],
315 315 ],
316 316
317 317 assign_system =
318 318 [ [(u'a = !bc de \\', None),
319 (u'fg', u_fmt("a = get_ipython().getoutput({u}'bc de fg')")),
319 (u'fg', u_fmt("a = get_ipython().getoutput('bc de fg')")),
320 320 ],
321 321 [(u'a = !bc de \\', None),
322 322 (u'fg\\', None),
323 (None, u_fmt("a = get_ipython().getoutput({u}'bc de fg')")),
323 (None, u_fmt("a = get_ipython().getoutput('bc de fg')")),
324 324 ],
325 325 ],
326 326 )
327 327
328 328
329 329 def test_assign_system():
330 330 tt.check_pairs(transform_and_reset(ipt.assign_from_system), syntax['assign_system'])
331 331
332 332 def test_assign_magic():
333 333 tt.check_pairs(transform_and_reset(ipt.assign_from_magic), syntax['assign_magic'])
334 334
335 335 def test_classic_prompt():
336 336 tt.check_pairs(transform_and_reset(ipt.classic_prompt), syntax['classic_prompt'])
337 337 for example in syntax_ml['classic_prompt']:
338 338 transform_checker(example, ipt.classic_prompt)
339 339 for example in syntax_ml['multiline_datastructure_prompt']:
340 340 transform_checker(example, ipt.classic_prompt)
341 341
342 342 # Check that we don't transform the second line if the first is obviously
343 343 # IPython syntax
344 344 transform_checker([
345 345 (u'%foo', '%foo'),
346 346 (u'>>> bar', '>>> bar'),
347 347 ], ipt.classic_prompt)
348 348
349 349
350 350 def test_ipy_prompt():
351 351 tt.check_pairs(transform_and_reset(ipt.ipy_prompt), syntax['ipy_prompt'])
352 352 for example in syntax_ml['ipy_prompt']:
353 353 transform_checker(example, ipt.ipy_prompt)
354 354
355 355 # Check that we don't transform the second line if we're inside a cell magic
356 356 transform_checker([
357 357 (u'%%foo', '%%foo'),
358 358 (u'In [1]: bar', 'In [1]: bar'),
359 359 ], ipt.ipy_prompt)
360 360
361 361 def test_assemble_logical_lines():
362 362 tests = \
363 363 [ [(u"a = \\", None),
364 364 (u"123", u"a = 123"),
365 365 ],
366 366 [(u"a = \\", None), # Test resetting when within a multi-line string
367 367 (u"12 *\\", None),
368 368 (None, u"a = 12 *"),
369 369 ],
370 370 [(u"# foo\\", u"# foo\\"), # Comments can't be continued like this
371 371 ],
372 372 ]
373 373 for example in tests:
374 374 transform_checker(example, ipt.assemble_logical_lines)
375 375
376 376 def test_assemble_python_lines():
377 377 tests = \
378 378 [ [(u"a = '''", None),
379 379 (u"abc'''", u"a = '''\nabc'''"),
380 380 ],
381 381 [(u"a = '''", None), # Test resetting when within a multi-line string
382 382 (u"def", None),
383 383 (None, u"a = '''\ndef"),
384 384 ],
385 385 [(u"a = [1,", None),
386 386 (u"2]", u"a = [1,\n2]"),
387 387 ],
388 388 [(u"a = [1,", None), # Test resetting when within a multi-line string
389 389 (u"2,", None),
390 390 (None, u"a = [1,\n2,"),
391 391 ],
392 392 [(u"a = '''", None), # Test line continuation within a multi-line string
393 393 (u"abc\\", None),
394 394 (u"def", None),
395 395 (u"'''", u"a = '''\nabc\\\ndef\n'''"),
396 396 ],
397 397 ] + syntax_ml['multiline_datastructure']
398 398 for example in tests:
399 399 transform_checker(example, ipt.assemble_python_lines)
400 400
401 401
402 402 def test_help_end():
403 403 tt.check_pairs(transform_and_reset(ipt.help_end), syntax['end_help'])
404 404
405 405 def test_escaped_noesc():
406 406 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_noesc'])
407 407
408 408
409 409 def test_escaped_shell():
410 410 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_shell'])
411 411
412 412
413 413 def test_escaped_help():
414 414 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_help'])
415 415
416 416
417 417 def test_escaped_magic():
418 418 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_magic'])
419 419
420 420
421 421 def test_escaped_quote():
422 422 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote'])
423 423
424 424
425 425 def test_escaped_quote2():
426 426 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote2'])
427 427
428 428
429 429 def test_escaped_paren():
430 430 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_paren'])
431 431
432 432
433 433 def test_cellmagic():
434 434 for example in syntax_ml['cellmagic']:
435 435 transform_checker(example, ipt.cellmagic)
436 436
437 437 line_example = [(u'%%bar 123', None),
438 438 (u'hello', None),
439 (u'' , u_fmt("get_ipython().run_cell_magic({u}'bar', {u}'123', {u}'hello')")),
439 (u'' , u_fmt("get_ipython().run_cell_magic('bar', '123', 'hello')")),
440 440 ]
441 441 transform_checker(line_example, ipt.cellmagic, end_on_blank_line=True)
442 442
443 443 def test_has_comment():
444 444 tests = [('text', False),
445 445 ('text #comment', True),
446 446 ('text #comment\n', True),
447 447 ('#comment', True),
448 448 ('#comment\n', True),
449 449 ('a = "#string"', False),
450 450 ('a = "#string" # comment', True),
451 451 ('a #comment not "string"', True),
452 452 ]
453 453 tt.check_pairs(ipt.has_comment, tests)
454 454
455 455 @ipt.TokenInputTransformer.wrap
456 456 def decistmt(tokens):
457 457 """Substitute Decimals for floats in a string of statements.
458 458
459 459 Based on an example from the tokenize module docs.
460 460 """
461 461 result = []
462 462 for toknum, tokval, _, _, _ in tokens:
463 463 if toknum == tokenize.NUMBER and '.' in tokval: # replace NUMBER tokens
464 464 for newtok in [
465 465 (tokenize.NAME, 'Decimal'),
466 466 (tokenize.OP, '('),
467 467 (tokenize.STRING, repr(tokval)),
468 468 (tokenize.OP, ')')
469 469 ]:
470 470 yield newtok
471 471 else:
472 472 yield (toknum, tokval)
473 473
474 474
475 475
476 476 def test_token_input_transformer():
477 tests = [(u'1.2', u_fmt(u"Decimal ({u}'1.2')")),
477 tests = [(u'1.2', u_fmt(u"Decimal ('1.2')")),
478 478 (u'"1.2"', u'"1.2"'),
479 479 ]
480 480 tt.check_pairs(transform_and_reset(decistmt), tests)
481 481 ml_tests = \
482 482 [ [(u"a = 1.2; b = '''x", None),
483 (u"y'''", u_fmt(u"a =Decimal ({u}'1.2');b ='''x\ny'''")),
483 (u"y'''", u_fmt(u"a =Decimal ('1.2');b ='''x\ny'''")),
484 484 ],
485 485 [(u"a = [1.2,", None),
486 (u"3]", u_fmt(u"a =[Decimal ({u}'1.2'),\n3 ]")),
486 (u"3]", u_fmt(u"a =[Decimal ('1.2'),\n3 ]")),
487 487 ],
488 488 [(u"a = '''foo", None), # Test resetting when within a multi-line string
489 489 (u"bar", None),
490 490 (None, u"a = '''foo\nbar"),
491 491 ],
492 492 ]
493 493 for example in ml_tests:
494 494 transform_checker(example, decistmt)
@@ -1,1044 +1,1044 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Tests for various magic functions.
3 3
4 4 Needs to be run by nose (to make ipython session available).
5 5 """
6 6
7 7 import io
8 8 import os
9 9 import re
10 10 import sys
11 11 import warnings
12 12 from unittest import TestCase
13 13 from importlib import invalidate_caches
14 14 from io import StringIO
15 15
16 16 import nose.tools as nt
17 17
18 18 import shlex
19 19
20 20 from IPython import get_ipython
21 21 from IPython.core import magic
22 22 from IPython.core.error import UsageError
23 23 from IPython.core.magic import (Magics, magics_class, line_magic,
24 24 cell_magic,
25 25 register_line_magic, register_cell_magic)
26 26 from IPython.core.magics import execution, script, code, logging
27 27 from IPython.testing import decorators as dec
28 28 from IPython.testing import tools as tt
29 29 from IPython.utils import py3compat
30 30 from IPython.utils.io import capture_output
31 31 from IPython.utils.tempdir import TemporaryDirectory
32 32 from IPython.utils.process import find_cmd
33 33
34 34
35 35
36 36 _ip = get_ipython()
37 37
38 38 @magic.magics_class
39 39 class DummyMagics(magic.Magics): pass
40 40
41 41 def test_extract_code_ranges():
42 42 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
43 43 expected = [(0, 1),
44 44 (2, 3),
45 45 (4, 6),
46 46 (6, 9),
47 47 (9, 14),
48 48 (16, None),
49 49 (None, 9),
50 50 (9, None),
51 51 (None, 13),
52 52 (None, None)]
53 53 actual = list(code.extract_code_ranges(instr))
54 54 nt.assert_equal(actual, expected)
55 55
56 56 def test_extract_symbols():
57 57 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
58 58 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
59 59 expected = [([], ['a']),
60 60 (["def b():\n return 42\n"], []),
61 61 (["class A: pass\n"], []),
62 62 (["class A: pass\n", "def b():\n return 42\n"], []),
63 63 (["class A: pass\n"], ['a']),
64 64 ([], ['z'])]
65 65 for symbols, exp in zip(symbols_args, expected):
66 66 nt.assert_equal(code.extract_symbols(source, symbols), exp)
67 67
68 68
69 69 def test_extract_symbols_raises_exception_with_non_python_code():
70 70 source = ("=begin A Ruby program :)=end\n"
71 71 "def hello\n"
72 72 "puts 'Hello world'\n"
73 73 "end")
74 74 with nt.assert_raises(SyntaxError):
75 75 code.extract_symbols(source, "hello")
76 76
77 77 def test_config():
78 78 """ test that config magic does not raise
79 79 can happen if Configurable init is moved too early into
80 80 Magics.__init__ as then a Config object will be registerd as a
81 81 magic.
82 82 """
83 83 ## should not raise.
84 84 _ip.magic('config')
85 85
86 86 def test_config_available_configs():
87 87 """ test that config magic prints available configs in unique and
88 88 sorted order. """
89 89 with capture_output() as captured:
90 90 _ip.magic('config')
91 91
92 92 stdout = captured.stdout
93 93 config_classes = stdout.strip().split('\n')[1:]
94 94 nt.assert_list_equal(config_classes, sorted(set(config_classes)))
95 95
96 96 def test_config_print_class():
97 97 """ test that config with a classname prints the class's options. """
98 98 with capture_output() as captured:
99 99 _ip.magic('config TerminalInteractiveShell')
100 100
101 101 stdout = captured.stdout
102 102 if not re.match("TerminalInteractiveShell.* options", stdout.splitlines()[0]):
103 103 print(stdout)
104 104 raise AssertionError("1st line of stdout not like "
105 105 "'TerminalInteractiveShell.* options'")
106 106
107 107 def test_rehashx():
108 108 # clear up everything
109 109 _ip.alias_manager.clear_aliases()
110 110 del _ip.db['syscmdlist']
111 111
112 112 _ip.magic('rehashx')
113 113 # Practically ALL ipython development systems will have more than 10 aliases
114 114
115 115 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
116 116 for name, cmd in _ip.alias_manager.aliases:
117 117 # we must strip dots from alias names
118 118 nt.assert_not_in('.', name)
119 119
120 120 # rehashx must fill up syscmdlist
121 121 scoms = _ip.db['syscmdlist']
122 122 nt.assert_true(len(scoms) > 10)
123 123
124 124
125 125 def test_magic_parse_options():
126 126 """Test that we don't mangle paths when parsing magic options."""
127 127 ip = get_ipython()
128 128 path = 'c:\\x'
129 129 m = DummyMagics(ip)
130 130 opts = m.parse_options('-f %s' % path,'f:')[0]
131 131 # argv splitting is os-dependent
132 132 if os.name == 'posix':
133 133 expected = 'c:x'
134 134 else:
135 135 expected = path
136 136 nt.assert_equal(opts['f'], expected)
137 137
138 138 def test_magic_parse_long_options():
139 139 """Magic.parse_options can handle --foo=bar long options"""
140 140 ip = get_ipython()
141 141 m = DummyMagics(ip)
142 142 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
143 143 nt.assert_in('foo', opts)
144 144 nt.assert_in('bar', opts)
145 145 nt.assert_equal(opts['bar'], "bubble")
146 146
147 147
148 148 @dec.skip_without('sqlite3')
149 149 def doctest_hist_f():
150 150 """Test %hist -f with temporary filename.
151 151
152 152 In [9]: import tempfile
153 153
154 154 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
155 155
156 156 In [11]: %hist -nl -f $tfile 3
157 157
158 158 In [13]: import os; os.unlink(tfile)
159 159 """
160 160
161 161
162 162 @dec.skip_without('sqlite3')
163 163 def doctest_hist_r():
164 164 """Test %hist -r
165 165
166 166 XXX - This test is not recording the output correctly. For some reason, in
167 167 testing mode the raw history isn't getting populated. No idea why.
168 168 Disabling the output checking for now, though at least we do run it.
169 169
170 170 In [1]: 'hist' in _ip.lsmagic()
171 171 Out[1]: True
172 172
173 173 In [2]: x=1
174 174
175 175 In [3]: %hist -rl 2
176 176 x=1 # random
177 177 %hist -r 2
178 178 """
179 179
180 180
181 181 @dec.skip_without('sqlite3')
182 182 def doctest_hist_op():
183 183 """Test %hist -op
184 184
185 185 In [1]: class b(float):
186 186 ...: pass
187 187 ...:
188 188
189 189 In [2]: class s(object):
190 190 ...: def __str__(self):
191 191 ...: return 's'
192 192 ...:
193 193
194 194 In [3]:
195 195
196 196 In [4]: class r(b):
197 197 ...: def __repr__(self):
198 198 ...: return 'r'
199 199 ...:
200 200
201 201 In [5]: class sr(s,r): pass
202 202 ...:
203 203
204 204 In [6]:
205 205
206 206 In [7]: bb=b()
207 207
208 208 In [8]: ss=s()
209 209
210 210 In [9]: rr=r()
211 211
212 212 In [10]: ssrr=sr()
213 213
214 214 In [11]: 4.5
215 215 Out[11]: 4.5
216 216
217 217 In [12]: str(ss)
218 218 Out[12]: 's'
219 219
220 220 In [13]:
221 221
222 222 In [14]: %hist -op
223 223 >>> class b:
224 224 ... pass
225 225 ...
226 226 >>> class s(b):
227 227 ... def __str__(self):
228 228 ... return 's'
229 229 ...
230 230 >>>
231 231 >>> class r(b):
232 232 ... def __repr__(self):
233 233 ... return 'r'
234 234 ...
235 235 >>> class sr(s,r): pass
236 236 >>>
237 237 >>> bb=b()
238 238 >>> ss=s()
239 239 >>> rr=r()
240 240 >>> ssrr=sr()
241 241 >>> 4.5
242 242 4.5
243 243 >>> str(ss)
244 244 's'
245 245 >>>
246 246 """
247 247
248 248 def test_hist_pof():
249 249 ip = get_ipython()
250 250 ip.run_cell(u"1+2", store_history=True)
251 251 #raise Exception(ip.history_manager.session_number)
252 252 #raise Exception(list(ip.history_manager._get_range_session()))
253 253 with TemporaryDirectory() as td:
254 254 tf = os.path.join(td, 'hist.py')
255 255 ip.run_line_magic('history', '-pof %s' % tf)
256 256 assert os.path.isfile(tf)
257 257
258 258
259 259 @dec.skip_without('sqlite3')
260 260 def test_macro():
261 261 ip = get_ipython()
262 262 ip.history_manager.reset() # Clear any existing history.
263 263 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
264 264 for i, cmd in enumerate(cmds, start=1):
265 265 ip.history_manager.store_inputs(i, cmd)
266 266 ip.magic("macro test 1-3")
267 267 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
268 268
269 269 # List macros
270 270 nt.assert_in("test", ip.magic("macro"))
271 271
272 272
273 273 @dec.skip_without('sqlite3')
274 274 def test_macro_run():
275 275 """Test that we can run a multi-line macro successfully."""
276 276 ip = get_ipython()
277 277 ip.history_manager.reset()
278 278 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
279 279 "%macro test 2-3"]
280 280 for cmd in cmds:
281 281 ip.run_cell(cmd, store_history=True)
282 282 nt.assert_equal(ip.user_ns["test"].value,
283 283 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
284 284 with tt.AssertPrints("12"):
285 285 ip.run_cell("test")
286 286 with tt.AssertPrints("13"):
287 287 ip.run_cell("test")
288 288
289 289
290 290 def test_magic_magic():
291 291 """Test %magic"""
292 292 ip = get_ipython()
293 293 with capture_output() as captured:
294 294 ip.magic("magic")
295 295
296 296 stdout = captured.stdout
297 297 nt.assert_in('%magic', stdout)
298 298 nt.assert_in('IPython', stdout)
299 299 nt.assert_in('Available', stdout)
300 300
301 301
302 302 @dec.skipif_not_numpy
303 303 def test_numpy_reset_array_undec():
304 304 "Test '%reset array' functionality"
305 305 _ip.ex('import numpy as np')
306 306 _ip.ex('a = np.empty(2)')
307 307 nt.assert_in('a', _ip.user_ns)
308 308 _ip.magic('reset -f array')
309 309 nt.assert_not_in('a', _ip.user_ns)
310 310
311 311 def test_reset_out():
312 312 "Test '%reset out' magic"
313 313 _ip.run_cell("parrot = 'dead'", store_history=True)
314 314 # test '%reset -f out', make an Out prompt
315 315 _ip.run_cell("parrot", store_history=True)
316 316 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
317 317 _ip.magic('reset -f out')
318 318 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
319 319 nt.assert_equal(len(_ip.user_ns['Out']), 0)
320 320
321 321 def test_reset_in():
322 322 "Test '%reset in' magic"
323 323 # test '%reset -f in'
324 324 _ip.run_cell("parrot", store_history=True)
325 325 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
326 326 _ip.magic('%reset -f in')
327 327 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
328 328 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
329 329
330 330 def test_reset_dhist():
331 331 "Test '%reset dhist' magic"
332 332 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
333 333 _ip.magic('cd ' + os.path.dirname(nt.__file__))
334 334 _ip.magic('cd -')
335 335 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
336 336 _ip.magic('reset -f dhist')
337 337 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
338 338 _ip.run_cell("_dh = [d for d in tmp]") #restore
339 339
340 340 def test_reset_in_length():
341 341 "Test that '%reset in' preserves In[] length"
342 342 _ip.run_cell("print 'foo'")
343 343 _ip.run_cell("reset -f in")
344 344 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
345 345
346 346 def test_tb_syntaxerror():
347 347 """test %tb after a SyntaxError"""
348 348 ip = get_ipython()
349 349 ip.run_cell("for")
350 350
351 351 # trap and validate stdout
352 352 save_stdout = sys.stdout
353 353 try:
354 354 sys.stdout = StringIO()
355 355 ip.run_cell("%tb")
356 356 out = sys.stdout.getvalue()
357 357 finally:
358 358 sys.stdout = save_stdout
359 359 # trim output, and only check the last line
360 360 last_line = out.rstrip().splitlines()[-1].strip()
361 361 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
362 362
363 363
364 364 def test_time():
365 365 ip = get_ipython()
366 366
367 367 with tt.AssertPrints("Wall time: "):
368 368 ip.run_cell("%time None")
369 369
370 370 ip.run_cell("def f(kmjy):\n"
371 371 " %time print (2*kmjy)")
372 372
373 373 with tt.AssertPrints("Wall time: "):
374 374 with tt.AssertPrints("hihi", suppress=False):
375 375 ip.run_cell("f('hi')")
376 376
377 377
378 378 @dec.skip_win32
379 379 def test_time2():
380 380 ip = get_ipython()
381 381
382 382 with tt.AssertPrints("CPU times: user "):
383 383 ip.run_cell("%time None")
384 384
385 385 def test_time3():
386 386 """Erroneous magic function calls, issue gh-3334"""
387 387 ip = get_ipython()
388 388 ip.user_ns.pop('run', None)
389 389
390 390 with tt.AssertNotPrints("not found", channel='stderr'):
391 391 ip.run_cell("%%time\n"
392 392 "run = 0\n"
393 393 "run += 1")
394 394
395 395 def test_doctest_mode():
396 396 "Toggle doctest_mode twice, it should be a no-op and run without error"
397 397 _ip.magic('doctest_mode')
398 398 _ip.magic('doctest_mode')
399 399
400 400
401 401 def test_parse_options():
402 402 """Tests for basic options parsing in magics."""
403 403 # These are only the most minimal of tests, more should be added later. At
404 404 # the very least we check that basic text/unicode calls work OK.
405 405 m = DummyMagics(_ip)
406 406 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
407 407 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
408 408
409 409
410 410 def test_dirops():
411 411 """Test various directory handling operations."""
412 412 # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
413 413 curpath = os.getcwd
414 414 startdir = os.getcwd()
415 415 ipdir = os.path.realpath(_ip.ipython_dir)
416 416 try:
417 417 _ip.magic('cd "%s"' % ipdir)
418 418 nt.assert_equal(curpath(), ipdir)
419 419 _ip.magic('cd -')
420 420 nt.assert_equal(curpath(), startdir)
421 421 _ip.magic('pushd "%s"' % ipdir)
422 422 nt.assert_equal(curpath(), ipdir)
423 423 _ip.magic('popd')
424 424 nt.assert_equal(curpath(), startdir)
425 425 finally:
426 426 os.chdir(startdir)
427 427
428 428
429 429 def test_xmode():
430 430 # Calling xmode three times should be a no-op
431 431 xmode = _ip.InteractiveTB.mode
432 432 for i in range(3):
433 433 _ip.magic("xmode")
434 434 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
435 435
436 436 def test_reset_hard():
437 437 monitor = []
438 438 class A(object):
439 439 def __del__(self):
440 440 monitor.append(1)
441 441 def __repr__(self):
442 442 return "<A instance>"
443 443
444 444 _ip.user_ns["a"] = A()
445 445 _ip.run_cell("a")
446 446
447 447 nt.assert_equal(monitor, [])
448 448 _ip.magic("reset -f")
449 449 nt.assert_equal(monitor, [1])
450 450
451 451 class TestXdel(tt.TempFileMixin):
452 452 def test_xdel(self):
453 453 """Test that references from %run are cleared by xdel."""
454 454 src = ("class A(object):\n"
455 455 " monitor = []\n"
456 456 " def __del__(self):\n"
457 457 " self.monitor.append(1)\n"
458 458 "a = A()\n")
459 459 self.mktmp(src)
460 460 # %run creates some hidden references...
461 461 _ip.magic("run %s" % self.fname)
462 462 # ... as does the displayhook.
463 463 _ip.run_cell("a")
464 464
465 465 monitor = _ip.user_ns["A"].monitor
466 466 nt.assert_equal(monitor, [])
467 467
468 468 _ip.magic("xdel a")
469 469
470 470 # Check that a's __del__ method has been called.
471 471 nt.assert_equal(monitor, [1])
472 472
473 473 def doctest_who():
474 474 """doctest for %who
475 475
476 476 In [1]: %reset -f
477 477
478 478 In [2]: alpha = 123
479 479
480 480 In [3]: beta = 'beta'
481 481
482 482 In [4]: %who int
483 483 alpha
484 484
485 485 In [5]: %who str
486 486 beta
487 487
488 488 In [6]: %whos
489 489 Variable Type Data/Info
490 490 ----------------------------
491 491 alpha int 123
492 492 beta str beta
493 493
494 494 In [7]: %who_ls
495 495 Out[7]: ['alpha', 'beta']
496 496 """
497 497
498 498 def test_whos():
499 499 """Check that whos is protected against objects where repr() fails."""
500 500 class A(object):
501 501 def __repr__(self):
502 502 raise Exception()
503 503 _ip.user_ns['a'] = A()
504 504 _ip.magic("whos")
505 505
506 506 @py3compat.u_format
507 507 def doctest_precision():
508 508 """doctest for %precision
509 509
510 510 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
511 511
512 512 In [2]: %precision 5
513 Out[2]: {u}'%.5f'
513 Out[2]: '%.5f'
514 514
515 515 In [3]: f.float_format
516 Out[3]: {u}'%.5f'
516 Out[3]: '%.5f'
517 517
518 518 In [4]: %precision %e
519 Out[4]: {u}'%e'
519 Out[4]: '%e'
520 520
521 521 In [5]: f(3.1415927)
522 Out[5]: {u}'3.141593e+00'
522 Out[5]: '3.141593e+00'
523 523 """
524 524
525 525 def test_psearch():
526 526 with tt.AssertPrints("dict.fromkeys"):
527 527 _ip.run_cell("dict.fr*?")
528 528
529 529 def test_timeit_shlex():
530 530 """test shlex issues with timeit (#1109)"""
531 531 _ip.ex("def f(*a,**kw): pass")
532 532 _ip.magic('timeit -n1 "this is a bug".count(" ")')
533 533 _ip.magic('timeit -r1 -n1 f(" ", 1)')
534 534 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
535 535 _ip.magic('timeit -r1 -n1 ("a " + "b")')
536 536 _ip.magic('timeit -r1 -n1 f("a " + "b")')
537 537 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
538 538
539 539
540 540 def test_timeit_arguments():
541 541 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
542 542 _ip.magic("timeit ('#')")
543 543
544 544
545 545 def test_timeit_special_syntax():
546 546 "Test %%timeit with IPython special syntax"
547 547 @register_line_magic
548 548 def lmagic(line):
549 549 ip = get_ipython()
550 550 ip.user_ns['lmagic_out'] = line
551 551
552 552 # line mode test
553 553 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
554 554 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
555 555 # cell mode test
556 556 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
557 557 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
558 558
559 559 def test_timeit_return():
560 560 """
561 561 test wether timeit -o return object
562 562 """
563 563
564 564 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
565 565 assert(res is not None)
566 566
567 567 def test_timeit_quiet():
568 568 """
569 569 test quiet option of timeit magic
570 570 """
571 571 with tt.AssertNotPrints("loops"):
572 572 _ip.run_cell("%timeit -n1 -r1 -q 1")
573 573
574 574 def test_timeit_return_quiet():
575 575 with tt.AssertNotPrints("loops"):
576 576 res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1')
577 577 assert (res is not None)
578 578
579 579 def test_timeit_invalid_return():
580 580 with nt.assert_raises_regexp(SyntaxError, "outside function"):
581 581 _ip.run_line_magic('timeit', 'return')
582 582
583 583 @dec.skipif(execution.profile is None)
584 584 def test_prun_special_syntax():
585 585 "Test %%prun with IPython special syntax"
586 586 @register_line_magic
587 587 def lmagic(line):
588 588 ip = get_ipython()
589 589 ip.user_ns['lmagic_out'] = line
590 590
591 591 # line mode test
592 592 _ip.run_line_magic('prun', '-q %lmagic my line')
593 593 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
594 594 # cell mode test
595 595 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
596 596 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
597 597
598 598 @dec.skipif(execution.profile is None)
599 599 def test_prun_quotes():
600 600 "Test that prun does not clobber string escapes (GH #1302)"
601 601 _ip.magic(r"prun -q x = '\t'")
602 602 nt.assert_equal(_ip.user_ns['x'], '\t')
603 603
604 604 def test_extension():
605 605 # Debugging information for failures of this test
606 606 print('sys.path:')
607 607 for p in sys.path:
608 608 print(' ', p)
609 609 print('CWD', os.getcwd())
610 610
611 611 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
612 612 daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
613 613 sys.path.insert(0, daft_path)
614 614 try:
615 615 _ip.user_ns.pop('arq', None)
616 616 invalidate_caches() # Clear import caches
617 617 _ip.magic("load_ext daft_extension")
618 618 nt.assert_equal(_ip.user_ns['arq'], 185)
619 619 _ip.magic("unload_ext daft_extension")
620 620 assert 'arq' not in _ip.user_ns
621 621 finally:
622 622 sys.path.remove(daft_path)
623 623
624 624
625 625 def test_notebook_export_json():
626 626 _ip = get_ipython()
627 627 _ip.history_manager.reset() # Clear any existing history.
628 628 cmds = [u"a=1", u"def b():\n return a**2", u"print('noël, été', b())"]
629 629 for i, cmd in enumerate(cmds, start=1):
630 630 _ip.history_manager.store_inputs(i, cmd)
631 631 with TemporaryDirectory() as td:
632 632 outfile = os.path.join(td, "nb.ipynb")
633 633 _ip.magic("notebook -e %s" % outfile)
634 634
635 635
636 636 class TestEnv(TestCase):
637 637
638 638 def test_env(self):
639 639 env = _ip.magic("env")
640 640 self.assertTrue(isinstance(env, dict))
641 641
642 642 def test_env_get_set_simple(self):
643 643 env = _ip.magic("env var val1")
644 644 self.assertEqual(env, None)
645 645 self.assertEqual(os.environ['var'], 'val1')
646 646 self.assertEqual(_ip.magic("env var"), 'val1')
647 647 env = _ip.magic("env var=val2")
648 648 self.assertEqual(env, None)
649 649 self.assertEqual(os.environ['var'], 'val2')
650 650
651 651 def test_env_get_set_complex(self):
652 652 env = _ip.magic("env var 'val1 '' 'val2")
653 653 self.assertEqual(env, None)
654 654 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
655 655 self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2")
656 656 env = _ip.magic('env var=val2 val3="val4')
657 657 self.assertEqual(env, None)
658 658 self.assertEqual(os.environ['var'], 'val2 val3="val4')
659 659
660 660 def test_env_set_bad_input(self):
661 661 self.assertRaises(UsageError, lambda: _ip.magic("set_env var"))
662 662
663 663 def test_env_set_whitespace(self):
664 664 self.assertRaises(UsageError, lambda: _ip.magic("env var A=B"))
665 665
666 666
667 667 class CellMagicTestCase(TestCase):
668 668
669 669 def check_ident(self, magic):
670 670 # Manually called, we get the result
671 671 out = _ip.run_cell_magic(magic, 'a', 'b')
672 672 nt.assert_equal(out, ('a','b'))
673 673 # Via run_cell, it goes into the user's namespace via displayhook
674 674 _ip.run_cell('%%' + magic +' c\nd')
675 675 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
676 676
677 677 def test_cell_magic_func_deco(self):
678 678 "Cell magic using simple decorator"
679 679 @register_cell_magic
680 680 def cellm(line, cell):
681 681 return line, cell
682 682
683 683 self.check_ident('cellm')
684 684
685 685 def test_cell_magic_reg(self):
686 686 "Cell magic manually registered"
687 687 def cellm(line, cell):
688 688 return line, cell
689 689
690 690 _ip.register_magic_function(cellm, 'cell', 'cellm2')
691 691 self.check_ident('cellm2')
692 692
693 693 def test_cell_magic_class(self):
694 694 "Cell magics declared via a class"
695 695 @magics_class
696 696 class MyMagics(Magics):
697 697
698 698 @cell_magic
699 699 def cellm3(self, line, cell):
700 700 return line, cell
701 701
702 702 _ip.register_magics(MyMagics)
703 703 self.check_ident('cellm3')
704 704
705 705 def test_cell_magic_class2(self):
706 706 "Cell magics declared via a class, #2"
707 707 @magics_class
708 708 class MyMagics2(Magics):
709 709
710 710 @cell_magic('cellm4')
711 711 def cellm33(self, line, cell):
712 712 return line, cell
713 713
714 714 _ip.register_magics(MyMagics2)
715 715 self.check_ident('cellm4')
716 716 # Check that nothing is registered as 'cellm33'
717 717 c33 = _ip.find_cell_magic('cellm33')
718 718 nt.assert_equal(c33, None)
719 719
720 720 def test_file():
721 721 """Basic %%file"""
722 722 ip = get_ipython()
723 723 with TemporaryDirectory() as td:
724 724 fname = os.path.join(td, 'file1')
725 725 ip.run_cell_magic("file", fname, u'\n'.join([
726 726 'line1',
727 727 'line2',
728 728 ]))
729 729 with open(fname) as f:
730 730 s = f.read()
731 731 nt.assert_in('line1\n', s)
732 732 nt.assert_in('line2', s)
733 733
734 734 def test_file_var_expand():
735 735 """%%file $filename"""
736 736 ip = get_ipython()
737 737 with TemporaryDirectory() as td:
738 738 fname = os.path.join(td, 'file1')
739 739 ip.user_ns['filename'] = fname
740 740 ip.run_cell_magic("file", '$filename', u'\n'.join([
741 741 'line1',
742 742 'line2',
743 743 ]))
744 744 with open(fname) as f:
745 745 s = f.read()
746 746 nt.assert_in('line1\n', s)
747 747 nt.assert_in('line2', s)
748 748
749 749 def test_file_unicode():
750 750 """%%file with unicode cell"""
751 751 ip = get_ipython()
752 752 with TemporaryDirectory() as td:
753 753 fname = os.path.join(td, 'file1')
754 754 ip.run_cell_magic("file", fname, u'\n'.join([
755 755 u'liné1',
756 756 u'liné2',
757 757 ]))
758 758 with io.open(fname, encoding='utf-8') as f:
759 759 s = f.read()
760 760 nt.assert_in(u'liné1\n', s)
761 761 nt.assert_in(u'liné2', s)
762 762
763 763 def test_file_amend():
764 764 """%%file -a amends files"""
765 765 ip = get_ipython()
766 766 with TemporaryDirectory() as td:
767 767 fname = os.path.join(td, 'file2')
768 768 ip.run_cell_magic("file", fname, u'\n'.join([
769 769 'line1',
770 770 'line2',
771 771 ]))
772 772 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
773 773 'line3',
774 774 'line4',
775 775 ]))
776 776 with open(fname) as f:
777 777 s = f.read()
778 778 nt.assert_in('line1\n', s)
779 779 nt.assert_in('line3\n', s)
780 780
781 781
782 782 def test_script_config():
783 783 ip = get_ipython()
784 784 ip.config.ScriptMagics.script_magics = ['whoda']
785 785 sm = script.ScriptMagics(shell=ip)
786 786 nt.assert_in('whoda', sm.magics['cell'])
787 787
788 788 @dec.skip_win32
789 789 def test_script_out():
790 790 ip = get_ipython()
791 791 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
792 792 nt.assert_equal(ip.user_ns['output'], 'hi\n')
793 793
794 794 @dec.skip_win32
795 795 def test_script_err():
796 796 ip = get_ipython()
797 797 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
798 798 nt.assert_equal(ip.user_ns['error'], 'hello\n')
799 799
800 800 @dec.skip_win32
801 801 def test_script_out_err():
802 802 ip = get_ipython()
803 803 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
804 804 nt.assert_equal(ip.user_ns['output'], 'hi\n')
805 805 nt.assert_equal(ip.user_ns['error'], 'hello\n')
806 806
807 807 @dec.skip_win32
808 808 def test_script_bg_out():
809 809 ip = get_ipython()
810 810 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
811 811 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
812 812
813 813 @dec.skip_win32
814 814 def test_script_bg_err():
815 815 ip = get_ipython()
816 816 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
817 817 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
818 818
819 819 @dec.skip_win32
820 820 def test_script_bg_out_err():
821 821 ip = get_ipython()
822 822 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
823 823 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
824 824 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
825 825
826 826 def test_script_defaults():
827 827 ip = get_ipython()
828 828 for cmd in ['sh', 'bash', 'perl', 'ruby']:
829 829 try:
830 830 find_cmd(cmd)
831 831 except Exception:
832 832 pass
833 833 else:
834 834 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
835 835
836 836
837 837 @magics_class
838 838 class FooFoo(Magics):
839 839 """class with both %foo and %%foo magics"""
840 840 @line_magic('foo')
841 841 def line_foo(self, line):
842 842 "I am line foo"
843 843 pass
844 844
845 845 @cell_magic("foo")
846 846 def cell_foo(self, line, cell):
847 847 "I am cell foo, not line foo"
848 848 pass
849 849
850 850 def test_line_cell_info():
851 851 """%%foo and %foo magics are distinguishable to inspect"""
852 852 ip = get_ipython()
853 853 ip.magics_manager.register(FooFoo)
854 854 oinfo = ip.object_inspect('foo')
855 855 nt.assert_true(oinfo['found'])
856 856 nt.assert_true(oinfo['ismagic'])
857 857
858 858 oinfo = ip.object_inspect('%%foo')
859 859 nt.assert_true(oinfo['found'])
860 860 nt.assert_true(oinfo['ismagic'])
861 861 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
862 862
863 863 oinfo = ip.object_inspect('%foo')
864 864 nt.assert_true(oinfo['found'])
865 865 nt.assert_true(oinfo['ismagic'])
866 866 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
867 867
868 868 def test_multiple_magics():
869 869 ip = get_ipython()
870 870 foo1 = FooFoo(ip)
871 871 foo2 = FooFoo(ip)
872 872 mm = ip.magics_manager
873 873 mm.register(foo1)
874 874 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
875 875 mm.register(foo2)
876 876 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
877 877
878 878 def test_alias_magic():
879 879 """Test %alias_magic."""
880 880 ip = get_ipython()
881 881 mm = ip.magics_manager
882 882
883 883 # Basic operation: both cell and line magics are created, if possible.
884 884 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
885 885 nt.assert_in('timeit_alias', mm.magics['line'])
886 886 nt.assert_in('timeit_alias', mm.magics['cell'])
887 887
888 888 # --cell is specified, line magic not created.
889 889 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
890 890 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
891 891 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
892 892
893 893 # Test that line alias is created successfully.
894 894 ip.run_line_magic('alias_magic', '--line env_alias env')
895 895 nt.assert_equal(ip.run_line_magic('env', ''),
896 896 ip.run_line_magic('env_alias', ''))
897 897
898 898 # Test that line alias with parameters passed in is created successfully.
899 899 ip.run_line_magic('alias_magic', '--line history_alias history --params ' + shlex.quote('3'))
900 900 nt.assert_in('history_alias', mm.magics['line'])
901 901
902 902
903 903 def test_save():
904 904 """Test %save."""
905 905 ip = get_ipython()
906 906 ip.history_manager.reset() # Clear any existing history.
907 907 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
908 908 for i, cmd in enumerate(cmds, start=1):
909 909 ip.history_manager.store_inputs(i, cmd)
910 910 with TemporaryDirectory() as tmpdir:
911 911 file = os.path.join(tmpdir, "testsave.py")
912 912 ip.run_line_magic("save", "%s 1-10" % file)
913 913 with open(file) as f:
914 914 content = f.read()
915 915 nt.assert_equal(content.count(cmds[0]), 1)
916 916 nt.assert_in('coding: utf-8', content)
917 917 ip.run_line_magic("save", "-a %s 1-10" % file)
918 918 with open(file) as f:
919 919 content = f.read()
920 920 nt.assert_equal(content.count(cmds[0]), 2)
921 921 nt.assert_in('coding: utf-8', content)
922 922
923 923
924 924 def test_store():
925 925 """Test %store."""
926 926 ip = get_ipython()
927 927 ip.run_line_magic('load_ext', 'storemagic')
928 928
929 929 # make sure the storage is empty
930 930 ip.run_line_magic('store', '-z')
931 931 ip.user_ns['var'] = 42
932 932 ip.run_line_magic('store', 'var')
933 933 ip.user_ns['var'] = 39
934 934 ip.run_line_magic('store', '-r')
935 935 nt.assert_equal(ip.user_ns['var'], 42)
936 936
937 937 ip.run_line_magic('store', '-d var')
938 938 ip.user_ns['var'] = 39
939 939 ip.run_line_magic('store' , '-r')
940 940 nt.assert_equal(ip.user_ns['var'], 39)
941 941
942 942
943 943 def _run_edit_test(arg_s, exp_filename=None,
944 944 exp_lineno=-1,
945 945 exp_contents=None,
946 946 exp_is_temp=None):
947 947 ip = get_ipython()
948 948 M = code.CodeMagics(ip)
949 949 last_call = ['','']
950 950 opts,args = M.parse_options(arg_s,'prxn:')
951 951 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
952 952
953 953 if exp_filename is not None:
954 954 nt.assert_equal(exp_filename, filename)
955 955 if exp_contents is not None:
956 956 with io.open(filename, 'r', encoding='utf-8') as f:
957 957 contents = f.read()
958 958 nt.assert_equal(exp_contents, contents)
959 959 if exp_lineno != -1:
960 960 nt.assert_equal(exp_lineno, lineno)
961 961 if exp_is_temp is not None:
962 962 nt.assert_equal(exp_is_temp, is_temp)
963 963
964 964
965 965 def test_edit_interactive():
966 966 """%edit on interactively defined objects"""
967 967 ip = get_ipython()
968 968 n = ip.execution_count
969 969 ip.run_cell(u"def foo(): return 1", store_history=True)
970 970
971 971 try:
972 972 _run_edit_test("foo")
973 973 except code.InteractivelyDefined as e:
974 974 nt.assert_equal(e.index, n)
975 975 else:
976 976 raise AssertionError("Should have raised InteractivelyDefined")
977 977
978 978
979 979 def test_edit_cell():
980 980 """%edit [cell id]"""
981 981 ip = get_ipython()
982 982
983 983 ip.run_cell(u"def foo(): return 1", store_history=True)
984 984
985 985 # test
986 986 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
987 987
988 988 def test_bookmark():
989 989 ip = get_ipython()
990 990 ip.run_line_magic('bookmark', 'bmname')
991 991 with tt.AssertPrints('bmname'):
992 992 ip.run_line_magic('bookmark', '-l')
993 993 ip.run_line_magic('bookmark', '-d bmname')
994 994
995 995 def test_ls_magic():
996 996 ip = get_ipython()
997 997 json_formatter = ip.display_formatter.formatters['application/json']
998 998 json_formatter.enabled = True
999 999 lsmagic = ip.magic('lsmagic')
1000 1000 with warnings.catch_warnings(record=True) as w:
1001 1001 j = json_formatter(lsmagic)
1002 1002 nt.assert_equal(sorted(j), ['cell', 'line'])
1003 1003 nt.assert_equal(w, []) # no warnings
1004 1004
1005 1005 def test_strip_initial_indent():
1006 1006 def sii(s):
1007 1007 lines = s.splitlines()
1008 1008 return '\n'.join(code.strip_initial_indent(lines))
1009 1009
1010 1010 nt.assert_equal(sii(" a = 1\nb = 2"), "a = 1\nb = 2")
1011 1011 nt.assert_equal(sii(" a\n b\nc"), "a\n b\nc")
1012 1012 nt.assert_equal(sii("a\n b"), "a\n b")
1013 1013
1014 1014 def test_logging_magic_quiet_from_arg():
1015 1015 _ip.config.LoggingMagics.quiet = False
1016 1016 lm = logging.LoggingMagics(shell=_ip)
1017 1017 with TemporaryDirectory() as td:
1018 1018 try:
1019 1019 with tt.AssertNotPrints(re.compile("Activating.*")):
1020 1020 lm.logstart('-q {}'.format(
1021 1021 os.path.join(td, "quiet_from_arg.log")))
1022 1022 finally:
1023 1023 _ip.logger.logstop()
1024 1024
1025 1025 def test_logging_magic_quiet_from_config():
1026 1026 _ip.config.LoggingMagics.quiet = True
1027 1027 lm = logging.LoggingMagics(shell=_ip)
1028 1028 with TemporaryDirectory() as td:
1029 1029 try:
1030 1030 with tt.AssertNotPrints(re.compile("Activating.*")):
1031 1031 lm.logstart(os.path.join(td, "quiet_from_config.log"))
1032 1032 finally:
1033 1033 _ip.logger.logstop()
1034 1034
1035 1035 def test_logging_magic_not_quiet():
1036 1036 _ip.config.LoggingMagics.quiet = False
1037 1037 lm = logging.LoggingMagics(shell=_ip)
1038 1038 with TemporaryDirectory() as td:
1039 1039 try:
1040 1040 with tt.AssertPrints(re.compile("Activating.*")):
1041 1041 lm.logstart(os.path.join(td, "not_quiet.log"))
1042 1042 finally:
1043 1043 _ip.logger.logstop()
1044 1044
General Comments 0
You need to be logged in to leave comments. Login now