##// END OF EJS Templates
Merge pull request #10638 from adityausathe/master...
Thomas Kluyver -
r23765:c05f400f merge
parent child Browse files
Show More
@@ -1,525 +1,534 b''
1 1 """Input transformer classes to support IPython special syntax.
2 2
3 3 This includes the machinery to recognise and transform ``%magic`` commands,
4 4 ``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
5 5 """
6 6 import abc
7 7 import functools
8 8 import re
9 9 from io import StringIO
10 10
11 11 from IPython.core.splitinput import LineInfo
12 12 from IPython.utils import tokenize2
13 13 from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
14 14
15 15 #-----------------------------------------------------------------------------
16 16 # Globals
17 17 #-----------------------------------------------------------------------------
18 18
19 19 # The escape sequences that define the syntax transformations IPython will
20 20 # apply to user input. These can NOT be just changed here: many regular
21 21 # expressions and other parts of the code may use their hardcoded values, and
22 22 # for all intents and purposes they constitute the 'IPython syntax', so they
23 23 # should be considered fixed.
24 24
25 25 ESC_SHELL = '!' # Send line to underlying system shell
26 26 ESC_SH_CAP = '!!' # Send line to system shell and capture output
27 27 ESC_HELP = '?' # Find information about object
28 28 ESC_HELP2 = '??' # Find extra-detailed information about object
29 29 ESC_MAGIC = '%' # Call magic function
30 30 ESC_MAGIC2 = '%%' # Call cell-magic function
31 31 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
32 32 ESC_QUOTE2 = ';' # Quote all args as a single string, call
33 33 ESC_PAREN = '/' # Call first argument with rest of line as arguments
34 34
35 35 ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\
36 36 ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\
37 37 ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
38 38
39 39
40 40 class InputTransformer(metaclass=abc.ABCMeta):
41 41 """Abstract base class for line-based input transformers."""
42 42
43 43 @abc.abstractmethod
44 44 def push(self, line):
45 45 """Send a line of input to the transformer, returning the transformed
46 46 input or None if the transformer is waiting for more input.
47 47
48 48 Must be overridden by subclasses.
49 49
50 50 Implementations may raise ``SyntaxError`` if the input is invalid. No
51 51 other exceptions may be raised.
52 52 """
53 53 pass
54 54
55 55 @abc.abstractmethod
56 56 def reset(self):
57 57 """Return, transformed any lines that the transformer has accumulated,
58 58 and reset its internal state.
59 59
60 60 Must be overridden by subclasses.
61 61 """
62 62 pass
63 63
64 64 @classmethod
65 65 def wrap(cls, func):
66 66 """Can be used by subclasses as a decorator, to return a factory that
67 67 will allow instantiation with the decorated object.
68 68 """
69 69 @functools.wraps(func)
70 70 def transformer_factory(**kwargs):
71 71 return cls(func, **kwargs)
72 72
73 73 return transformer_factory
74 74
75 75 class StatelessInputTransformer(InputTransformer):
76 76 """Wrapper for a stateless input transformer implemented as a function."""
77 77 def __init__(self, func):
78 78 self.func = func
79 79
80 80 def __repr__(self):
81 81 return "StatelessInputTransformer(func={0!r})".format(self.func)
82 82
83 83 def push(self, line):
84 84 """Send a line of input to the transformer, returning the
85 85 transformed input."""
86 86 return self.func(line)
87 87
88 88 def reset(self):
89 89 """No-op - exists for compatibility."""
90 90 pass
91 91
92 92 class CoroutineInputTransformer(InputTransformer):
93 93 """Wrapper for an input transformer implemented as a coroutine."""
94 94 def __init__(self, coro, **kwargs):
95 95 # Prime it
96 96 self.coro = coro(**kwargs)
97 97 next(self.coro)
98 98
99 99 def __repr__(self):
100 100 return "CoroutineInputTransformer(coro={0!r})".format(self.coro)
101 101
102 102 def push(self, line):
103 103 """Send a line of input to the transformer, returning the
104 104 transformed input or None if the transformer is waiting for more
105 105 input.
106 106 """
107 107 return self.coro.send(line)
108 108
109 109 def reset(self):
110 110 """Return, transformed any lines that the transformer has
111 111 accumulated, and reset its internal state.
112 112 """
113 113 return self.coro.send(None)
114 114
115 115 class TokenInputTransformer(InputTransformer):
116 116 """Wrapper for a token-based input transformer.
117 117
118 118 func should accept a list of tokens (5-tuples, see tokenize docs), and
119 119 return an iterable which can be passed to tokenize.untokenize().
120 120 """
121 121 def __init__(self, func):
122 122 self.func = func
123 123 self.buf = []
124 124 self.reset_tokenizer()
125 125
126 126 def reset_tokenizer(self):
127 127 it = iter(self.buf)
128 128 self.tokenizer = generate_tokens(it.__next__)
129 129
130 130 def push(self, line):
131 131 self.buf.append(line + '\n')
132 132 if all(l.isspace() for l in self.buf):
133 133 return self.reset()
134 134
135 135 tokens = []
136 136 stop_at_NL = False
137 137 try:
138 138 for intok in self.tokenizer:
139 139 tokens.append(intok)
140 140 t = intok[0]
141 141 if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL):
142 142 # Stop before we try to pull a line we don't have yet
143 143 break
144 144 elif t == tokenize2.ERRORTOKEN:
145 145 stop_at_NL = True
146 146 except TokenError:
147 147 # Multi-line statement - stop and try again with the next line
148 148 self.reset_tokenizer()
149 149 return None
150 150
151 151 return self.output(tokens)
152 152
153 153 def output(self, tokens):
154 154 self.buf.clear()
155 155 self.reset_tokenizer()
156 156 return untokenize(self.func(tokens)).rstrip('\n')
157 157
158 158 def reset(self):
159 159 l = ''.join(self.buf)
160 160 self.buf.clear()
161 161 self.reset_tokenizer()
162 162 if l:
163 163 return l.rstrip('\n')
164 164
165 165 class assemble_python_lines(TokenInputTransformer):
166 166 def __init__(self):
167 167 super(assemble_python_lines, self).__init__(None)
168 168
169 169 def output(self, tokens):
170 170 return self.reset()
171 171
172 172 @CoroutineInputTransformer.wrap
173 173 def assemble_logical_lines():
174 174 """Join lines following explicit line continuations (\)"""
175 175 line = ''
176 176 while True:
177 177 line = (yield line)
178 178 if not line or line.isspace():
179 179 continue
180 180
181 181 parts = []
182 182 while line is not None:
183 183 if line.endswith('\\') and (not has_comment(line)):
184 184 parts.append(line[:-1])
185 185 line = (yield None) # Get another line
186 186 else:
187 187 parts.append(line)
188 188 break
189 189
190 190 # Output
191 191 line = ''.join(parts)
192 192
193 193 # Utilities
194 194 def _make_help_call(target, esc, lspace, next_input=None):
195 195 """Prepares a pinfo(2)/psearch call from a target name and the escape
196 196 (i.e. ? or ??)"""
197 197 method = 'pinfo2' if esc == '??' \
198 198 else 'psearch' if '*' in target \
199 199 else 'pinfo'
200 200 arg = " ".join([method, target])
201 #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
202 t_magic_name, _, t_magic_arg_s = arg.partition(' ')
203 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
201 204 if next_input is None:
202 return '%sget_ipython().magic(%r)' % (lspace, arg)
205 return '%sget_ipython().run_line_magic(%r, %r)' % (lspace, t_magic_name, t_magic_arg_s)
203 206 else:
204 return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \
205 (lspace, next_input, arg)
207 return '%sget_ipython().set_next_input(%r);get_ipython().run_line_magic(%r, %r)' % \
208 (lspace, next_input, t_magic_name, t_magic_arg_s)
206 209
207 210 # These define the transformations for the different escape characters.
208 211 def _tr_system(line_info):
209 212 "Translate lines escaped with: !"
210 213 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
211 214 return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
212 215
213 216 def _tr_system2(line_info):
214 217 "Translate lines escaped with: !!"
215 218 cmd = line_info.line.lstrip()[2:]
216 219 return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
217 220
218 221 def _tr_help(line_info):
219 222 "Translate lines escaped with: ?/??"
220 223 # A naked help line should just fire the intro help screen
221 224 if not line_info.line[1:]:
222 225 return 'get_ipython().show_usage()'
223 226
224 227 return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
225 228
226 229 def _tr_magic(line_info):
227 230 "Translate lines escaped with: %"
228 tpl = '%sget_ipython().magic(%r)'
231 tpl = '%sget_ipython().run_line_magic(%r, %r)'
229 232 if line_info.line.startswith(ESC_MAGIC2):
230 233 return line_info.line
231 234 cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
232 return tpl % (line_info.pre, cmd)
235 #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
236 t_magic_name, _, t_magic_arg_s = cmd.partition(' ')
237 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
238 return tpl % (line_info.pre, t_magic_name, t_magic_arg_s)
233 239
234 240 def _tr_quote(line_info):
235 241 "Translate lines escaped with: ,"
236 242 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
237 243 '", "'.join(line_info.the_rest.split()) )
238 244
239 245 def _tr_quote2(line_info):
240 246 "Translate lines escaped with: ;"
241 247 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
242 248 line_info.the_rest)
243 249
244 250 def _tr_paren(line_info):
245 251 "Translate lines escaped with: /"
246 252 return '%s%s(%s)' % (line_info.pre, line_info.ifun,
247 253 ", ".join(line_info.the_rest.split()))
248 254
249 255 tr = { ESC_SHELL : _tr_system,
250 256 ESC_SH_CAP : _tr_system2,
251 257 ESC_HELP : _tr_help,
252 258 ESC_HELP2 : _tr_help,
253 259 ESC_MAGIC : _tr_magic,
254 260 ESC_QUOTE : _tr_quote,
255 261 ESC_QUOTE2 : _tr_quote2,
256 262 ESC_PAREN : _tr_paren }
257 263
258 264 @StatelessInputTransformer.wrap
259 265 def escaped_commands(line):
260 266 """Transform escaped commands - %magic, !system, ?help + various autocalls.
261 267 """
262 268 if not line or line.isspace():
263 269 return line
264 270 lineinf = LineInfo(line)
265 271 if lineinf.esc not in tr:
266 272 return line
267 273
268 274 return tr[lineinf.esc](lineinf)
269 275
270 276 _initial_space_re = re.compile(r'\s*')
271 277
272 278 _help_end_re = re.compile(r"""(%{0,2}
273 279 [a-zA-Z_*][\w*]* # Variable name
274 280 (\.[a-zA-Z_*][\w*]*)* # .etc.etc
275 281 )
276 282 (\?\??)$ # ? or ??
277 283 """,
278 284 re.VERBOSE)
279 285
280 286 # Extra pseudotokens for multiline strings and data structures
281 287 _MULTILINE_STRING = object()
282 288 _MULTILINE_STRUCTURE = object()
283 289
284 290 def _line_tokens(line):
285 291 """Helper for has_comment and ends_in_comment_or_string."""
286 292 readline = StringIO(line).readline
287 293 toktypes = set()
288 294 try:
289 295 for t in generate_tokens(readline):
290 296 toktypes.add(t[0])
291 297 except TokenError as e:
292 298 # There are only two cases where a TokenError is raised.
293 299 if 'multi-line string' in e.args[0]:
294 300 toktypes.add(_MULTILINE_STRING)
295 301 else:
296 302 toktypes.add(_MULTILINE_STRUCTURE)
297 303 return toktypes
298 304
299 305 def has_comment(src):
300 306 """Indicate whether an input line has (i.e. ends in, or is) a comment.
301 307
302 308 This uses tokenize, so it can distinguish comments from # inside strings.
303 309
304 310 Parameters
305 311 ----------
306 312 src : string
307 313 A single line input string.
308 314
309 315 Returns
310 316 -------
311 317 comment : bool
312 318 True if source has a comment.
313 319 """
314 320 return (tokenize2.COMMENT in _line_tokens(src))
315 321
316 322 def ends_in_comment_or_string(src):
317 323 """Indicates whether or not an input line ends in a comment or within
318 324 a multiline string.
319 325
320 326 Parameters
321 327 ----------
322 328 src : string
323 329 A single line input string.
324 330
325 331 Returns
326 332 -------
327 333 comment : bool
328 334 True if source ends in a comment or multiline string.
329 335 """
330 336 toktypes = _line_tokens(src)
331 337 return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes)
332 338
333 339
334 340 @StatelessInputTransformer.wrap
335 341 def help_end(line):
336 342 """Translate lines with ?/?? at the end"""
337 343 m = _help_end_re.search(line)
338 344 if m is None or ends_in_comment_or_string(line):
339 345 return line
340 346 target = m.group(1)
341 347 esc = m.group(3)
342 348 lspace = _initial_space_re.match(line).group(0)
343 349
344 350 # If we're mid-command, put it back on the next prompt for the user.
345 351 next_input = line.rstrip('?') if line.strip() != m.group(0) else None
346 352
347 353 return _make_help_call(target, esc, lspace, next_input)
348 354
349 355
350 356 @CoroutineInputTransformer.wrap
351 357 def cellmagic(end_on_blank_line=False):
352 358 """Captures & transforms cell magics.
353 359
354 360 After a cell magic is started, this stores up any lines it gets until it is
355 361 reset (sent None).
356 362 """
357 363 tpl = 'get_ipython().run_cell_magic(%r, %r, %r)'
358 364 cellmagic_help_re = re.compile('%%\w+\?')
359 365 line = ''
360 366 while True:
361 367 line = (yield line)
362 368 # consume leading empty lines
363 369 while not line:
364 370 line = (yield line)
365 371
366 372 if not line.startswith(ESC_MAGIC2):
367 373 # This isn't a cell magic, idle waiting for reset then start over
368 374 while line is not None:
369 375 line = (yield line)
370 376 continue
371 377
372 378 if cellmagic_help_re.match(line):
373 379 # This case will be handled by help_end
374 380 continue
375 381
376 382 first = line
377 383 body = []
378 384 line = (yield None)
379 385 while (line is not None) and \
380 386 ((line.strip() != '') or not end_on_blank_line):
381 387 body.append(line)
382 388 line = (yield None)
383 389
384 390 # Output
385 391 magic_name, _, first = first.partition(' ')
386 392 magic_name = magic_name.lstrip(ESC_MAGIC2)
387 393 line = tpl % (magic_name, first, u'\n'.join(body))
388 394
389 395
390 396 def _strip_prompts(prompt_re, initial_re=None, turnoff_re=None):
391 397 """Remove matching input prompts from a block of input.
392 398
393 399 Parameters
394 400 ----------
395 401 prompt_re : regular expression
396 402 A regular expression matching any input prompt (including continuation)
397 403 initial_re : regular expression, optional
398 404 A regular expression matching only the initial prompt, but not continuation.
399 405 If no initial expression is given, prompt_re will be used everywhere.
400 406 Used mainly for plain Python prompts, where the continuation prompt
401 407 ``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
402 408
403 409 If initial_re and prompt_re differ,
404 410 only initial_re will be tested against the first line.
405 411 If any prompt is found on the first two lines,
406 412 prompts will be stripped from the rest of the block.
407 413 """
408 414 if initial_re is None:
409 415 initial_re = prompt_re
410 416 line = ''
411 417 while True:
412 418 line = (yield line)
413 419
414 420 # First line of cell
415 421 if line is None:
416 422 continue
417 423 out, n1 = initial_re.subn('', line, count=1)
418 424 if turnoff_re and not n1:
419 425 if turnoff_re.match(line):
420 426 # We're in e.g. a cell magic; disable this transformer for
421 427 # the rest of the cell.
422 428 while line is not None:
423 429 line = (yield line)
424 430 continue
425 431
426 432 line = (yield out)
427 433
428 434 if line is None:
429 435 continue
430 436 # check for any prompt on the second line of the cell,
431 437 # because people often copy from just after the first prompt,
432 438 # so we might not see it in the first line.
433 439 out, n2 = prompt_re.subn('', line, count=1)
434 440 line = (yield out)
435 441
436 442 if n1 or n2:
437 443 # Found a prompt in the first two lines - check for it in
438 444 # the rest of the cell as well.
439 445 while line is not None:
440 446 line = (yield prompt_re.sub('', line, count=1))
441 447
442 448 else:
443 449 # Prompts not in input - wait for reset
444 450 while line is not None:
445 451 line = (yield line)
446 452
447 453 @CoroutineInputTransformer.wrap
448 454 def classic_prompt():
449 455 """Strip the >>>/... prompts of the Python interactive shell."""
450 456 # FIXME: non-capturing version (?:...) usable?
451 457 prompt_re = re.compile(r'^(>>>|\.\.\.)( |$)')
452 458 initial_re = re.compile(r'^>>>( |$)')
453 459 # Any %magic/!system is IPython syntax, so we needn't look for >>> prompts
454 460 turnoff_re = re.compile(r'^[%!]')
455 461 return _strip_prompts(prompt_re, initial_re, turnoff_re)
456 462
457 463 @CoroutineInputTransformer.wrap
458 464 def ipy_prompt():
459 465 """Strip IPython's In [1]:/...: prompts."""
460 466 # FIXME: non-capturing version (?:...) usable?
461 467 prompt_re = re.compile(r'^(In \[\d+\]: |\s*\.{3,}: ?)')
462 468 # Disable prompt stripping inside cell magics
463 469 turnoff_re = re.compile(r'^%%')
464 470 return _strip_prompts(prompt_re, turnoff_re=turnoff_re)
465 471
466 472
467 473 @CoroutineInputTransformer.wrap
468 474 def leading_indent():
469 475 """Remove leading indentation.
470 476
471 477 If the first line starts with a spaces or tabs, the same whitespace will be
472 478 removed from each following line until it is reset.
473 479 """
474 480 space_re = re.compile(r'^[ \t]+')
475 481 line = ''
476 482 while True:
477 483 line = (yield line)
478 484
479 485 if line is None:
480 486 continue
481 487
482 488 m = space_re.match(line)
483 489 if m:
484 490 space = m.group(0)
485 491 while line is not None:
486 492 if line.startswith(space):
487 493 line = line[len(space):]
488 494 line = (yield line)
489 495 else:
490 496 # No leading spaces - wait for reset
491 497 while line is not None:
492 498 line = (yield line)
493 499
494 500
495 501 _assign_pat = \
496 502 r'''(?P<lhs>(\s*)
497 503 ([\w\.]+) # Initial identifier
498 504 (\s*,\s*
499 505 \*?[\w\.]+)* # Further identifiers for unpacking
500 506 \s*?,? # Trailing comma
501 507 )
502 508 \s*=\s*
503 509 '''
504 510
505 511 assign_system_re = re.compile(r'{}!\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
506 512 assign_system_template = '%s = get_ipython().getoutput(%r)'
507 513 @StatelessInputTransformer.wrap
508 514 def assign_from_system(line):
509 515 """Transform assignment from system commands (e.g. files = !ls)"""
510 516 m = assign_system_re.match(line)
511 517 if m is None:
512 518 return line
513 519
514 520 return assign_system_template % m.group('lhs', 'cmd')
515 521
516 522 assign_magic_re = re.compile(r'{}%\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
517 assign_magic_template = '%s = get_ipython().magic(%r)'
523 assign_magic_template = '%s = get_ipython().run_line_magic(%r, %r)'
518 524 @StatelessInputTransformer.wrap
519 525 def assign_from_magic(line):
520 526 """Transform assignment from magic commands (e.g. a = %who_ls)"""
521 527 m = assign_magic_re.match(line)
522 528 if m is None:
523 529 return line
524
525 return assign_magic_template % m.group('lhs', 'cmd')
530 #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
531 m_lhs, m_cmd = m.group('lhs', 'cmd')
532 t_magic_name, _, t_magic_arg_s = m_cmd.partition(' ')
533 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
534 return assign_magic_template % (m_lhs, t_magic_name, t_magic_arg_s)
@@ -1,3253 +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):
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
2058 _stack_depth : int
2059 If run_line_magic() is called from magic() then _stack_depth=2.
2060 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2057 2061 """
2058 2062 fn = self.find_line_magic(magic_name)
2059 2063 if fn is None:
2060 2064 cm = self.find_cell_magic(magic_name)
2061 2065 etpl = "Line magic function `%%%s` not found%s."
2062 2066 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2063 2067 'did you mean that instead?)' % magic_name )
2064 2068 error(etpl % (magic_name, extra))
2065 2069 else:
2066 2070 # Note: this is the distance in the stack to the user's frame.
2067 2071 # This will need to be updated if the internal calling logic gets
2068 2072 # refactored, or else we'll be expanding the wrong variables.
2069 stack_depth = 2
2073
2074 # Determine stack_depth depending on where run_line_magic() has been called
2075 stack_depth = _stack_depth
2070 2076 magic_arg_s = self.var_expand(line, stack_depth)
2071 2077 # Put magic args in a list so we can call with f(*a) syntax
2072 2078 args = [magic_arg_s]
2073 2079 kwargs = {}
2074 2080 # Grab local namespace if we need it:
2075 2081 if getattr(fn, "needs_local_scope", False):
2076 2082 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2077 2083 with self.builtin_trap:
2078 2084 result = fn(*args,**kwargs)
2079 2085 return result
2080 2086
2081 2087 def run_cell_magic(self, magic_name, line, cell):
2082 2088 """Execute the given cell magic.
2083 2089
2084 2090 Parameters
2085 2091 ----------
2086 2092 magic_name : str
2087 2093 Name of the desired magic function, without '%' prefix.
2088 2094
2089 2095 line : str
2090 2096 The rest of the first input line as a single string.
2091 2097
2092 2098 cell : str
2093 2099 The body of the cell as a (possibly multiline) string.
2094 2100 """
2095 2101 fn = self.find_cell_magic(magic_name)
2096 2102 if fn is None:
2097 2103 lm = self.find_line_magic(magic_name)
2098 2104 etpl = "Cell magic `%%{0}` not found{1}."
2099 2105 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2100 2106 'did you mean that instead?)'.format(magic_name))
2101 2107 error(etpl.format(magic_name, extra))
2102 2108 elif cell == '':
2103 2109 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2104 2110 if self.find_line_magic(magic_name) is not None:
2105 2111 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2106 2112 raise UsageError(message)
2107 2113 else:
2108 2114 # Note: this is the distance in the stack to the user's frame.
2109 2115 # This will need to be updated if the internal calling logic gets
2110 2116 # refactored, or else we'll be expanding the wrong variables.
2111 2117 stack_depth = 2
2112 2118 magic_arg_s = self.var_expand(line, stack_depth)
2113 2119 with self.builtin_trap:
2114 2120 result = fn(magic_arg_s, cell)
2115 2121 return result
2116 2122
2117 2123 def find_line_magic(self, magic_name):
2118 2124 """Find and return a line magic by name.
2119 2125
2120 2126 Returns None if the magic isn't found."""
2121 2127 return self.magics_manager.magics['line'].get(magic_name)
2122 2128
2123 2129 def find_cell_magic(self, magic_name):
2124 2130 """Find and return a cell magic by name.
2125 2131
2126 2132 Returns None if the magic isn't found."""
2127 2133 return self.magics_manager.magics['cell'].get(magic_name)
2128 2134
2129 2135 def find_magic(self, magic_name, magic_kind='line'):
2130 2136 """Find and return a magic of the given type by name.
2131 2137
2132 2138 Returns None if the magic isn't found."""
2133 2139 return self.magics_manager.magics[magic_kind].get(magic_name)
2134 2140
2135 2141 def magic(self, arg_s):
2136 2142 """DEPRECATED. Use run_line_magic() instead.
2137 2143
2138 2144 Call a magic function by name.
2139 2145
2140 2146 Input: a string containing the name of the magic function to call and
2141 2147 any additional arguments to be passed to the magic.
2142 2148
2143 2149 magic('name -opt foo bar') is equivalent to typing at the ipython
2144 2150 prompt:
2145 2151
2146 2152 In[1]: %name -opt foo bar
2147 2153
2148 2154 To call a magic without arguments, simply use magic('name').
2149 2155
2150 2156 This provides a proper Python function to call IPython's magics in any
2151 2157 valid Python code you can type at the interpreter, including loops and
2152 2158 compound statements.
2153 2159 """
2154 2160 # TODO: should we issue a loud deprecation warning here?
2155 2161 magic_name, _, magic_arg_s = arg_s.partition(' ')
2156 2162 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2157 return self.run_line_magic(magic_name, magic_arg_s)
2163 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2158 2164
2159 2165 #-------------------------------------------------------------------------
2160 2166 # Things related to macros
2161 2167 #-------------------------------------------------------------------------
2162 2168
2163 2169 def define_macro(self, name, themacro):
2164 2170 """Define a new macro
2165 2171
2166 2172 Parameters
2167 2173 ----------
2168 2174 name : str
2169 2175 The name of the macro.
2170 2176 themacro : str or Macro
2171 2177 The action to do upon invoking the macro. If a string, a new
2172 2178 Macro object is created by passing the string to it.
2173 2179 """
2174 2180
2175 2181 from IPython.core import macro
2176 2182
2177 2183 if isinstance(themacro, str):
2178 2184 themacro = macro.Macro(themacro)
2179 2185 if not isinstance(themacro, macro.Macro):
2180 2186 raise ValueError('A macro must be a string or a Macro instance.')
2181 2187 self.user_ns[name] = themacro
2182 2188
2183 2189 #-------------------------------------------------------------------------
2184 2190 # Things related to the running of system commands
2185 2191 #-------------------------------------------------------------------------
2186 2192
2187 2193 def system_piped(self, cmd):
2188 2194 """Call the given cmd in a subprocess, piping stdout/err
2189 2195
2190 2196 Parameters
2191 2197 ----------
2192 2198 cmd : str
2193 2199 Command to execute (can not end in '&', as background processes are
2194 2200 not supported. Should not be a command that expects input
2195 2201 other than simple text.
2196 2202 """
2197 2203 if cmd.rstrip().endswith('&'):
2198 2204 # this is *far* from a rigorous test
2199 2205 # We do not support backgrounding processes because we either use
2200 2206 # pexpect or pipes to read from. Users can always just call
2201 2207 # os.system() or use ip.system=ip.system_raw
2202 2208 # if they really want a background process.
2203 2209 raise OSError("Background processes not supported.")
2204 2210
2205 2211 # we explicitly do NOT return the subprocess status code, because
2206 2212 # a non-None value would trigger :func:`sys.displayhook` calls.
2207 2213 # Instead, we store the exit_code in user_ns.
2208 2214 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2209 2215
2210 2216 def system_raw(self, cmd):
2211 2217 """Call the given cmd in a subprocess using os.system on Windows or
2212 2218 subprocess.call using the system shell on other platforms.
2213 2219
2214 2220 Parameters
2215 2221 ----------
2216 2222 cmd : str
2217 2223 Command to execute.
2218 2224 """
2219 2225 cmd = self.var_expand(cmd, depth=1)
2220 2226 # protect os.system from UNC paths on Windows, which it can't handle:
2221 2227 if sys.platform == 'win32':
2222 2228 from IPython.utils._process_win32 import AvoidUNCPath
2223 2229 with AvoidUNCPath() as path:
2224 2230 if path is not None:
2225 2231 cmd = '"pushd %s &&"%s' % (path, cmd)
2226 2232 try:
2227 2233 ec = os.system(cmd)
2228 2234 except KeyboardInterrupt:
2229 2235 print('\n' + self.get_exception_only(), file=sys.stderr)
2230 2236 ec = -2
2231 2237 else:
2232 2238 # For posix the result of the subprocess.call() below is an exit
2233 2239 # code, which by convention is zero for success, positive for
2234 2240 # program failure. Exit codes above 128 are reserved for signals,
2235 2241 # and the formula for converting a signal to an exit code is usually
2236 2242 # signal_number+128. To more easily differentiate between exit
2237 2243 # codes and signals, ipython uses negative numbers. For instance
2238 2244 # since control-c is signal 2 but exit code 130, ipython's
2239 2245 # _exit_code variable will read -2. Note that some shells like
2240 2246 # csh and fish don't follow sh/bash conventions for exit codes.
2241 2247 executable = os.environ.get('SHELL', None)
2242 2248 try:
2243 2249 # Use env shell instead of default /bin/sh
2244 2250 ec = subprocess.call(cmd, shell=True, executable=executable)
2245 2251 except KeyboardInterrupt:
2246 2252 # intercept control-C; a long traceback is not useful here
2247 2253 print('\n' + self.get_exception_only(), file=sys.stderr)
2248 2254 ec = 130
2249 2255 if ec > 128:
2250 2256 ec = -(ec - 128)
2251 2257
2252 2258 # We explicitly do NOT return the subprocess status code, because
2253 2259 # a non-None value would trigger :func:`sys.displayhook` calls.
2254 2260 # Instead, we store the exit_code in user_ns. Note the semantics
2255 2261 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2256 2262 # but raising SystemExit(_exit_code) will give status 254!
2257 2263 self.user_ns['_exit_code'] = ec
2258 2264
2259 2265 # use piped system by default, because it is better behaved
2260 2266 system = system_piped
2261 2267
2262 2268 def getoutput(self, cmd, split=True, depth=0):
2263 2269 """Get output (possibly including stderr) from a subprocess.
2264 2270
2265 2271 Parameters
2266 2272 ----------
2267 2273 cmd : str
2268 2274 Command to execute (can not end in '&', as background processes are
2269 2275 not supported.
2270 2276 split : bool, optional
2271 2277 If True, split the output into an IPython SList. Otherwise, an
2272 2278 IPython LSString is returned. These are objects similar to normal
2273 2279 lists and strings, with a few convenience attributes for easier
2274 2280 manipulation of line-based output. You can use '?' on them for
2275 2281 details.
2276 2282 depth : int, optional
2277 2283 How many frames above the caller are the local variables which should
2278 2284 be expanded in the command string? The default (0) assumes that the
2279 2285 expansion variables are in the stack frame calling this function.
2280 2286 """
2281 2287 if cmd.rstrip().endswith('&'):
2282 2288 # this is *far* from a rigorous test
2283 2289 raise OSError("Background processes not supported.")
2284 2290 out = getoutput(self.var_expand(cmd, depth=depth+1))
2285 2291 if split:
2286 2292 out = SList(out.splitlines())
2287 2293 else:
2288 2294 out = LSString(out)
2289 2295 return out
2290 2296
2291 2297 #-------------------------------------------------------------------------
2292 2298 # Things related to aliases
2293 2299 #-------------------------------------------------------------------------
2294 2300
2295 2301 def init_alias(self):
2296 2302 self.alias_manager = AliasManager(shell=self, parent=self)
2297 2303 self.configurables.append(self.alias_manager)
2298 2304
2299 2305 #-------------------------------------------------------------------------
2300 2306 # Things related to extensions
2301 2307 #-------------------------------------------------------------------------
2302 2308
2303 2309 def init_extension_manager(self):
2304 2310 self.extension_manager = ExtensionManager(shell=self, parent=self)
2305 2311 self.configurables.append(self.extension_manager)
2306 2312
2307 2313 #-------------------------------------------------------------------------
2308 2314 # Things related to payloads
2309 2315 #-------------------------------------------------------------------------
2310 2316
2311 2317 def init_payload(self):
2312 2318 self.payload_manager = PayloadManager(parent=self)
2313 2319 self.configurables.append(self.payload_manager)
2314 2320
2315 2321 #-------------------------------------------------------------------------
2316 2322 # Things related to the prefilter
2317 2323 #-------------------------------------------------------------------------
2318 2324
2319 2325 def init_prefilter(self):
2320 2326 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2321 2327 self.configurables.append(self.prefilter_manager)
2322 2328 # Ultimately this will be refactored in the new interpreter code, but
2323 2329 # for now, we should expose the main prefilter method (there's legacy
2324 2330 # code out there that may rely on this).
2325 2331 self.prefilter = self.prefilter_manager.prefilter_lines
2326 2332
2327 2333 def auto_rewrite_input(self, cmd):
2328 2334 """Print to the screen the rewritten form of the user's command.
2329 2335
2330 2336 This shows visual feedback by rewriting input lines that cause
2331 2337 automatic calling to kick in, like::
2332 2338
2333 2339 /f x
2334 2340
2335 2341 into::
2336 2342
2337 2343 ------> f(x)
2338 2344
2339 2345 after the user's input prompt. This helps the user understand that the
2340 2346 input line was transformed automatically by IPython.
2341 2347 """
2342 2348 if not self.show_rewritten_input:
2343 2349 return
2344 2350
2345 2351 # This is overridden in TerminalInteractiveShell to use fancy prompts
2346 2352 print("------> " + cmd)
2347 2353
2348 2354 #-------------------------------------------------------------------------
2349 2355 # Things related to extracting values/expressions from kernel and user_ns
2350 2356 #-------------------------------------------------------------------------
2351 2357
2352 2358 def _user_obj_error(self):
2353 2359 """return simple exception dict
2354 2360
2355 2361 for use in user_expressions
2356 2362 """
2357 2363
2358 2364 etype, evalue, tb = self._get_exc_info()
2359 2365 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2360 2366
2361 2367 exc_info = {
2362 2368 u'status' : 'error',
2363 2369 u'traceback' : stb,
2364 2370 u'ename' : etype.__name__,
2365 2371 u'evalue' : py3compat.safe_unicode(evalue),
2366 2372 }
2367 2373
2368 2374 return exc_info
2369 2375
2370 2376 def _format_user_obj(self, obj):
2371 2377 """format a user object to display dict
2372 2378
2373 2379 for use in user_expressions
2374 2380 """
2375 2381
2376 2382 data, md = self.display_formatter.format(obj)
2377 2383 value = {
2378 2384 'status' : 'ok',
2379 2385 'data' : data,
2380 2386 'metadata' : md,
2381 2387 }
2382 2388 return value
2383 2389
2384 2390 def user_expressions(self, expressions):
2385 2391 """Evaluate a dict of expressions in the user's namespace.
2386 2392
2387 2393 Parameters
2388 2394 ----------
2389 2395 expressions : dict
2390 2396 A dict with string keys and string values. The expression values
2391 2397 should be valid Python expressions, each of which will be evaluated
2392 2398 in the user namespace.
2393 2399
2394 2400 Returns
2395 2401 -------
2396 2402 A dict, keyed like the input expressions dict, with the rich mime-typed
2397 2403 display_data of each value.
2398 2404 """
2399 2405 out = {}
2400 2406 user_ns = self.user_ns
2401 2407 global_ns = self.user_global_ns
2402 2408
2403 2409 for key, expr in expressions.items():
2404 2410 try:
2405 2411 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2406 2412 except:
2407 2413 value = self._user_obj_error()
2408 2414 out[key] = value
2409 2415 return out
2410 2416
2411 2417 #-------------------------------------------------------------------------
2412 2418 # Things related to the running of code
2413 2419 #-------------------------------------------------------------------------
2414 2420
2415 2421 def ex(self, cmd):
2416 2422 """Execute a normal python statement in user namespace."""
2417 2423 with self.builtin_trap:
2418 2424 exec(cmd, self.user_global_ns, self.user_ns)
2419 2425
2420 2426 def ev(self, expr):
2421 2427 """Evaluate python expression expr in user namespace.
2422 2428
2423 2429 Returns the result of evaluation
2424 2430 """
2425 2431 with self.builtin_trap:
2426 2432 return eval(expr, self.user_global_ns, self.user_ns)
2427 2433
2428 2434 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2429 2435 """A safe version of the builtin execfile().
2430 2436
2431 2437 This version will never throw an exception, but instead print
2432 2438 helpful error messages to the screen. This only works on pure
2433 2439 Python files with the .py extension.
2434 2440
2435 2441 Parameters
2436 2442 ----------
2437 2443 fname : string
2438 2444 The name of the file to be executed.
2439 2445 where : tuple
2440 2446 One or two namespaces, passed to execfile() as (globals,locals).
2441 2447 If only one is given, it is passed as both.
2442 2448 exit_ignore : bool (False)
2443 2449 If True, then silence SystemExit for non-zero status (it is always
2444 2450 silenced for zero status, as it is so common).
2445 2451 raise_exceptions : bool (False)
2446 2452 If True raise exceptions everywhere. Meant for testing.
2447 2453 shell_futures : bool (False)
2448 2454 If True, the code will share future statements with the interactive
2449 2455 shell. It will both be affected by previous __future__ imports, and
2450 2456 any __future__ imports in the code will affect the shell. If False,
2451 2457 __future__ imports are not shared in either direction.
2452 2458
2453 2459 """
2454 2460 fname = os.path.abspath(os.path.expanduser(fname))
2455 2461
2456 2462 # Make sure we can open the file
2457 2463 try:
2458 2464 with open(fname):
2459 2465 pass
2460 2466 except:
2461 2467 warn('Could not open file <%s> for safe execution.' % fname)
2462 2468 return
2463 2469
2464 2470 # Find things also in current directory. This is needed to mimic the
2465 2471 # behavior of running a script from the system command line, where
2466 2472 # Python inserts the script's directory into sys.path
2467 2473 dname = os.path.dirname(fname)
2468 2474
2469 2475 with prepended_to_syspath(dname), self.builtin_trap:
2470 2476 try:
2471 2477 glob, loc = (where + (None, ))[:2]
2472 2478 py3compat.execfile(
2473 2479 fname, glob, loc,
2474 2480 self.compile if shell_futures else None)
2475 2481 except SystemExit as status:
2476 2482 # If the call was made with 0 or None exit status (sys.exit(0)
2477 2483 # or sys.exit() ), don't bother showing a traceback, as both of
2478 2484 # these are considered normal by the OS:
2479 2485 # > python -c'import sys;sys.exit(0)'; echo $?
2480 2486 # 0
2481 2487 # > python -c'import sys;sys.exit()'; echo $?
2482 2488 # 0
2483 2489 # For other exit status, we show the exception unless
2484 2490 # explicitly silenced, but only in short form.
2485 2491 if status.code:
2486 2492 if raise_exceptions:
2487 2493 raise
2488 2494 if not exit_ignore:
2489 2495 self.showtraceback(exception_only=True)
2490 2496 except:
2491 2497 if raise_exceptions:
2492 2498 raise
2493 2499 # tb offset is 2 because we wrap execfile
2494 2500 self.showtraceback(tb_offset=2)
2495 2501
2496 2502 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2497 2503 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2498 2504
2499 2505 Parameters
2500 2506 ----------
2501 2507 fname : str
2502 2508 The name of the file to execute. The filename must have a
2503 2509 .ipy or .ipynb extension.
2504 2510 shell_futures : bool (False)
2505 2511 If True, the code will share future statements with the interactive
2506 2512 shell. It will both be affected by previous __future__ imports, and
2507 2513 any __future__ imports in the code will affect the shell. If False,
2508 2514 __future__ imports are not shared in either direction.
2509 2515 raise_exceptions : bool (False)
2510 2516 If True raise exceptions everywhere. Meant for testing.
2511 2517 """
2512 2518 fname = os.path.abspath(os.path.expanduser(fname))
2513 2519
2514 2520 # Make sure we can open the file
2515 2521 try:
2516 2522 with open(fname):
2517 2523 pass
2518 2524 except:
2519 2525 warn('Could not open file <%s> for safe execution.' % fname)
2520 2526 return
2521 2527
2522 2528 # Find things also in current directory. This is needed to mimic the
2523 2529 # behavior of running a script from the system command line, where
2524 2530 # Python inserts the script's directory into sys.path
2525 2531 dname = os.path.dirname(fname)
2526 2532
2527 2533 def get_cells():
2528 2534 """generator for sequence of code blocks to run"""
2529 2535 if fname.endswith('.ipynb'):
2530 2536 from nbformat import read
2531 2537 nb = read(fname, as_version=4)
2532 2538 if not nb.cells:
2533 2539 return
2534 2540 for cell in nb.cells:
2535 2541 if cell.cell_type == 'code':
2536 2542 yield cell.source
2537 2543 else:
2538 2544 with open(fname) as f:
2539 2545 yield f.read()
2540 2546
2541 2547 with prepended_to_syspath(dname):
2542 2548 try:
2543 2549 for cell in get_cells():
2544 2550 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2545 2551 if raise_exceptions:
2546 2552 result.raise_error()
2547 2553 elif not result.success:
2548 2554 break
2549 2555 except:
2550 2556 if raise_exceptions:
2551 2557 raise
2552 2558 self.showtraceback()
2553 2559 warn('Unknown failure executing file: <%s>' % fname)
2554 2560
2555 2561 def safe_run_module(self, mod_name, where):
2556 2562 """A safe version of runpy.run_module().
2557 2563
2558 2564 This version will never throw an exception, but instead print
2559 2565 helpful error messages to the screen.
2560 2566
2561 2567 `SystemExit` exceptions with status code 0 or None are ignored.
2562 2568
2563 2569 Parameters
2564 2570 ----------
2565 2571 mod_name : string
2566 2572 The name of the module to be executed.
2567 2573 where : dict
2568 2574 The globals namespace.
2569 2575 """
2570 2576 try:
2571 2577 try:
2572 2578 where.update(
2573 2579 runpy.run_module(str(mod_name), run_name="__main__",
2574 2580 alter_sys=True)
2575 2581 )
2576 2582 except SystemExit as status:
2577 2583 if status.code:
2578 2584 raise
2579 2585 except:
2580 2586 self.showtraceback()
2581 2587 warn('Unknown failure executing module: <%s>' % mod_name)
2582 2588
2583 2589 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2584 2590 """Run a complete IPython cell.
2585 2591
2586 2592 Parameters
2587 2593 ----------
2588 2594 raw_cell : str
2589 2595 The code (including IPython code such as %magic functions) to run.
2590 2596 store_history : bool
2591 2597 If True, the raw and translated cell will be stored in IPython's
2592 2598 history. For user code calling back into IPython's machinery, this
2593 2599 should be set to False.
2594 2600 silent : bool
2595 2601 If True, avoid side-effects, such as implicit displayhooks and
2596 2602 and logging. silent=True forces store_history=False.
2597 2603 shell_futures : bool
2598 2604 If True, the code will share future statements with the interactive
2599 2605 shell. It will both be affected by previous __future__ imports, and
2600 2606 any __future__ imports in the code will affect the shell. If False,
2601 2607 __future__ imports are not shared in either direction.
2602 2608
2603 2609 Returns
2604 2610 -------
2605 2611 result : :class:`ExecutionResult`
2606 2612 """
2607 2613 result = ExecutionResult()
2608 2614
2609 2615 if (not raw_cell) or raw_cell.isspace():
2610 2616 self.last_execution_succeeded = True
2611 2617 return result
2612 2618
2613 2619 if silent:
2614 2620 store_history = False
2615 2621
2616 2622 if store_history:
2617 2623 result.execution_count = self.execution_count
2618 2624
2619 2625 def error_before_exec(value):
2620 2626 result.error_before_exec = value
2621 2627 self.last_execution_succeeded = False
2622 2628 return result
2623 2629
2624 2630 self.events.trigger('pre_execute')
2625 2631 if not silent:
2626 2632 self.events.trigger('pre_run_cell')
2627 2633
2628 2634 # If any of our input transformation (input_transformer_manager or
2629 2635 # prefilter_manager) raises an exception, we store it in this variable
2630 2636 # so that we can display the error after logging the input and storing
2631 2637 # it in the history.
2632 2638 preprocessing_exc_tuple = None
2633 2639 try:
2634 2640 # Static input transformations
2635 2641 cell = self.input_transformer_manager.transform_cell(raw_cell)
2636 2642 except SyntaxError:
2637 2643 preprocessing_exc_tuple = sys.exc_info()
2638 2644 cell = raw_cell # cell has to exist so it can be stored/logged
2639 2645 else:
2640 2646 if len(cell.splitlines()) == 1:
2641 2647 # Dynamic transformations - only applied for single line commands
2642 2648 with self.builtin_trap:
2643 2649 try:
2644 2650 # use prefilter_lines to handle trailing newlines
2645 2651 # restore trailing newline for ast.parse
2646 2652 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2647 2653 except Exception:
2648 2654 # don't allow prefilter errors to crash IPython
2649 2655 preprocessing_exc_tuple = sys.exc_info()
2650 2656
2651 2657 # Store raw and processed history
2652 2658 if store_history:
2653 2659 self.history_manager.store_inputs(self.execution_count,
2654 2660 cell, raw_cell)
2655 2661 if not silent:
2656 2662 self.logger.log(cell, raw_cell)
2657 2663
2658 2664 # Display the exception if input processing failed.
2659 2665 if preprocessing_exc_tuple is not None:
2660 2666 self.showtraceback(preprocessing_exc_tuple)
2661 2667 if store_history:
2662 2668 self.execution_count += 1
2663 2669 return error_before_exec(preprocessing_exc_tuple[2])
2664 2670
2665 2671 # Our own compiler remembers the __future__ environment. If we want to
2666 2672 # run code with a separate __future__ environment, use the default
2667 2673 # compiler
2668 2674 compiler = self.compile if shell_futures else CachingCompiler()
2669 2675
2670 2676 with self.builtin_trap:
2671 2677 cell_name = self.compile.cache(cell, self.execution_count)
2672 2678
2673 2679 with self.display_trap:
2674 2680 # Compile to bytecode
2675 2681 try:
2676 2682 code_ast = compiler.ast_parse(cell, filename=cell_name)
2677 2683 except self.custom_exceptions as e:
2678 2684 etype, value, tb = sys.exc_info()
2679 2685 self.CustomTB(etype, value, tb)
2680 2686 return error_before_exec(e)
2681 2687 except IndentationError as e:
2682 2688 self.showindentationerror()
2683 2689 if store_history:
2684 2690 self.execution_count += 1
2685 2691 return error_before_exec(e)
2686 2692 except (OverflowError, SyntaxError, ValueError, TypeError,
2687 2693 MemoryError) as e:
2688 2694 self.showsyntaxerror()
2689 2695 if store_history:
2690 2696 self.execution_count += 1
2691 2697 return error_before_exec(e)
2692 2698
2693 2699 # Apply AST transformations
2694 2700 try:
2695 2701 code_ast = self.transform_ast(code_ast)
2696 2702 except InputRejected as e:
2697 2703 self.showtraceback()
2698 2704 if store_history:
2699 2705 self.execution_count += 1
2700 2706 return error_before_exec(e)
2701 2707
2702 2708 # Give the displayhook a reference to our ExecutionResult so it
2703 2709 # can fill in the output value.
2704 2710 self.displayhook.exec_result = result
2705 2711
2706 2712 # Execute the user code
2707 2713 interactivity = "none" if silent else self.ast_node_interactivity
2708 2714 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2709 2715 interactivity=interactivity, compiler=compiler, result=result)
2710 2716
2711 2717 self.last_execution_succeeded = not has_raised
2712 2718
2713 2719 # Reset this so later displayed values do not modify the
2714 2720 # ExecutionResult
2715 2721 self.displayhook.exec_result = None
2716 2722
2717 2723 self.events.trigger('post_execute')
2718 2724 if not silent:
2719 2725 self.events.trigger('post_run_cell')
2720 2726
2721 2727 if store_history:
2722 2728 # Write output to the database. Does nothing unless
2723 2729 # history output logging is enabled.
2724 2730 self.history_manager.store_output(self.execution_count)
2725 2731 # Each cell is a *single* input, regardless of how many lines it has
2726 2732 self.execution_count += 1
2727 2733
2728 2734 return result
2729 2735
2730 2736 def transform_ast(self, node):
2731 2737 """Apply the AST transformations from self.ast_transformers
2732 2738
2733 2739 Parameters
2734 2740 ----------
2735 2741 node : ast.Node
2736 2742 The root node to be transformed. Typically called with the ast.Module
2737 2743 produced by parsing user input.
2738 2744
2739 2745 Returns
2740 2746 -------
2741 2747 An ast.Node corresponding to the node it was called with. Note that it
2742 2748 may also modify the passed object, so don't rely on references to the
2743 2749 original AST.
2744 2750 """
2745 2751 for transformer in self.ast_transformers:
2746 2752 try:
2747 2753 node = transformer.visit(node)
2748 2754 except InputRejected:
2749 2755 # User-supplied AST transformers can reject an input by raising
2750 2756 # an InputRejected. Short-circuit in this case so that we
2751 2757 # don't unregister the transform.
2752 2758 raise
2753 2759 except Exception:
2754 2760 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2755 2761 self.ast_transformers.remove(transformer)
2756 2762
2757 2763 if self.ast_transformers:
2758 2764 ast.fix_missing_locations(node)
2759 2765 return node
2760 2766
2761 2767
2762 2768 def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
2763 2769 compiler=compile, result=None):
2764 2770 """Run a sequence of AST nodes. The execution mode depends on the
2765 2771 interactivity parameter.
2766 2772
2767 2773 Parameters
2768 2774 ----------
2769 2775 nodelist : list
2770 2776 A sequence of AST nodes to run.
2771 2777 cell_name : str
2772 2778 Will be passed to the compiler as the filename of the cell. Typically
2773 2779 the value returned by ip.compile.cache(cell).
2774 2780 interactivity : str
2775 2781 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
2776 2782 specifying which nodes should be run interactively (displaying output
2777 2783 from expressions). 'last_expr' will run the last node interactively
2778 2784 only if it is an expression (i.e. expressions in loops or other blocks
2779 2785 are not displayed) 'last_expr_or_assign' will run the last expression
2780 2786 or the last assignment. Other values for this parameter will raise a
2781 2787 ValueError.
2782 2788 compiler : callable
2783 2789 A function with the same interface as the built-in compile(), to turn
2784 2790 the AST nodes into code objects. Default is the built-in compile().
2785 2791 result : ExecutionResult, optional
2786 2792 An object to store exceptions that occur during execution.
2787 2793
2788 2794 Returns
2789 2795 -------
2790 2796 True if an exception occurred while running code, False if it finished
2791 2797 running.
2792 2798 """
2793 2799 if not nodelist:
2794 2800 return
2795 2801
2796 2802 if interactivity == 'last_expr_or_assign':
2797 2803 if isinstance(nodelist[-1], _assign_nodes):
2798 2804 asg = nodelist[-1]
2799 2805 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
2800 2806 target = asg.targets[0]
2801 2807 elif isinstance(asg, _single_targets_nodes):
2802 2808 target = asg.target
2803 2809 else:
2804 2810 target = None
2805 2811 if isinstance(target, ast.Name):
2806 2812 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
2807 2813 ast.fix_missing_locations(nnode)
2808 2814 nodelist.append(nnode)
2809 2815 interactivity = 'last_expr'
2810 2816
2811 2817 if interactivity == 'last_expr':
2812 2818 if isinstance(nodelist[-1], ast.Expr):
2813 2819 interactivity = "last"
2814 2820 else:
2815 2821 interactivity = "none"
2816 2822
2817 2823 if interactivity == 'none':
2818 2824 to_run_exec, to_run_interactive = nodelist, []
2819 2825 elif interactivity == 'last':
2820 2826 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2821 2827 elif interactivity == 'all':
2822 2828 to_run_exec, to_run_interactive = [], nodelist
2823 2829 else:
2824 2830 raise ValueError("Interactivity was %r" % interactivity)
2825 2831
2826 2832 try:
2827 2833 for i, node in enumerate(to_run_exec):
2828 2834 mod = ast.Module([node])
2829 2835 code = compiler(mod, cell_name, "exec")
2830 2836 if self.run_code(code, result):
2831 2837 return True
2832 2838
2833 2839 for i, node in enumerate(to_run_interactive):
2834 2840 mod = ast.Interactive([node])
2835 2841 code = compiler(mod, cell_name, "single")
2836 2842 if self.run_code(code, result):
2837 2843 return True
2838 2844
2839 2845 # Flush softspace
2840 2846 if softspace(sys.stdout, 0):
2841 2847 print()
2842 2848
2843 2849 except:
2844 2850 # It's possible to have exceptions raised here, typically by
2845 2851 # compilation of odd code (such as a naked 'return' outside a
2846 2852 # function) that did parse but isn't valid. Typically the exception
2847 2853 # is a SyntaxError, but it's safest just to catch anything and show
2848 2854 # the user a traceback.
2849 2855
2850 2856 # We do only one try/except outside the loop to minimize the impact
2851 2857 # on runtime, and also because if any node in the node list is
2852 2858 # broken, we should stop execution completely.
2853 2859 if result:
2854 2860 result.error_before_exec = sys.exc_info()[1]
2855 2861 self.showtraceback()
2856 2862 return True
2857 2863
2858 2864 return False
2859 2865
2860 2866 def run_code(self, code_obj, result=None):
2861 2867 """Execute a code object.
2862 2868
2863 2869 When an exception occurs, self.showtraceback() is called to display a
2864 2870 traceback.
2865 2871
2866 2872 Parameters
2867 2873 ----------
2868 2874 code_obj : code object
2869 2875 A compiled code object, to be executed
2870 2876 result : ExecutionResult, optional
2871 2877 An object to store exceptions that occur during execution.
2872 2878
2873 2879 Returns
2874 2880 -------
2875 2881 False : successful execution.
2876 2882 True : an error occurred.
2877 2883 """
2878 2884 # Set our own excepthook in case the user code tries to call it
2879 2885 # directly, so that the IPython crash handler doesn't get triggered
2880 2886 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2881 2887
2882 2888 # we save the original sys.excepthook in the instance, in case config
2883 2889 # code (such as magics) needs access to it.
2884 2890 self.sys_excepthook = old_excepthook
2885 2891 outflag = True # happens in more places, so it's easier as default
2886 2892 try:
2887 2893 try:
2888 2894 self.hooks.pre_run_code_hook()
2889 2895 #rprint('Running code', repr(code_obj)) # dbg
2890 2896 exec(code_obj, self.user_global_ns, self.user_ns)
2891 2897 finally:
2892 2898 # Reset our crash handler in place
2893 2899 sys.excepthook = old_excepthook
2894 2900 except SystemExit as e:
2895 2901 if result is not None:
2896 2902 result.error_in_exec = e
2897 2903 self.showtraceback(exception_only=True)
2898 2904 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2899 2905 except self.custom_exceptions:
2900 2906 etype, value, tb = sys.exc_info()
2901 2907 if result is not None:
2902 2908 result.error_in_exec = value
2903 2909 self.CustomTB(etype, value, tb)
2904 2910 except:
2905 2911 if result is not None:
2906 2912 result.error_in_exec = sys.exc_info()[1]
2907 2913 self.showtraceback(running_compiled_code=True)
2908 2914 else:
2909 2915 outflag = False
2910 2916 return outflag
2911 2917
2912 2918 # For backwards compatibility
2913 2919 runcode = run_code
2914 2920
2915 2921 #-------------------------------------------------------------------------
2916 2922 # Things related to GUI support and pylab
2917 2923 #-------------------------------------------------------------------------
2918 2924
2919 2925 active_eventloop = None
2920 2926
2921 2927 def enable_gui(self, gui=None):
2922 2928 raise NotImplementedError('Implement enable_gui in a subclass')
2923 2929
2924 2930 def enable_matplotlib(self, gui=None):
2925 2931 """Enable interactive matplotlib and inline figure support.
2926 2932
2927 2933 This takes the following steps:
2928 2934
2929 2935 1. select the appropriate eventloop and matplotlib backend
2930 2936 2. set up matplotlib for interactive use with that backend
2931 2937 3. configure formatters for inline figure display
2932 2938 4. enable the selected gui eventloop
2933 2939
2934 2940 Parameters
2935 2941 ----------
2936 2942 gui : optional, string
2937 2943 If given, dictates the choice of matplotlib GUI backend to use
2938 2944 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2939 2945 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2940 2946 matplotlib (as dictated by the matplotlib build-time options plus the
2941 2947 user's matplotlibrc configuration file). Note that not all backends
2942 2948 make sense in all contexts, for example a terminal ipython can't
2943 2949 display figures inline.
2944 2950 """
2945 2951 from IPython.core import pylabtools as pt
2946 2952 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2947 2953
2948 2954 if gui != 'inline':
2949 2955 # If we have our first gui selection, store it
2950 2956 if self.pylab_gui_select is None:
2951 2957 self.pylab_gui_select = gui
2952 2958 # Otherwise if they are different
2953 2959 elif gui != self.pylab_gui_select:
2954 2960 print('Warning: Cannot change to a different GUI toolkit: %s.'
2955 2961 ' Using %s instead.' % (gui, self.pylab_gui_select))
2956 2962 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2957 2963
2958 2964 pt.activate_matplotlib(backend)
2959 2965 pt.configure_inline_support(self, backend)
2960 2966
2961 2967 # Now we must activate the gui pylab wants to use, and fix %run to take
2962 2968 # plot updates into account
2963 2969 self.enable_gui(gui)
2964 2970 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2965 2971 pt.mpl_runner(self.safe_execfile)
2966 2972
2967 2973 return gui, backend
2968 2974
2969 2975 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2970 2976 """Activate pylab support at runtime.
2971 2977
2972 2978 This turns on support for matplotlib, preloads into the interactive
2973 2979 namespace all of numpy and pylab, and configures IPython to correctly
2974 2980 interact with the GUI event loop. The GUI backend to be used can be
2975 2981 optionally selected with the optional ``gui`` argument.
2976 2982
2977 2983 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2978 2984
2979 2985 Parameters
2980 2986 ----------
2981 2987 gui : optional, string
2982 2988 If given, dictates the choice of matplotlib GUI backend to use
2983 2989 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2984 2990 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2985 2991 matplotlib (as dictated by the matplotlib build-time options plus the
2986 2992 user's matplotlibrc configuration file). Note that not all backends
2987 2993 make sense in all contexts, for example a terminal ipython can't
2988 2994 display figures inline.
2989 2995 import_all : optional, bool, default: True
2990 2996 Whether to do `from numpy import *` and `from pylab import *`
2991 2997 in addition to module imports.
2992 2998 welcome_message : deprecated
2993 2999 This argument is ignored, no welcome message will be displayed.
2994 3000 """
2995 3001 from IPython.core.pylabtools import import_pylab
2996 3002
2997 3003 gui, backend = self.enable_matplotlib(gui)
2998 3004
2999 3005 # We want to prevent the loading of pylab to pollute the user's
3000 3006 # namespace as shown by the %who* magics, so we execute the activation
3001 3007 # code in an empty namespace, and we update *both* user_ns and
3002 3008 # user_ns_hidden with this information.
3003 3009 ns = {}
3004 3010 import_pylab(ns, import_all)
3005 3011 # warn about clobbered names
3006 3012 ignored = {"__builtins__"}
3007 3013 both = set(ns).intersection(self.user_ns).difference(ignored)
3008 3014 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3009 3015 self.user_ns.update(ns)
3010 3016 self.user_ns_hidden.update(ns)
3011 3017 return gui, backend, clobbered
3012 3018
3013 3019 #-------------------------------------------------------------------------
3014 3020 # Utilities
3015 3021 #-------------------------------------------------------------------------
3016 3022
3017 3023 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3018 3024 """Expand python variables in a string.
3019 3025
3020 3026 The depth argument indicates how many frames above the caller should
3021 3027 be walked to look for the local namespace where to expand variables.
3022 3028
3023 3029 The global namespace for expansion is always the user's interactive
3024 3030 namespace.
3025 3031 """
3026 3032 ns = self.user_ns.copy()
3027 3033 try:
3028 3034 frame = sys._getframe(depth+1)
3029 3035 except ValueError:
3030 3036 # This is thrown if there aren't that many frames on the stack,
3031 3037 # e.g. if a script called run_line_magic() directly.
3032 3038 pass
3033 3039 else:
3034 3040 ns.update(frame.f_locals)
3035 3041
3036 3042 try:
3037 3043 # We have to use .vformat() here, because 'self' is a valid and common
3038 3044 # name, and expanding **ns for .format() would make it collide with
3039 3045 # the 'self' argument of the method.
3040 3046 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3041 3047 except Exception:
3042 3048 # if formatter couldn't format, just let it go untransformed
3043 3049 pass
3044 3050 return cmd
3045 3051
3046 3052 def mktempfile(self, data=None, prefix='ipython_edit_'):
3047 3053 """Make a new tempfile and return its filename.
3048 3054
3049 3055 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3050 3056 but it registers the created filename internally so ipython cleans it up
3051 3057 at exit time.
3052 3058
3053 3059 Optional inputs:
3054 3060
3055 3061 - data(None): if data is given, it gets written out to the temp file
3056 3062 immediately, and the file is closed again."""
3057 3063
3058 3064 dirname = tempfile.mkdtemp(prefix=prefix)
3059 3065 self.tempdirs.append(dirname)
3060 3066
3061 3067 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3062 3068 os.close(handle) # On Windows, there can only be one open handle on a file
3063 3069 self.tempfiles.append(filename)
3064 3070
3065 3071 if data:
3066 3072 tmp_file = open(filename,'w')
3067 3073 tmp_file.write(data)
3068 3074 tmp_file.close()
3069 3075 return filename
3070 3076
3071 3077 @undoc
3072 3078 def write(self,data):
3073 3079 """DEPRECATED: Write a string to the default output"""
3074 3080 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3075 3081 DeprecationWarning, stacklevel=2)
3076 3082 sys.stdout.write(data)
3077 3083
3078 3084 @undoc
3079 3085 def write_err(self,data):
3080 3086 """DEPRECATED: Write a string to the default error output"""
3081 3087 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3082 3088 DeprecationWarning, stacklevel=2)
3083 3089 sys.stderr.write(data)
3084 3090
3085 3091 def ask_yes_no(self, prompt, default=None, interrupt=None):
3086 3092 if self.quiet:
3087 3093 return True
3088 3094 return ask_yes_no(prompt,default,interrupt)
3089 3095
3090 3096 def show_usage(self):
3091 3097 """Show a usage message"""
3092 3098 page.page(IPython.core.usage.interactive_usage)
3093 3099
3094 3100 def extract_input_lines(self, range_str, raw=False):
3095 3101 """Return as a string a set of input history slices.
3096 3102
3097 3103 Parameters
3098 3104 ----------
3099 3105 range_str : string
3100 3106 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3101 3107 since this function is for use by magic functions which get their
3102 3108 arguments as strings. The number before the / is the session
3103 3109 number: ~n goes n back from the current session.
3104 3110
3105 3111 raw : bool, optional
3106 3112 By default, the processed input is used. If this is true, the raw
3107 3113 input history is used instead.
3108 3114
3109 3115 Notes
3110 3116 -----
3111 3117
3112 3118 Slices can be described with two notations:
3113 3119
3114 3120 * ``N:M`` -> standard python form, means including items N...(M-1).
3115 3121 * ``N-M`` -> include items N..M (closed endpoint).
3116 3122 """
3117 3123 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3118 3124 return "\n".join(x for _, _, x in lines)
3119 3125
3120 3126 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3121 3127 """Get a code string from history, file, url, or a string or macro.
3122 3128
3123 3129 This is mainly used by magic functions.
3124 3130
3125 3131 Parameters
3126 3132 ----------
3127 3133
3128 3134 target : str
3129 3135
3130 3136 A string specifying code to retrieve. This will be tried respectively
3131 3137 as: ranges of input history (see %history for syntax), url,
3132 3138 corresponding .py file, filename, or an expression evaluating to a
3133 3139 string or Macro in the user namespace.
3134 3140
3135 3141 raw : bool
3136 3142 If true (default), retrieve raw history. Has no effect on the other
3137 3143 retrieval mechanisms.
3138 3144
3139 3145 py_only : bool (default False)
3140 3146 Only try to fetch python code, do not try alternative methods to decode file
3141 3147 if unicode fails.
3142 3148
3143 3149 Returns
3144 3150 -------
3145 3151 A string of code.
3146 3152
3147 3153 ValueError is raised if nothing is found, and TypeError if it evaluates
3148 3154 to an object of another type. In each case, .args[0] is a printable
3149 3155 message.
3150 3156 """
3151 3157 code = self.extract_input_lines(target, raw=raw) # Grab history
3152 3158 if code:
3153 3159 return code
3154 3160 try:
3155 3161 if target.startswith(('http://', 'https://')):
3156 3162 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3157 3163 except UnicodeDecodeError:
3158 3164 if not py_only :
3159 3165 # Deferred import
3160 3166 from urllib.request import urlopen
3161 3167 response = urlopen(target)
3162 3168 return response.read().decode('latin1')
3163 3169 raise ValueError(("'%s' seem to be unreadable.") % target)
3164 3170
3165 3171 potential_target = [target]
3166 3172 try :
3167 3173 potential_target.insert(0,get_py_filename(target))
3168 3174 except IOError:
3169 3175 pass
3170 3176
3171 3177 for tgt in potential_target :
3172 3178 if os.path.isfile(tgt): # Read file
3173 3179 try :
3174 3180 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3175 3181 except UnicodeDecodeError :
3176 3182 if not py_only :
3177 3183 with io_open(tgt,'r', encoding='latin1') as f :
3178 3184 return f.read()
3179 3185 raise ValueError(("'%s' seem to be unreadable.") % target)
3180 3186 elif os.path.isdir(os.path.expanduser(tgt)):
3181 3187 raise ValueError("'%s' is a directory, not a regular file." % target)
3182 3188
3183 3189 if search_ns:
3184 3190 # Inspect namespace to load object source
3185 3191 object_info = self.object_inspect(target, detail_level=1)
3186 3192 if object_info['found'] and object_info['source']:
3187 3193 return object_info['source']
3188 3194
3189 3195 try: # User namespace
3190 3196 codeobj = eval(target, self.user_ns)
3191 3197 except Exception:
3192 3198 raise ValueError(("'%s' was not found in history, as a file, url, "
3193 3199 "nor in the user namespace.") % target)
3194 3200
3195 3201 if isinstance(codeobj, str):
3196 3202 return codeobj
3197 3203 elif isinstance(codeobj, Macro):
3198 3204 return codeobj.value
3199 3205
3200 3206 raise TypeError("%s is neither a string nor a macro." % target,
3201 3207 codeobj)
3202 3208
3203 3209 #-------------------------------------------------------------------------
3204 3210 # Things related to IPython exiting
3205 3211 #-------------------------------------------------------------------------
3206 3212 def atexit_operations(self):
3207 3213 """This will be executed at the time of exit.
3208 3214
3209 3215 Cleanup operations and saving of persistent data that is done
3210 3216 unconditionally by IPython should be performed here.
3211 3217
3212 3218 For things that may depend on startup flags or platform specifics (such
3213 3219 as having readline or not), register a separate atexit function in the
3214 3220 code that has the appropriate information, rather than trying to
3215 3221 clutter
3216 3222 """
3217 3223 # Close the history session (this stores the end time and line count)
3218 3224 # this must be *before* the tempfile cleanup, in case of temporary
3219 3225 # history db
3220 3226 self.history_manager.end_session()
3221 3227
3222 3228 # Cleanup all tempfiles and folders left around
3223 3229 for tfile in self.tempfiles:
3224 3230 try:
3225 3231 os.unlink(tfile)
3226 3232 except OSError:
3227 3233 pass
3228 3234
3229 3235 for tdir in self.tempdirs:
3230 3236 try:
3231 3237 os.rmdir(tdir)
3232 3238 except OSError:
3233 3239 pass
3234 3240
3235 3241 # Clear all user namespaces to release all references cleanly.
3236 3242 self.reset(new_session=False)
3237 3243
3238 3244 # Run user hooks
3239 3245 self.hooks.shutdown_hook()
3240 3246
3241 3247 def cleanup(self):
3242 3248 self.restore_sys_module_state()
3243 3249
3244 3250
3245 3251 # Overridden in terminal subclass to change prompts
3246 3252 def switch_doctest_mode(self, mode):
3247 3253 pass
3248 3254
3249 3255
3250 3256 class InteractiveShellABC(metaclass=abc.ABCMeta):
3251 3257 """An abstract base class for InteractiveShell."""
3252 3258
3253 3259 InteractiveShellABC.register(InteractiveShell)
@@ -1,318 +1,318 b''
1 1 """Implementation of magic functions related to History.
2 2 """
3 3 #-----------------------------------------------------------------------------
4 4 # Copyright (c) 2012, IPython Development Team.
5 5 #
6 6 # Distributed under the terms of the Modified BSD License.
7 7 #
8 8 # The full license is in the file COPYING.txt, distributed with this software.
9 9 #-----------------------------------------------------------------------------
10 10
11 11 #-----------------------------------------------------------------------------
12 12 # Imports
13 13 #-----------------------------------------------------------------------------
14 14
15 15 # Stdlib
16 16 import os
17 17 import sys
18 18 from io import open as io_open
19 19
20 20 # Our own packages
21 21 from IPython.core.error import StdinNotImplementedError
22 22 from IPython.core.magic import Magics, magics_class, line_magic
23 23 from IPython.core.magic_arguments import (argument, magic_arguments,
24 24 parse_argstring)
25 25 from IPython.testing.skipdoctest import skip_doctest
26 26 from IPython.utils import io
27 27
28 28 #-----------------------------------------------------------------------------
29 29 # Magics class implementation
30 30 #-----------------------------------------------------------------------------
31 31
32 32
33 33 _unspecified = object()
34 34
35 35
36 36 @magics_class
37 37 class HistoryMagics(Magics):
38 38
39 39 @magic_arguments()
40 40 @argument(
41 41 '-n', dest='print_nums', action='store_true', default=False,
42 42 help="""
43 43 print line numbers for each input.
44 44 This feature is only available if numbered prompts are in use.
45 45 """)
46 46 @argument(
47 47 '-o', dest='get_output', action='store_true', default=False,
48 48 help="also print outputs for each input.")
49 49 @argument(
50 50 '-p', dest='pyprompts', action='store_true', default=False,
51 51 help="""
52 52 print classic '>>>' python prompts before each input.
53 53 This is useful for making documentation, and in conjunction
54 54 with -o, for producing doctest-ready output.
55 55 """)
56 56 @argument(
57 57 '-t', dest='raw', action='store_false', default=True,
58 58 help="""
59 59 print the 'translated' history, as IPython understands it.
60 60 IPython filters your input and converts it all into valid Python
61 61 source before executing it (things like magics or aliases are turned
62 62 into function calls, for example). With this option, you'll see the
63 63 native history instead of the user-entered version: '%%cd /' will be
64 seen as 'get_ipython().magic("%%cd /")' instead of '%%cd /'.
64 seen as 'get_ipython().run_line_magic("cd", "/")' instead of '%%cd /'.
65 65 """)
66 66 @argument(
67 67 '-f', dest='filename',
68 68 help="""
69 69 FILENAME: instead of printing the output to the screen, redirect
70 70 it to the given file. The file is always overwritten, though *when
71 71 it can*, IPython asks for confirmation first. In particular, running
72 72 the command 'history -f FILENAME' from the IPython Notebook
73 73 interface will replace FILENAME even if it already exists *without*
74 74 confirmation.
75 75 """)
76 76 @argument(
77 77 '-g', dest='pattern', nargs='*', default=None,
78 78 help="""
79 79 treat the arg as a glob pattern to search for in (full) history.
80 80 This includes the saved history (almost all commands ever written).
81 81 The pattern may contain '?' to match one unknown character and '*'
82 82 to match any number of unknown characters. Use '%%hist -g' to show
83 83 full saved history (may be very long).
84 84 """)
85 85 @argument(
86 86 '-l', dest='limit', type=int, nargs='?', default=_unspecified,
87 87 help="""
88 88 get the last n lines from all sessions. Specify n as a single
89 89 arg, or the default is the last 10 lines.
90 90 """)
91 91 @argument(
92 92 '-u', dest='unique', action='store_true',
93 93 help="""
94 94 when searching history using `-g`, show only unique history.
95 95 """)
96 96 @argument('range', nargs='*')
97 97 @skip_doctest
98 98 @line_magic
99 99 def history(self, parameter_s = ''):
100 100 """Print input history (_i<n> variables), with most recent last.
101 101
102 102 By default, input history is printed without line numbers so it can be
103 103 directly pasted into an editor. Use -n to show them.
104 104
105 105 By default, all input history from the current session is displayed.
106 106 Ranges of history can be indicated using the syntax:
107 107
108 108 ``4``
109 109 Line 4, current session
110 110 ``4-6``
111 111 Lines 4-6, current session
112 112 ``243/1-5``
113 113 Lines 1-5, session 243
114 114 ``~2/7``
115 115 Line 7, session 2 before current
116 116 ``~8/1-~6/5``
117 117 From the first line of 8 sessions ago, to the fifth line of 6
118 118 sessions ago.
119 119
120 120 Multiple ranges can be entered, separated by spaces
121 121
122 122 The same syntax is used by %macro, %save, %edit, %rerun
123 123
124 124 Examples
125 125 --------
126 126 ::
127 127
128 128 In [6]: %history -n 4-6
129 129 4:a = 12
130 130 5:print a**2
131 131 6:%history -n 4-6
132 132
133 133 """
134 134
135 135 args = parse_argstring(self.history, parameter_s)
136 136
137 137 # For brevity
138 138 history_manager = self.shell.history_manager
139 139
140 140 def _format_lineno(session, line):
141 141 """Helper function to format line numbers properly."""
142 142 if session in (0, history_manager.session_number):
143 143 return str(line)
144 144 return "%s/%s" % (session, line)
145 145
146 146 # Check if output to specific file was requested.
147 147 outfname = args.filename
148 148 if not outfname:
149 149 outfile = sys.stdout # default
150 150 # We don't want to close stdout at the end!
151 151 close_at_end = False
152 152 else:
153 153 if os.path.exists(outfname):
154 154 try:
155 155 ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
156 156 except StdinNotImplementedError:
157 157 ans = True
158 158 if not ans:
159 159 print('Aborting.')
160 160 return
161 161 print("Overwriting file.")
162 162 outfile = io_open(outfname, 'w', encoding='utf-8')
163 163 close_at_end = True
164 164
165 165 print_nums = args.print_nums
166 166 get_output = args.get_output
167 167 pyprompts = args.pyprompts
168 168 raw = args.raw
169 169
170 170 pattern = None
171 171 limit = None if args.limit is _unspecified else args.limit
172 172
173 173 if args.pattern is not None:
174 174 if args.pattern:
175 175 pattern = "*" + " ".join(args.pattern) + "*"
176 176 else:
177 177 pattern = "*"
178 178 hist = history_manager.search(pattern, raw=raw, output=get_output,
179 179 n=limit, unique=args.unique)
180 180 print_nums = True
181 181 elif args.limit is not _unspecified:
182 182 n = 10 if limit is None else limit
183 183 hist = history_manager.get_tail(n, raw=raw, output=get_output)
184 184 else:
185 185 if args.range: # Get history by ranges
186 186 hist = history_manager.get_range_by_str(" ".join(args.range),
187 187 raw, get_output)
188 188 else: # Just get history for the current session
189 189 hist = history_manager.get_range(raw=raw, output=get_output)
190 190
191 191 # We could be displaying the entire history, so let's not try to pull
192 192 # it into a list in memory. Anything that needs more space will just
193 193 # misalign.
194 194 width = 4
195 195
196 196 for session, lineno, inline in hist:
197 197 # Print user history with tabs expanded to 4 spaces. The GUI
198 198 # clients use hard tabs for easier usability in auto-indented code,
199 199 # but we want to produce PEP-8 compliant history for safe pasting
200 200 # into an editor.
201 201 if get_output:
202 202 inline, output = inline
203 203 inline = inline.expandtabs(4).rstrip()
204 204
205 205 multiline = "\n" in inline
206 206 line_sep = '\n' if multiline else ' '
207 207 if print_nums:
208 208 print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
209 209 line_sep), file=outfile, end=u'')
210 210 if pyprompts:
211 211 print(u">>> ", end=u"", file=outfile)
212 212 if multiline:
213 213 inline = "\n... ".join(inline.splitlines()) + "\n..."
214 214 print(inline, file=outfile)
215 215 if get_output and output:
216 216 print(output, file=outfile)
217 217
218 218 if close_at_end:
219 219 outfile.close()
220 220
221 221 @line_magic
222 222 def recall(self, arg):
223 223 r"""Repeat a command, or get command to input line for editing.
224 224
225 225 %recall and %rep are equivalent.
226 226
227 227 - %recall (no arguments):
228 228
229 229 Place a string version of last computation result (stored in the
230 230 special '_' variable) to the next input prompt. Allows you to create
231 231 elaborate command lines without using copy-paste::
232 232
233 233 In[1]: l = ["hei", "vaan"]
234 234 In[2]: "".join(l)
235 235 Out[2]: heivaan
236 236 In[3]: %recall
237 237 In[4]: heivaan_ <== cursor blinking
238 238
239 239 %recall 45
240 240
241 241 Place history line 45 on the next input prompt. Use %hist to find
242 242 out the number.
243 243
244 244 %recall 1-4
245 245
246 246 Combine the specified lines into one cell, and place it on the next
247 247 input prompt. See %history for the slice syntax.
248 248
249 249 %recall foo+bar
250 250
251 251 If foo+bar can be evaluated in the user namespace, the result is
252 252 placed at the next input prompt. Otherwise, the history is searched
253 253 for lines which contain that substring, and the most recent one is
254 254 placed at the next input prompt.
255 255 """
256 256 if not arg: # Last output
257 257 self.shell.set_next_input(str(self.shell.user_ns["_"]))
258 258 return
259 259 # Get history range
260 260 histlines = self.shell.history_manager.get_range_by_str(arg)
261 261 cmd = "\n".join(x[2] for x in histlines)
262 262 if cmd:
263 263 self.shell.set_next_input(cmd.rstrip())
264 264 return
265 265
266 266 try: # Variable in user namespace
267 267 cmd = str(eval(arg, self.shell.user_ns))
268 268 except Exception: # Search for term in history
269 269 histlines = self.shell.history_manager.search("*"+arg+"*")
270 270 for h in reversed([x[2] for x in histlines]):
271 271 if 'recall' in h or 'rep' in h:
272 272 continue
273 273 self.shell.set_next_input(h.rstrip())
274 274 return
275 275 else:
276 276 self.shell.set_next_input(cmd.rstrip())
277 277 print("Couldn't evaluate or find in history:", arg)
278 278
279 279 @line_magic
280 280 def rerun(self, parameter_s=''):
281 281 """Re-run previous input
282 282
283 283 By default, you can specify ranges of input history to be repeated
284 284 (as with %history). With no arguments, it will repeat the last line.
285 285
286 286 Options:
287 287
288 288 -l <n> : Repeat the last n lines of input, not including the
289 289 current command.
290 290
291 291 -g foo : Repeat the most recent line which contains foo
292 292 """
293 293 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
294 294 if "l" in opts: # Last n lines
295 295 n = int(opts['l'])
296 296 hist = self.shell.history_manager.get_tail(n)
297 297 elif "g" in opts: # Search
298 298 p = "*"+opts['g']+"*"
299 299 hist = list(self.shell.history_manager.search(p))
300 300 for l in reversed(hist):
301 301 if "rerun" not in l[2]:
302 302 hist = [l] # The last match which isn't a %rerun
303 303 break
304 304 else:
305 305 hist = [] # No matches except %rerun
306 306 elif args: # Specify history ranges
307 307 hist = self.shell.history_manager.get_range_by_str(args)
308 308 else: # Last line
309 309 hist = self.shell.history_manager.get_tail(1)
310 310 hist = [x[2] for x in hist]
311 311 if not hist:
312 312 print("No lines in history match specification")
313 313 return
314 314 histlines = "\n".join(hist)
315 315 print("=== Executing: ===")
316 316 print(histlines)
317 317 print("=== Output: ===")
318 318 self.shell.run_cell("\n".join(hist), store_history=False)
@@ -1,706 +1,709 b''
1 1 # encoding: utf-8
2 2 """
3 3 Prefiltering components.
4 4
5 5 Prefilters transform user input before it is exec'd by Python. These
6 6 transforms are used to implement additional syntax such as !ls and %magic.
7 7 """
8 8
9 9 # Copyright (c) IPython Development Team.
10 10 # Distributed under the terms of the Modified BSD License.
11 11
12 12 from keyword import iskeyword
13 13 import re
14 14
15 15 from IPython.core.autocall import IPyAutocall
16 16 from traitlets.config.configurable import Configurable
17 17 from IPython.core.inputsplitter import (
18 18 ESC_MAGIC,
19 19 ESC_QUOTE,
20 20 ESC_QUOTE2,
21 21 ESC_PAREN,
22 22 )
23 23 from IPython.core.macro import Macro
24 24 from IPython.core.splitinput import LineInfo
25 25
26 26 from traitlets import (
27 27 List, Integer, Unicode, Bool, Instance, CRegExp
28 28 )
29 29
30 30 #-----------------------------------------------------------------------------
31 31 # Global utilities, errors and constants
32 32 #-----------------------------------------------------------------------------
33 33
34 34
35 35 class PrefilterError(Exception):
36 36 pass
37 37
38 38
39 39 # RegExp to identify potential function names
40 40 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
41 41
42 42 # RegExp to exclude strings with this start from autocalling. In
43 43 # particular, all binary operators should be excluded, so that if foo is
44 44 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
45 45 # characters '!=()' don't need to be checked for, as the checkPythonChars
46 46 # routine explicitely does so, to catch direct calls and rebindings of
47 47 # existing names.
48 48
49 49 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
50 50 # it affects the rest of the group in square brackets.
51 51 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
52 52 r'|^is |^not |^in |^and |^or ')
53 53
54 54 # try to catch also methods for stuff in lists/tuples/dicts: off
55 55 # (experimental). For this to work, the line_split regexp would need
56 56 # to be modified so it wouldn't break things at '['. That line is
57 57 # nasty enough that I shouldn't change it until I can test it _well_.
58 58 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
59 59
60 60
61 61 # Handler Check Utilities
62 62 def is_shadowed(identifier, ip):
63 63 """Is the given identifier defined in one of the namespaces which shadow
64 64 the alias and magic namespaces? Note that an identifier is different
65 65 than ifun, because it can not contain a '.' character."""
66 66 # This is much safer than calling ofind, which can change state
67 67 return (identifier in ip.user_ns \
68 68 or identifier in ip.user_global_ns \
69 69 or identifier in ip.ns_table['builtin']\
70 70 or iskeyword(identifier))
71 71
72 72
73 73 #-----------------------------------------------------------------------------
74 74 # Main Prefilter manager
75 75 #-----------------------------------------------------------------------------
76 76
77 77
78 78 class PrefilterManager(Configurable):
79 79 """Main prefilter component.
80 80
81 81 The IPython prefilter is run on all user input before it is run. The
82 82 prefilter consumes lines of input and produces transformed lines of
83 83 input.
84 84
85 85 The iplementation consists of two phases:
86 86
87 87 1. Transformers
88 88 2. Checkers and handlers
89 89
90 90 Over time, we plan on deprecating the checkers and handlers and doing
91 91 everything in the transformers.
92 92
93 93 The transformers are instances of :class:`PrefilterTransformer` and have
94 94 a single method :meth:`transform` that takes a line and returns a
95 95 transformed line. The transformation can be accomplished using any
96 96 tool, but our current ones use regular expressions for speed.
97 97
98 98 After all the transformers have been run, the line is fed to the checkers,
99 99 which are instances of :class:`PrefilterChecker`. The line is passed to
100 100 the :meth:`check` method, which either returns `None` or a
101 101 :class:`PrefilterHandler` instance. If `None` is returned, the other
102 102 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
103 103 the line is passed to the :meth:`handle` method of the returned
104 104 handler and no further checkers are tried.
105 105
106 106 Both transformers and checkers have a `priority` attribute, that determines
107 107 the order in which they are called. Smaller priorities are tried first.
108 108
109 109 Both transformers and checkers also have `enabled` attribute, which is
110 110 a boolean that determines if the instance is used.
111 111
112 112 Users or developers can change the priority or enabled attribute of
113 113 transformers or checkers, but they must call the :meth:`sort_checkers`
114 114 or :meth:`sort_transformers` method after changing the priority.
115 115 """
116 116
117 117 multi_line_specials = Bool(True).tag(config=True)
118 118 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
119 119
120 120 def __init__(self, shell=None, **kwargs):
121 121 super(PrefilterManager, self).__init__(shell=shell, **kwargs)
122 122 self.shell = shell
123 123 self.init_transformers()
124 124 self.init_handlers()
125 125 self.init_checkers()
126 126
127 127 #-------------------------------------------------------------------------
128 128 # API for managing transformers
129 129 #-------------------------------------------------------------------------
130 130
131 131 def init_transformers(self):
132 132 """Create the default transformers."""
133 133 self._transformers = []
134 134 for transformer_cls in _default_transformers:
135 135 transformer_cls(
136 136 shell=self.shell, prefilter_manager=self, parent=self
137 137 )
138 138
139 139 def sort_transformers(self):
140 140 """Sort the transformers by priority.
141 141
142 142 This must be called after the priority of a transformer is changed.
143 143 The :meth:`register_transformer` method calls this automatically.
144 144 """
145 145 self._transformers.sort(key=lambda x: x.priority)
146 146
147 147 @property
148 148 def transformers(self):
149 149 """Return a list of checkers, sorted by priority."""
150 150 return self._transformers
151 151
152 152 def register_transformer(self, transformer):
153 153 """Register a transformer instance."""
154 154 if transformer not in self._transformers:
155 155 self._transformers.append(transformer)
156 156 self.sort_transformers()
157 157
158 158 def unregister_transformer(self, transformer):
159 159 """Unregister a transformer instance."""
160 160 if transformer in self._transformers:
161 161 self._transformers.remove(transformer)
162 162
163 163 #-------------------------------------------------------------------------
164 164 # API for managing checkers
165 165 #-------------------------------------------------------------------------
166 166
167 167 def init_checkers(self):
168 168 """Create the default checkers."""
169 169 self._checkers = []
170 170 for checker in _default_checkers:
171 171 checker(
172 172 shell=self.shell, prefilter_manager=self, parent=self
173 173 )
174 174
175 175 def sort_checkers(self):
176 176 """Sort the checkers by priority.
177 177
178 178 This must be called after the priority of a checker is changed.
179 179 The :meth:`register_checker` method calls this automatically.
180 180 """
181 181 self._checkers.sort(key=lambda x: x.priority)
182 182
183 183 @property
184 184 def checkers(self):
185 185 """Return a list of checkers, sorted by priority."""
186 186 return self._checkers
187 187
188 188 def register_checker(self, checker):
189 189 """Register a checker instance."""
190 190 if checker not in self._checkers:
191 191 self._checkers.append(checker)
192 192 self.sort_checkers()
193 193
194 194 def unregister_checker(self, checker):
195 195 """Unregister a checker instance."""
196 196 if checker in self._checkers:
197 197 self._checkers.remove(checker)
198 198
199 199 #-------------------------------------------------------------------------
200 200 # API for managing handlers
201 201 #-------------------------------------------------------------------------
202 202
203 203 def init_handlers(self):
204 204 """Create the default handlers."""
205 205 self._handlers = {}
206 206 self._esc_handlers = {}
207 207 for handler in _default_handlers:
208 208 handler(
209 209 shell=self.shell, prefilter_manager=self, parent=self
210 210 )
211 211
212 212 @property
213 213 def handlers(self):
214 214 """Return a dict of all the handlers."""
215 215 return self._handlers
216 216
217 217 def register_handler(self, name, handler, esc_strings):
218 218 """Register a handler instance by name with esc_strings."""
219 219 self._handlers[name] = handler
220 220 for esc_str in esc_strings:
221 221 self._esc_handlers[esc_str] = handler
222 222
223 223 def unregister_handler(self, name, handler, esc_strings):
224 224 """Unregister a handler instance by name with esc_strings."""
225 225 try:
226 226 del self._handlers[name]
227 227 except KeyError:
228 228 pass
229 229 for esc_str in esc_strings:
230 230 h = self._esc_handlers.get(esc_str)
231 231 if h is handler:
232 232 del self._esc_handlers[esc_str]
233 233
234 234 def get_handler_by_name(self, name):
235 235 """Get a handler by its name."""
236 236 return self._handlers.get(name)
237 237
238 238 def get_handler_by_esc(self, esc_str):
239 239 """Get a handler by its escape string."""
240 240 return self._esc_handlers.get(esc_str)
241 241
242 242 #-------------------------------------------------------------------------
243 243 # Main prefiltering API
244 244 #-------------------------------------------------------------------------
245 245
246 246 def prefilter_line_info(self, line_info):
247 247 """Prefilter a line that has been converted to a LineInfo object.
248 248
249 249 This implements the checker/handler part of the prefilter pipe.
250 250 """
251 251 # print "prefilter_line_info: ", line_info
252 252 handler = self.find_handler(line_info)
253 253 return handler.handle(line_info)
254 254
255 255 def find_handler(self, line_info):
256 256 """Find a handler for the line_info by trying checkers."""
257 257 for checker in self.checkers:
258 258 if checker.enabled:
259 259 handler = checker.check(line_info)
260 260 if handler:
261 261 return handler
262 262 return self.get_handler_by_name('normal')
263 263
264 264 def transform_line(self, line, continue_prompt):
265 265 """Calls the enabled transformers in order of increasing priority."""
266 266 for transformer in self.transformers:
267 267 if transformer.enabled:
268 268 line = transformer.transform(line, continue_prompt)
269 269 return line
270 270
271 271 def prefilter_line(self, line, continue_prompt=False):
272 272 """Prefilter a single input line as text.
273 273
274 274 This method prefilters a single line of text by calling the
275 275 transformers and then the checkers/handlers.
276 276 """
277 277
278 278 # print "prefilter_line: ", line, continue_prompt
279 279 # All handlers *must* return a value, even if it's blank ('').
280 280
281 281 # save the line away in case we crash, so the post-mortem handler can
282 282 # record it
283 283 self.shell._last_input_line = line
284 284
285 285 if not line:
286 286 # Return immediately on purely empty lines, so that if the user
287 287 # previously typed some whitespace that started a continuation
288 288 # prompt, he can break out of that loop with just an empty line.
289 289 # This is how the default python prompt works.
290 290 return ''
291 291
292 292 # At this point, we invoke our transformers.
293 293 if not continue_prompt or (continue_prompt and self.multi_line_specials):
294 294 line = self.transform_line(line, continue_prompt)
295 295
296 296 # Now we compute line_info for the checkers and handlers
297 297 line_info = LineInfo(line, continue_prompt)
298 298
299 299 # the input history needs to track even empty lines
300 300 stripped = line.strip()
301 301
302 302 normal_handler = self.get_handler_by_name('normal')
303 303 if not stripped:
304 304 return normal_handler.handle(line_info)
305 305
306 306 # special handlers are only allowed for single line statements
307 307 if continue_prompt and not self.multi_line_specials:
308 308 return normal_handler.handle(line_info)
309 309
310 310 prefiltered = self.prefilter_line_info(line_info)
311 311 # print "prefiltered line: %r" % prefiltered
312 312 return prefiltered
313 313
314 314 def prefilter_lines(self, lines, continue_prompt=False):
315 315 """Prefilter multiple input lines of text.
316 316
317 317 This is the main entry point for prefiltering multiple lines of
318 318 input. This simply calls :meth:`prefilter_line` for each line of
319 319 input.
320 320
321 321 This covers cases where there are multiple lines in the user entry,
322 322 which is the case when the user goes back to a multiline history
323 323 entry and presses enter.
324 324 """
325 325 llines = lines.rstrip('\n').split('\n')
326 326 # We can get multiple lines in one shot, where multiline input 'blends'
327 327 # into one line, in cases like recalling from the readline history
328 328 # buffer. We need to make sure that in such cases, we correctly
329 329 # communicate downstream which line is first and which are continuation
330 330 # ones.
331 331 if len(llines) > 1:
332 332 out = '\n'.join([self.prefilter_line(line, lnum>0)
333 333 for lnum, line in enumerate(llines) ])
334 334 else:
335 335 out = self.prefilter_line(llines[0], continue_prompt)
336 336
337 337 return out
338 338
339 339 #-----------------------------------------------------------------------------
340 340 # Prefilter transformers
341 341 #-----------------------------------------------------------------------------
342 342
343 343
344 344 class PrefilterTransformer(Configurable):
345 345 """Transform a line of user input."""
346 346
347 347 priority = Integer(100).tag(config=True)
348 348 # Transformers don't currently use shell or prefilter_manager, but as we
349 349 # move away from checkers and handlers, they will need them.
350 350 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
351 351 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
352 352 enabled = Bool(True).tag(config=True)
353 353
354 354 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
355 355 super(PrefilterTransformer, self).__init__(
356 356 shell=shell, prefilter_manager=prefilter_manager, **kwargs
357 357 )
358 358 self.prefilter_manager.register_transformer(self)
359 359
360 360 def transform(self, line, continue_prompt):
361 361 """Transform a line, returning the new one."""
362 362 return None
363 363
364 364 def __repr__(self):
365 365 return "<%s(priority=%r, enabled=%r)>" % (
366 366 self.__class__.__name__, self.priority, self.enabled)
367 367
368 368
369 369 #-----------------------------------------------------------------------------
370 370 # Prefilter checkers
371 371 #-----------------------------------------------------------------------------
372 372
373 373
374 374 class PrefilterChecker(Configurable):
375 375 """Inspect an input line and return a handler for that line."""
376 376
377 377 priority = Integer(100).tag(config=True)
378 378 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
379 379 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
380 380 enabled = Bool(True).tag(config=True)
381 381
382 382 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
383 383 super(PrefilterChecker, self).__init__(
384 384 shell=shell, prefilter_manager=prefilter_manager, **kwargs
385 385 )
386 386 self.prefilter_manager.register_checker(self)
387 387
388 388 def check(self, line_info):
389 389 """Inspect line_info and return a handler instance or None."""
390 390 return None
391 391
392 392 def __repr__(self):
393 393 return "<%s(priority=%r, enabled=%r)>" % (
394 394 self.__class__.__name__, self.priority, self.enabled)
395 395
396 396
397 397 class EmacsChecker(PrefilterChecker):
398 398
399 399 priority = Integer(100).tag(config=True)
400 400 enabled = Bool(False).tag(config=True)
401 401
402 402 def check(self, line_info):
403 403 "Emacs ipython-mode tags certain input lines."
404 404 if line_info.line.endswith('# PYTHON-MODE'):
405 405 return self.prefilter_manager.get_handler_by_name('emacs')
406 406 else:
407 407 return None
408 408
409 409
410 410 class MacroChecker(PrefilterChecker):
411 411
412 412 priority = Integer(250).tag(config=True)
413 413
414 414 def check(self, line_info):
415 415 obj = self.shell.user_ns.get(line_info.ifun)
416 416 if isinstance(obj, Macro):
417 417 return self.prefilter_manager.get_handler_by_name('macro')
418 418 else:
419 419 return None
420 420
421 421
422 422 class IPyAutocallChecker(PrefilterChecker):
423 423
424 424 priority = Integer(300).tag(config=True)
425 425
426 426 def check(self, line_info):
427 427 "Instances of IPyAutocall in user_ns get autocalled immediately"
428 428 obj = self.shell.user_ns.get(line_info.ifun, None)
429 429 if isinstance(obj, IPyAutocall):
430 430 obj.set_ip(self.shell)
431 431 return self.prefilter_manager.get_handler_by_name('auto')
432 432 else:
433 433 return None
434 434
435 435
436 436 class AssignmentChecker(PrefilterChecker):
437 437
438 438 priority = Integer(600).tag(config=True)
439 439
440 440 def check(self, line_info):
441 441 """Check to see if user is assigning to a var for the first time, in
442 442 which case we want to avoid any sort of automagic / autocall games.
443 443
444 444 This allows users to assign to either alias or magic names true python
445 445 variables (the magic/alias systems always take second seat to true
446 446 python code). E.g. ls='hi', or ls,that=1,2"""
447 447 if line_info.the_rest:
448 448 if line_info.the_rest[0] in '=,':
449 449 return self.prefilter_manager.get_handler_by_name('normal')
450 450 else:
451 451 return None
452 452
453 453
454 454 class AutoMagicChecker(PrefilterChecker):
455 455
456 456 priority = Integer(700).tag(config=True)
457 457
458 458 def check(self, line_info):
459 459 """If the ifun is magic, and automagic is on, run it. Note: normal,
460 460 non-auto magic would already have been triggered via '%' in
461 461 check_esc_chars. This just checks for automagic. Also, before
462 462 triggering the magic handler, make sure that there is nothing in the
463 463 user namespace which could shadow it."""
464 464 if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
465 465 return None
466 466
467 467 # We have a likely magic method. Make sure we should actually call it.
468 468 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
469 469 return None
470 470
471 471 head = line_info.ifun.split('.',1)[0]
472 472 if is_shadowed(head, self.shell):
473 473 return None
474 474
475 475 return self.prefilter_manager.get_handler_by_name('magic')
476 476
477 477
478 478 class PythonOpsChecker(PrefilterChecker):
479 479
480 480 priority = Integer(900).tag(config=True)
481 481
482 482 def check(self, line_info):
483 483 """If the 'rest' of the line begins with a function call or pretty much
484 484 any python operator, we should simply execute the line (regardless of
485 485 whether or not there's a possible autocall expansion). This avoids
486 486 spurious (and very confusing) geattr() accesses."""
487 487 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
488 488 return self.prefilter_manager.get_handler_by_name('normal')
489 489 else:
490 490 return None
491 491
492 492
493 493 class AutocallChecker(PrefilterChecker):
494 494
495 495 priority = Integer(1000).tag(config=True)
496 496
497 497 function_name_regexp = CRegExp(re_fun_name,
498 498 help="RegExp to identify potential function names."
499 499 ).tag(config=True)
500 500 exclude_regexp = CRegExp(re_exclude_auto,
501 501 help="RegExp to exclude strings with this start from autocalling."
502 502 ).tag(config=True)
503 503
504 504 def check(self, line_info):
505 505 "Check if the initial word/function is callable and autocall is on."
506 506 if not self.shell.autocall:
507 507 return None
508 508
509 509 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
510 510 if not oinfo['found']:
511 511 return None
512 512
513 513 ignored_funs = ['b', 'f', 'r', 'u', 'br', 'rb', 'fr', 'rf']
514 514 ifun = line_info.ifun
515 515 line = line_info.line
516 516 if ifun.lower() in ignored_funs and (line.startswith(ifun + "'") or line.startswith(ifun + '"')):
517 517 return None
518 518
519 519 if callable(oinfo['obj']) \
520 520 and (not self.exclude_regexp.match(line_info.the_rest)) \
521 521 and self.function_name_regexp.match(line_info.ifun):
522 522 return self.prefilter_manager.get_handler_by_name('auto')
523 523 else:
524 524 return None
525 525
526 526
527 527 #-----------------------------------------------------------------------------
528 528 # Prefilter handlers
529 529 #-----------------------------------------------------------------------------
530 530
531 531
532 532 class PrefilterHandler(Configurable):
533 533
534 534 handler_name = Unicode('normal')
535 535 esc_strings = List([])
536 536 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
537 537 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
538 538
539 539 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
540 540 super(PrefilterHandler, self).__init__(
541 541 shell=shell, prefilter_manager=prefilter_manager, **kwargs
542 542 )
543 543 self.prefilter_manager.register_handler(
544 544 self.handler_name,
545 545 self,
546 546 self.esc_strings
547 547 )
548 548
549 549 def handle(self, line_info):
550 550 # print "normal: ", line_info
551 551 """Handle normal input lines. Use as a template for handlers."""
552 552
553 553 # With autoindent on, we need some way to exit the input loop, and I
554 554 # don't want to force the user to have to backspace all the way to
555 555 # clear the line. The rule will be in this case, that either two
556 556 # lines of pure whitespace in a row, or a line of pure whitespace but
557 557 # of a size different to the indent level, will exit the input loop.
558 558 line = line_info.line
559 559 continue_prompt = line_info.continue_prompt
560 560
561 561 if (continue_prompt and
562 562 self.shell.autoindent and
563 563 line.isspace() and
564 564 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
565 565 line = ''
566 566
567 567 return line
568 568
569 569 def __str__(self):
570 570 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
571 571
572 572
573 573 class MacroHandler(PrefilterHandler):
574 574 handler_name = Unicode("macro")
575 575
576 576 def handle(self, line_info):
577 577 obj = self.shell.user_ns.get(line_info.ifun)
578 578 pre_space = line_info.pre_whitespace
579 579 line_sep = "\n" + pre_space
580 580 return pre_space + line_sep.join(obj.value.splitlines())
581 581
582 582
583 583 class MagicHandler(PrefilterHandler):
584 584
585 585 handler_name = Unicode('magic')
586 586 esc_strings = List([ESC_MAGIC])
587 587
588 588 def handle(self, line_info):
589 589 """Execute magic functions."""
590 590 ifun = line_info.ifun
591 591 the_rest = line_info.the_rest
592 cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace,
593 (ifun + " " + the_rest))
592 #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
593 t_arg_s = ifun + " " + the_rest
594 t_magic_name, _, t_magic_arg_s = t_arg_s.partition(' ')
595 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
596 cmd = '%sget_ipython().run_line_magic(%r, %r)' % (line_info.pre_whitespace, t_magic_name, t_magic_arg_s)
594 597 return cmd
595 598
596 599
597 600 class AutoHandler(PrefilterHandler):
598 601
599 602 handler_name = Unicode('auto')
600 603 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
601 604
602 605 def handle(self, line_info):
603 606 """Handle lines which can be auto-executed, quoting if requested."""
604 607 line = line_info.line
605 608 ifun = line_info.ifun
606 609 the_rest = line_info.the_rest
607 610 esc = line_info.esc
608 611 continue_prompt = line_info.continue_prompt
609 612 obj = line_info.ofind(self.shell)['obj']
610 613
611 614 # This should only be active for single-line input!
612 615 if continue_prompt:
613 616 return line
614 617
615 618 force_auto = isinstance(obj, IPyAutocall)
616 619
617 620 # User objects sometimes raise exceptions on attribute access other
618 621 # than AttributeError (we've seen it in the past), so it's safest to be
619 622 # ultra-conservative here and catch all.
620 623 try:
621 624 auto_rewrite = obj.rewrite
622 625 except Exception:
623 626 auto_rewrite = True
624 627
625 628 if esc == ESC_QUOTE:
626 629 # Auto-quote splitting on whitespace
627 630 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
628 631 elif esc == ESC_QUOTE2:
629 632 # Auto-quote whole string
630 633 newcmd = '%s("%s")' % (ifun,the_rest)
631 634 elif esc == ESC_PAREN:
632 635 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
633 636 else:
634 637 # Auto-paren.
635 638 if force_auto:
636 639 # Don't rewrite if it is already a call.
637 640 do_rewrite = not the_rest.startswith('(')
638 641 else:
639 642 if not the_rest:
640 643 # We only apply it to argument-less calls if the autocall
641 644 # parameter is set to 2.
642 645 do_rewrite = (self.shell.autocall >= 2)
643 646 elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
644 647 # Don't autocall in this case: item access for an object
645 648 # which is BOTH callable and implements __getitem__.
646 649 do_rewrite = False
647 650 else:
648 651 do_rewrite = True
649 652
650 653 # Figure out the rewritten command
651 654 if do_rewrite:
652 655 if the_rest.endswith(';'):
653 656 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
654 657 else:
655 658 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
656 659 else:
657 660 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
658 661 return normal_handler.handle(line_info)
659 662
660 663 # Display the rewritten call
661 664 if auto_rewrite:
662 665 self.shell.auto_rewrite_input(newcmd)
663 666
664 667 return newcmd
665 668
666 669
667 670 class EmacsHandler(PrefilterHandler):
668 671
669 672 handler_name = Unicode('emacs')
670 673 esc_strings = List([])
671 674
672 675 def handle(self, line_info):
673 676 """Handle input lines marked by python-mode."""
674 677
675 678 # Currently, nothing is done. Later more functionality can be added
676 679 # here if needed.
677 680
678 681 # The input cache shouldn't be updated
679 682 return line_info.line
680 683
681 684
682 685 #-----------------------------------------------------------------------------
683 686 # Defaults
684 687 #-----------------------------------------------------------------------------
685 688
686 689
687 690 _default_transformers = [
688 691 ]
689 692
690 693 _default_checkers = [
691 694 EmacsChecker,
692 695 MacroChecker,
693 696 IPyAutocallChecker,
694 697 AssignmentChecker,
695 698 AutoMagicChecker,
696 699 PythonOpsChecker,
697 700 AutocallChecker
698 701 ]
699 702
700 703 _default_handlers = [
701 704 PrefilterHandler,
702 705 MacroHandler,
703 706 MagicHandler,
704 707 AutoHandler,
705 708 EmacsHandler
706 709 ]
@@ -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().magic({u}'lsmagic ')"), # 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 ("%ls foo", "get_ipython().magic(%r)" % u'ls foo#'),
483 ("!ls foo\n%ls bar", "get_ipython().system(%r)\nget_ipython().magic(%r)" % (
484 u'ls foo#', u'ls bar#'
482 ("%ls foo", "get_ipython().run_line_magic(%r, %r)" % (u'ls', u'foo#')),
483 ("!ls foo\n%ls bar", "get_ipython().system(%r)\nget_ipython().run_line_magic(%r, %r)" % (
484 u'ls foo#', u'ls', u'bar#'
485 485 )),
486 ("1\n2\n3\n%ls foo\n4\n5", "1#\n2#\n3#\nget_ipython().magic(%r)\n4#\n5#" % u'ls foo#'),
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().magic({u}'who')"),
61 (u'b = %who', "b = get_ipython().magic({u}'who')"),
62 (u'c= %ls', "c = get_ipython().magic({u}'ls')"),
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().magic({u}'foo')"),
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().magic({u}'pinfo x1')"),
101 (u'??x2', "get_ipython().magic({u}'pinfo2 x2')"),
102 (u'?a.*s', "get_ipython().magic({u}'psearch a.*s')"),
103 (u'?%hist1', "get_ipython().magic({u}'pinfo %hist1')"),
104 (u'?%%hist2', "get_ipython().magic({u}'pinfo %%hist2')"),
105 (u'?abc = qwe', "get_ipython().magic({u}'pinfo 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().magic({u}'pinfo x3')"),
111 (u'x4??', "get_ipython().magic({u}'pinfo2 x4')"),
112 (u'%hist1?', "get_ipython().magic({u}'pinfo %hist1')"),
113 (u'%hist2??', "get_ipython().magic({u}'pinfo2 %hist2')"),
114 (u'%%hist3?', "get_ipython().magic({u}'pinfo %%hist3')"),
115 (u'%%hist4??', "get_ipython().magic({u}'pinfo2 %%hist4')"),
116 (u'f*?', "get_ipython().magic({u}'psearch f*')"),
117 (u'ax.*aspe*?', "get_ipython().magic({u}'psearch ax.*aspe*')"),
118 (u'a = abc?', "get_ipython().set_next_input({u}'a = abc');"
119 "get_ipython().magic({u}'pinfo abc')"),
120 (u'a = abc.qe??', "get_ipython().set_next_input({u}'a = abc.qe');"
121 "get_ipython().magic({u}'pinfo2 abc.qe')"),
122 (u'a = *.items?', "get_ipython().set_next_input({u}'a = *.items');"
123 "get_ipython().magic({u}'psearch *.items')"),
124 (u'plot(a?', "get_ipython().set_next_input({u}'plot(a');"
125 "get_ipython().magic({u}'pinfo 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().magic({u}'cd')"),
133 (u'%cd /home', "get_ipython().magic({u}'cd /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().magic({u}'cd C:\\\\User')"),
136 (u' %magic', " get_ipython().magic({u}'magic')"),
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().magic({u}'lsmagic')"),
167 (u'>>> %lsmagic', "get_ipython().magic({u}'lsmagic')"),
168 (u'In [2]: !ls', "get_ipython().system({u}'ls')"),
169 (u'In [3]: abs?', "get_ipython().magic({u}'pinfo abs')"),
170 (u'In [4]: b = %who', "b = get_ipython().magic({u}'who')"),
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().magic({u}'abc 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().magic({u}'abc 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().magic({u}'bc 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().magic({u}'bc 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