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