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