##// END OF EJS Templates
Merge pull request #10638 from adityausathe/master...
Thomas Kluyver -
r23765:c05f400f merge
parent child Browse files
Show More
@@ -1,525 +1,534 b''
1 """Input transformer classes to support IPython special syntax.
1 """Input transformer classes 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 """
5 """
6 import abc
6 import abc
7 import functools
7 import functools
8 import re
8 import re
9 from io import StringIO
9 from io import StringIO
10
10
11 from IPython.core.splitinput import LineInfo
11 from IPython.core.splitinput import LineInfo
12 from IPython.utils import tokenize2
12 from IPython.utils import tokenize2
13 from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
13 from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
14
14
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 # Globals
16 # Globals
17 #-----------------------------------------------------------------------------
17 #-----------------------------------------------------------------------------
18
18
19 # The escape sequences that define the syntax transformations IPython will
19 # The escape sequences that define the syntax transformations IPython will
20 # apply to user input. These can NOT be just changed here: many regular
20 # apply to user input. These can NOT be just changed here: many regular
21 # expressions and other parts of the code may use their hardcoded values, and
21 # expressions and other parts of the code may use their hardcoded values, and
22 # for all intents and purposes they constitute the 'IPython syntax', so they
22 # for all intents and purposes they constitute the 'IPython syntax', so they
23 # should be considered fixed.
23 # should be considered fixed.
24
24
25 ESC_SHELL = '!' # Send line to underlying system shell
25 ESC_SHELL = '!' # Send line to underlying system shell
26 ESC_SH_CAP = '!!' # Send line to system shell and capture output
26 ESC_SH_CAP = '!!' # Send line to system shell and capture output
27 ESC_HELP = '?' # Find information about object
27 ESC_HELP = '?' # Find information about object
28 ESC_HELP2 = '??' # Find extra-detailed information about object
28 ESC_HELP2 = '??' # Find extra-detailed information about object
29 ESC_MAGIC = '%' # Call magic function
29 ESC_MAGIC = '%' # Call magic function
30 ESC_MAGIC2 = '%%' # Call cell-magic function
30 ESC_MAGIC2 = '%%' # Call cell-magic function
31 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
31 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
32 ESC_QUOTE2 = ';' # Quote all args as a single string, call
32 ESC_QUOTE2 = ';' # Quote all args as a single string, call
33 ESC_PAREN = '/' # Call first argument with rest of line as arguments
33 ESC_PAREN = '/' # Call first argument with rest of line as arguments
34
34
35 ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\
35 ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\
36 ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\
36 ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\
37 ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
37 ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
38
38
39
39
40 class InputTransformer(metaclass=abc.ABCMeta):
40 class InputTransformer(metaclass=abc.ABCMeta):
41 """Abstract base class for line-based input transformers."""
41 """Abstract base class for line-based input transformers."""
42
42
43 @abc.abstractmethod
43 @abc.abstractmethod
44 def push(self, line):
44 def push(self, line):
45 """Send a line of input to the transformer, returning the transformed
45 """Send a line of input to the transformer, returning the transformed
46 input or None if the transformer is waiting for more input.
46 input or None if the transformer is waiting for more input.
47
47
48 Must be overridden by subclasses.
48 Must be overridden by subclasses.
49
49
50 Implementations may raise ``SyntaxError`` if the input is invalid. No
50 Implementations may raise ``SyntaxError`` if the input is invalid. No
51 other exceptions may be raised.
51 other exceptions may be raised.
52 """
52 """
53 pass
53 pass
54
54
55 @abc.abstractmethod
55 @abc.abstractmethod
56 def reset(self):
56 def reset(self):
57 """Return, transformed any lines that the transformer has accumulated,
57 """Return, transformed any lines that the transformer has accumulated,
58 and reset its internal state.
58 and reset its internal state.
59
59
60 Must be overridden by subclasses.
60 Must be overridden by subclasses.
61 """
61 """
62 pass
62 pass
63
63
64 @classmethod
64 @classmethod
65 def wrap(cls, func):
65 def wrap(cls, func):
66 """Can be used by subclasses as a decorator, to return a factory that
66 """Can be used by subclasses as a decorator, to return a factory that
67 will allow instantiation with the decorated object.
67 will allow instantiation with the decorated object.
68 """
68 """
69 @functools.wraps(func)
69 @functools.wraps(func)
70 def transformer_factory(**kwargs):
70 def transformer_factory(**kwargs):
71 return cls(func, **kwargs)
71 return cls(func, **kwargs)
72
72
73 return transformer_factory
73 return transformer_factory
74
74
75 class StatelessInputTransformer(InputTransformer):
75 class StatelessInputTransformer(InputTransformer):
76 """Wrapper for a stateless input transformer implemented as a function."""
76 """Wrapper for a stateless input transformer implemented as a function."""
77 def __init__(self, func):
77 def __init__(self, func):
78 self.func = func
78 self.func = func
79
79
80 def __repr__(self):
80 def __repr__(self):
81 return "StatelessInputTransformer(func={0!r})".format(self.func)
81 return "StatelessInputTransformer(func={0!r})".format(self.func)
82
82
83 def push(self, line):
83 def push(self, line):
84 """Send a line of input to the transformer, returning the
84 """Send a line of input to the transformer, returning the
85 transformed input."""
85 transformed input."""
86 return self.func(line)
86 return self.func(line)
87
87
88 def reset(self):
88 def reset(self):
89 """No-op - exists for compatibility."""
89 """No-op - exists for compatibility."""
90 pass
90 pass
91
91
92 class CoroutineInputTransformer(InputTransformer):
92 class CoroutineInputTransformer(InputTransformer):
93 """Wrapper for an input transformer implemented as a coroutine."""
93 """Wrapper for an input transformer implemented as a coroutine."""
94 def __init__(self, coro, **kwargs):
94 def __init__(self, coro, **kwargs):
95 # Prime it
95 # Prime it
96 self.coro = coro(**kwargs)
96 self.coro = coro(**kwargs)
97 next(self.coro)
97 next(self.coro)
98
98
99 def __repr__(self):
99 def __repr__(self):
100 return "CoroutineInputTransformer(coro={0!r})".format(self.coro)
100 return "CoroutineInputTransformer(coro={0!r})".format(self.coro)
101
101
102 def push(self, line):
102 def push(self, line):
103 """Send a line of input to the transformer, returning the
103 """Send a line of input to the transformer, returning the
104 transformed input or None if the transformer is waiting for more
104 transformed input or None if the transformer is waiting for more
105 input.
105 input.
106 """
106 """
107 return self.coro.send(line)
107 return self.coro.send(line)
108
108
109 def reset(self):
109 def reset(self):
110 """Return, transformed any lines that the transformer has
110 """Return, transformed any lines that the transformer has
111 accumulated, and reset its internal state.
111 accumulated, and reset its internal state.
112 """
112 """
113 return self.coro.send(None)
113 return self.coro.send(None)
114
114
115 class TokenInputTransformer(InputTransformer):
115 class TokenInputTransformer(InputTransformer):
116 """Wrapper for a token-based input transformer.
116 """Wrapper for a token-based input transformer.
117
117
118 func should accept a list of tokens (5-tuples, see tokenize docs), and
118 func should accept a list of tokens (5-tuples, see tokenize docs), and
119 return an iterable which can be passed to tokenize.untokenize().
119 return an iterable which can be passed to tokenize.untokenize().
120 """
120 """
121 def __init__(self, func):
121 def __init__(self, func):
122 self.func = func
122 self.func = func
123 self.buf = []
123 self.buf = []
124 self.reset_tokenizer()
124 self.reset_tokenizer()
125
125
126 def reset_tokenizer(self):
126 def reset_tokenizer(self):
127 it = iter(self.buf)
127 it = iter(self.buf)
128 self.tokenizer = generate_tokens(it.__next__)
128 self.tokenizer = generate_tokens(it.__next__)
129
129
130 def push(self, line):
130 def push(self, line):
131 self.buf.append(line + '\n')
131 self.buf.append(line + '\n')
132 if all(l.isspace() for l in self.buf):
132 if all(l.isspace() for l in self.buf):
133 return self.reset()
133 return self.reset()
134
134
135 tokens = []
135 tokens = []
136 stop_at_NL = False
136 stop_at_NL = False
137 try:
137 try:
138 for intok in self.tokenizer:
138 for intok in self.tokenizer:
139 tokens.append(intok)
139 tokens.append(intok)
140 t = intok[0]
140 t = intok[0]
141 if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL):
141 if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL):
142 # Stop before we try to pull a line we don't have yet
142 # Stop before we try to pull a line we don't have yet
143 break
143 break
144 elif t == tokenize2.ERRORTOKEN:
144 elif t == tokenize2.ERRORTOKEN:
145 stop_at_NL = True
145 stop_at_NL = True
146 except TokenError:
146 except TokenError:
147 # Multi-line statement - stop and try again with the next line
147 # Multi-line statement - stop and try again with the next line
148 self.reset_tokenizer()
148 self.reset_tokenizer()
149 return None
149 return None
150
150
151 return self.output(tokens)
151 return self.output(tokens)
152
152
153 def output(self, tokens):
153 def output(self, tokens):
154 self.buf.clear()
154 self.buf.clear()
155 self.reset_tokenizer()
155 self.reset_tokenizer()
156 return untokenize(self.func(tokens)).rstrip('\n')
156 return untokenize(self.func(tokens)).rstrip('\n')
157
157
158 def reset(self):
158 def reset(self):
159 l = ''.join(self.buf)
159 l = ''.join(self.buf)
160 self.buf.clear()
160 self.buf.clear()
161 self.reset_tokenizer()
161 self.reset_tokenizer()
162 if l:
162 if l:
163 return l.rstrip('\n')
163 return l.rstrip('\n')
164
164
165 class assemble_python_lines(TokenInputTransformer):
165 class assemble_python_lines(TokenInputTransformer):
166 def __init__(self):
166 def __init__(self):
167 super(assemble_python_lines, self).__init__(None)
167 super(assemble_python_lines, self).__init__(None)
168
168
169 def output(self, tokens):
169 def output(self, tokens):
170 return self.reset()
170 return self.reset()
171
171
172 @CoroutineInputTransformer.wrap
172 @CoroutineInputTransformer.wrap
173 def assemble_logical_lines():
173 def assemble_logical_lines():
174 """Join lines following explicit line continuations (\)"""
174 """Join lines following explicit line continuations (\)"""
175 line = ''
175 line = ''
176 while True:
176 while True:
177 line = (yield line)
177 line = (yield line)
178 if not line or line.isspace():
178 if not line or line.isspace():
179 continue
179 continue
180
180
181 parts = []
181 parts = []
182 while line is not None:
182 while line is not None:
183 if line.endswith('\\') and (not has_comment(line)):
183 if line.endswith('\\') and (not has_comment(line)):
184 parts.append(line[:-1])
184 parts.append(line[:-1])
185 line = (yield None) # Get another line
185 line = (yield None) # Get another line
186 else:
186 else:
187 parts.append(line)
187 parts.append(line)
188 break
188 break
189
189
190 # Output
190 # Output
191 line = ''.join(parts)
191 line = ''.join(parts)
192
192
193 # Utilities
193 # Utilities
194 def _make_help_call(target, esc, lspace, next_input=None):
194 def _make_help_call(target, esc, lspace, next_input=None):
195 """Prepares a pinfo(2)/psearch call from a target name and the escape
195 """Prepares a pinfo(2)/psearch call from a target name and the escape
196 (i.e. ? or ??)"""
196 (i.e. ? or ??)"""
197 method = 'pinfo2' if esc == '??' \
197 method = 'pinfo2' if esc == '??' \
198 else 'psearch' if '*' in target \
198 else 'psearch' if '*' in target \
199 else 'pinfo'
199 else 'pinfo'
200 arg = " ".join([method, target])
200 arg = " ".join([method, target])
201 #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
202 t_magic_name, _, t_magic_arg_s = arg.partition(' ')
203 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
201 if next_input is None:
204 if next_input is None:
202 return '%sget_ipython().magic(%r)' % (lspace, arg)
205 return '%sget_ipython().run_line_magic(%r, %r)' % (lspace, t_magic_name, t_magic_arg_s)
203 else:
206 else:
204 return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \
207 return '%sget_ipython().set_next_input(%r);get_ipython().run_line_magic(%r, %r)' % \
205 (lspace, next_input, arg)
208 (lspace, next_input, t_magic_name, t_magic_arg_s)
206
209
207 # These define the transformations for the different escape characters.
210 # These define the transformations for the different escape characters.
208 def _tr_system(line_info):
211 def _tr_system(line_info):
209 "Translate lines escaped with: !"
212 "Translate lines escaped with: !"
210 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
213 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
211 return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
214 return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
212
215
213 def _tr_system2(line_info):
216 def _tr_system2(line_info):
214 "Translate lines escaped with: !!"
217 "Translate lines escaped with: !!"
215 cmd = line_info.line.lstrip()[2:]
218 cmd = line_info.line.lstrip()[2:]
216 return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
219 return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
217
220
218 def _tr_help(line_info):
221 def _tr_help(line_info):
219 "Translate lines escaped with: ?/??"
222 "Translate lines escaped with: ?/??"
220 # A naked help line should just fire the intro help screen
223 # A naked help line should just fire the intro help screen
221 if not line_info.line[1:]:
224 if not line_info.line[1:]:
222 return 'get_ipython().show_usage()'
225 return 'get_ipython().show_usage()'
223
226
224 return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
227 return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
225
228
226 def _tr_magic(line_info):
229 def _tr_magic(line_info):
227 "Translate lines escaped with: %"
230 "Translate lines escaped with: %"
228 tpl = '%sget_ipython().magic(%r)'
231 tpl = '%sget_ipython().run_line_magic(%r, %r)'
229 if line_info.line.startswith(ESC_MAGIC2):
232 if line_info.line.startswith(ESC_MAGIC2):
230 return line_info.line
233 return line_info.line
231 cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
234 cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
232 return tpl % (line_info.pre, cmd)
235 #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
236 t_magic_name, _, t_magic_arg_s = cmd.partition(' ')
237 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
238 return tpl % (line_info.pre, t_magic_name, t_magic_arg_s)
233
239
234 def _tr_quote(line_info):
240 def _tr_quote(line_info):
235 "Translate lines escaped with: ,"
241 "Translate lines escaped with: ,"
236 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
242 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
237 '", "'.join(line_info.the_rest.split()) )
243 '", "'.join(line_info.the_rest.split()) )
238
244
239 def _tr_quote2(line_info):
245 def _tr_quote2(line_info):
240 "Translate lines escaped with: ;"
246 "Translate lines escaped with: ;"
241 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
247 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
242 line_info.the_rest)
248 line_info.the_rest)
243
249
244 def _tr_paren(line_info):
250 def _tr_paren(line_info):
245 "Translate lines escaped with: /"
251 "Translate lines escaped with: /"
246 return '%s%s(%s)' % (line_info.pre, line_info.ifun,
252 return '%s%s(%s)' % (line_info.pre, line_info.ifun,
247 ", ".join(line_info.the_rest.split()))
253 ", ".join(line_info.the_rest.split()))
248
254
249 tr = { ESC_SHELL : _tr_system,
255 tr = { ESC_SHELL : _tr_system,
250 ESC_SH_CAP : _tr_system2,
256 ESC_SH_CAP : _tr_system2,
251 ESC_HELP : _tr_help,
257 ESC_HELP : _tr_help,
252 ESC_HELP2 : _tr_help,
258 ESC_HELP2 : _tr_help,
253 ESC_MAGIC : _tr_magic,
259 ESC_MAGIC : _tr_magic,
254 ESC_QUOTE : _tr_quote,
260 ESC_QUOTE : _tr_quote,
255 ESC_QUOTE2 : _tr_quote2,
261 ESC_QUOTE2 : _tr_quote2,
256 ESC_PAREN : _tr_paren }
262 ESC_PAREN : _tr_paren }
257
263
258 @StatelessInputTransformer.wrap
264 @StatelessInputTransformer.wrap
259 def escaped_commands(line):
265 def escaped_commands(line):
260 """Transform escaped commands - %magic, !system, ?help + various autocalls.
266 """Transform escaped commands - %magic, !system, ?help + various autocalls.
261 """
267 """
262 if not line or line.isspace():
268 if not line or line.isspace():
263 return line
269 return line
264 lineinf = LineInfo(line)
270 lineinf = LineInfo(line)
265 if lineinf.esc not in tr:
271 if lineinf.esc not in tr:
266 return line
272 return line
267
273
268 return tr[lineinf.esc](lineinf)
274 return tr[lineinf.esc](lineinf)
269
275
270 _initial_space_re = re.compile(r'\s*')
276 _initial_space_re = re.compile(r'\s*')
271
277
272 _help_end_re = re.compile(r"""(%{0,2}
278 _help_end_re = re.compile(r"""(%{0,2}
273 [a-zA-Z_*][\w*]* # Variable name
279 [a-zA-Z_*][\w*]* # Variable name
274 (\.[a-zA-Z_*][\w*]*)* # .etc.etc
280 (\.[a-zA-Z_*][\w*]*)* # .etc.etc
275 )
281 )
276 (\?\??)$ # ? or ??
282 (\?\??)$ # ? or ??
277 """,
283 """,
278 re.VERBOSE)
284 re.VERBOSE)
279
285
280 # Extra pseudotokens for multiline strings and data structures
286 # Extra pseudotokens for multiline strings and data structures
281 _MULTILINE_STRING = object()
287 _MULTILINE_STRING = object()
282 _MULTILINE_STRUCTURE = object()
288 _MULTILINE_STRUCTURE = object()
283
289
284 def _line_tokens(line):
290 def _line_tokens(line):
285 """Helper for has_comment and ends_in_comment_or_string."""
291 """Helper for has_comment and ends_in_comment_or_string."""
286 readline = StringIO(line).readline
292 readline = StringIO(line).readline
287 toktypes = set()
293 toktypes = set()
288 try:
294 try:
289 for t in generate_tokens(readline):
295 for t in generate_tokens(readline):
290 toktypes.add(t[0])
296 toktypes.add(t[0])
291 except TokenError as e:
297 except TokenError as e:
292 # There are only two cases where a TokenError is raised.
298 # There are only two cases where a TokenError is raised.
293 if 'multi-line string' in e.args[0]:
299 if 'multi-line string' in e.args[0]:
294 toktypes.add(_MULTILINE_STRING)
300 toktypes.add(_MULTILINE_STRING)
295 else:
301 else:
296 toktypes.add(_MULTILINE_STRUCTURE)
302 toktypes.add(_MULTILINE_STRUCTURE)
297 return toktypes
303 return toktypes
298
304
299 def has_comment(src):
305 def has_comment(src):
300 """Indicate whether an input line has (i.e. ends in, or is) a comment.
306 """Indicate whether an input line has (i.e. ends in, or is) a comment.
301
307
302 This uses tokenize, so it can distinguish comments from # inside strings.
308 This uses tokenize, so it can distinguish comments from # inside strings.
303
309
304 Parameters
310 Parameters
305 ----------
311 ----------
306 src : string
312 src : string
307 A single line input string.
313 A single line input string.
308
314
309 Returns
315 Returns
310 -------
316 -------
311 comment : bool
317 comment : bool
312 True if source has a comment.
318 True if source has a comment.
313 """
319 """
314 return (tokenize2.COMMENT in _line_tokens(src))
320 return (tokenize2.COMMENT in _line_tokens(src))
315
321
316 def ends_in_comment_or_string(src):
322 def ends_in_comment_or_string(src):
317 """Indicates whether or not an input line ends in a comment or within
323 """Indicates whether or not an input line ends in a comment or within
318 a multiline string.
324 a multiline string.
319
325
320 Parameters
326 Parameters
321 ----------
327 ----------
322 src : string
328 src : string
323 A single line input string.
329 A single line input string.
324
330
325 Returns
331 Returns
326 -------
332 -------
327 comment : bool
333 comment : bool
328 True if source ends in a comment or multiline string.
334 True if source ends in a comment or multiline string.
329 """
335 """
330 toktypes = _line_tokens(src)
336 toktypes = _line_tokens(src)
331 return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes)
337 return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes)
332
338
333
339
334 @StatelessInputTransformer.wrap
340 @StatelessInputTransformer.wrap
335 def help_end(line):
341 def help_end(line):
336 """Translate lines with ?/?? at the end"""
342 """Translate lines with ?/?? at the end"""
337 m = _help_end_re.search(line)
343 m = _help_end_re.search(line)
338 if m is None or ends_in_comment_or_string(line):
344 if m is None or ends_in_comment_or_string(line):
339 return line
345 return line
340 target = m.group(1)
346 target = m.group(1)
341 esc = m.group(3)
347 esc = m.group(3)
342 lspace = _initial_space_re.match(line).group(0)
348 lspace = _initial_space_re.match(line).group(0)
343
349
344 # If we're mid-command, put it back on the next prompt for the user.
350 # If we're mid-command, put it back on the next prompt for the user.
345 next_input = line.rstrip('?') if line.strip() != m.group(0) else None
351 next_input = line.rstrip('?') if line.strip() != m.group(0) else None
346
352
347 return _make_help_call(target, esc, lspace, next_input)
353 return _make_help_call(target, esc, lspace, next_input)
348
354
349
355
350 @CoroutineInputTransformer.wrap
356 @CoroutineInputTransformer.wrap
351 def cellmagic(end_on_blank_line=False):
357 def cellmagic(end_on_blank_line=False):
352 """Captures & transforms cell magics.
358 """Captures & transforms cell magics.
353
359
354 After a cell magic is started, this stores up any lines it gets until it is
360 After a cell magic is started, this stores up any lines it gets until it is
355 reset (sent None).
361 reset (sent None).
356 """
362 """
357 tpl = 'get_ipython().run_cell_magic(%r, %r, %r)'
363 tpl = 'get_ipython().run_cell_magic(%r, %r, %r)'
358 cellmagic_help_re = re.compile('%%\w+\?')
364 cellmagic_help_re = re.compile('%%\w+\?')
359 line = ''
365 line = ''
360 while True:
366 while True:
361 line = (yield line)
367 line = (yield line)
362 # consume leading empty lines
368 # consume leading empty lines
363 while not line:
369 while not line:
364 line = (yield line)
370 line = (yield line)
365
371
366 if not line.startswith(ESC_MAGIC2):
372 if not line.startswith(ESC_MAGIC2):
367 # This isn't a cell magic, idle waiting for reset then start over
373 # This isn't a cell magic, idle waiting for reset then start over
368 while line is not None:
374 while line is not None:
369 line = (yield line)
375 line = (yield line)
370 continue
376 continue
371
377
372 if cellmagic_help_re.match(line):
378 if cellmagic_help_re.match(line):
373 # This case will be handled by help_end
379 # This case will be handled by help_end
374 continue
380 continue
375
381
376 first = line
382 first = line
377 body = []
383 body = []
378 line = (yield None)
384 line = (yield None)
379 while (line is not None) and \
385 while (line is not None) and \
380 ((line.strip() != '') or not end_on_blank_line):
386 ((line.strip() != '') or not end_on_blank_line):
381 body.append(line)
387 body.append(line)
382 line = (yield None)
388 line = (yield None)
383
389
384 # Output
390 # Output
385 magic_name, _, first = first.partition(' ')
391 magic_name, _, first = first.partition(' ')
386 magic_name = magic_name.lstrip(ESC_MAGIC2)
392 magic_name = magic_name.lstrip(ESC_MAGIC2)
387 line = tpl % (magic_name, first, u'\n'.join(body))
393 line = tpl % (magic_name, first, u'\n'.join(body))
388
394
389
395
390 def _strip_prompts(prompt_re, initial_re=None, turnoff_re=None):
396 def _strip_prompts(prompt_re, initial_re=None, turnoff_re=None):
391 """Remove matching input prompts from a block of input.
397 """Remove matching input prompts from a block of input.
392
398
393 Parameters
399 Parameters
394 ----------
400 ----------
395 prompt_re : regular expression
401 prompt_re : regular expression
396 A regular expression matching any input prompt (including continuation)
402 A regular expression matching any input prompt (including continuation)
397 initial_re : regular expression, optional
403 initial_re : regular expression, optional
398 A regular expression matching only the initial prompt, but not continuation.
404 A regular expression matching only the initial prompt, but not continuation.
399 If no initial expression is given, prompt_re will be used everywhere.
405 If no initial expression is given, prompt_re will be used everywhere.
400 Used mainly for plain Python prompts, where the continuation prompt
406 Used mainly for plain Python prompts, where the continuation prompt
401 ``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
407 ``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
402
408
403 If initial_re and prompt_re differ,
409 If initial_re and prompt_re differ,
404 only initial_re will be tested against the first line.
410 only initial_re will be tested against the first line.
405 If any prompt is found on the first two lines,
411 If any prompt is found on the first two lines,
406 prompts will be stripped from the rest of the block.
412 prompts will be stripped from the rest of the block.
407 """
413 """
408 if initial_re is None:
414 if initial_re is None:
409 initial_re = prompt_re
415 initial_re = prompt_re
410 line = ''
416 line = ''
411 while True:
417 while True:
412 line = (yield line)
418 line = (yield line)
413
419
414 # First line of cell
420 # First line of cell
415 if line is None:
421 if line is None:
416 continue
422 continue
417 out, n1 = initial_re.subn('', line, count=1)
423 out, n1 = initial_re.subn('', line, count=1)
418 if turnoff_re and not n1:
424 if turnoff_re and not n1:
419 if turnoff_re.match(line):
425 if turnoff_re.match(line):
420 # We're in e.g. a cell magic; disable this transformer for
426 # We're in e.g. a cell magic; disable this transformer for
421 # the rest of the cell.
427 # the rest of the cell.
422 while line is not None:
428 while line is not None:
423 line = (yield line)
429 line = (yield line)
424 continue
430 continue
425
431
426 line = (yield out)
432 line = (yield out)
427
433
428 if line is None:
434 if line is None:
429 continue
435 continue
430 # check for any prompt on the second line of the cell,
436 # check for any prompt on the second line of the cell,
431 # because people often copy from just after the first prompt,
437 # because people often copy from just after the first prompt,
432 # so we might not see it in the first line.
438 # so we might not see it in the first line.
433 out, n2 = prompt_re.subn('', line, count=1)
439 out, n2 = prompt_re.subn('', line, count=1)
434 line = (yield out)
440 line = (yield out)
435
441
436 if n1 or n2:
442 if n1 or n2:
437 # Found a prompt in the first two lines - check for it in
443 # Found a prompt in the first two lines - check for it in
438 # the rest of the cell as well.
444 # the rest of the cell as well.
439 while line is not None:
445 while line is not None:
440 line = (yield prompt_re.sub('', line, count=1))
446 line = (yield prompt_re.sub('', line, count=1))
441
447
442 else:
448 else:
443 # Prompts not in input - wait for reset
449 # Prompts not in input - wait for reset
444 while line is not None:
450 while line is not None:
445 line = (yield line)
451 line = (yield line)
446
452
447 @CoroutineInputTransformer.wrap
453 @CoroutineInputTransformer.wrap
448 def classic_prompt():
454 def classic_prompt():
449 """Strip the >>>/... prompts of the Python interactive shell."""
455 """Strip the >>>/... prompts of the Python interactive shell."""
450 # FIXME: non-capturing version (?:...) usable?
456 # FIXME: non-capturing version (?:...) usable?
451 prompt_re = re.compile(r'^(>>>|\.\.\.)( |$)')
457 prompt_re = re.compile(r'^(>>>|\.\.\.)( |$)')
452 initial_re = re.compile(r'^>>>( |$)')
458 initial_re = re.compile(r'^>>>( |$)')
453 # Any %magic/!system is IPython syntax, so we needn't look for >>> prompts
459 # Any %magic/!system is IPython syntax, so we needn't look for >>> prompts
454 turnoff_re = re.compile(r'^[%!]')
460 turnoff_re = re.compile(r'^[%!]')
455 return _strip_prompts(prompt_re, initial_re, turnoff_re)
461 return _strip_prompts(prompt_re, initial_re, turnoff_re)
456
462
457 @CoroutineInputTransformer.wrap
463 @CoroutineInputTransformer.wrap
458 def ipy_prompt():
464 def ipy_prompt():
459 """Strip IPython's In [1]:/...: prompts."""
465 """Strip IPython's In [1]:/...: prompts."""
460 # FIXME: non-capturing version (?:...) usable?
466 # FIXME: non-capturing version (?:...) usable?
461 prompt_re = re.compile(r'^(In \[\d+\]: |\s*\.{3,}: ?)')
467 prompt_re = re.compile(r'^(In \[\d+\]: |\s*\.{3,}: ?)')
462 # Disable prompt stripping inside cell magics
468 # Disable prompt stripping inside cell magics
463 turnoff_re = re.compile(r'^%%')
469 turnoff_re = re.compile(r'^%%')
464 return _strip_prompts(prompt_re, turnoff_re=turnoff_re)
470 return _strip_prompts(prompt_re, turnoff_re=turnoff_re)
465
471
466
472
467 @CoroutineInputTransformer.wrap
473 @CoroutineInputTransformer.wrap
468 def leading_indent():
474 def leading_indent():
469 """Remove leading indentation.
475 """Remove leading indentation.
470
476
471 If the first line starts with a spaces or tabs, the same whitespace will be
477 If the first line starts with a spaces or tabs, the same whitespace will be
472 removed from each following line until it is reset.
478 removed from each following line until it is reset.
473 """
479 """
474 space_re = re.compile(r'^[ \t]+')
480 space_re = re.compile(r'^[ \t]+')
475 line = ''
481 line = ''
476 while True:
482 while True:
477 line = (yield line)
483 line = (yield line)
478
484
479 if line is None:
485 if line is None:
480 continue
486 continue
481
487
482 m = space_re.match(line)
488 m = space_re.match(line)
483 if m:
489 if m:
484 space = m.group(0)
490 space = m.group(0)
485 while line is not None:
491 while line is not None:
486 if line.startswith(space):
492 if line.startswith(space):
487 line = line[len(space):]
493 line = line[len(space):]
488 line = (yield line)
494 line = (yield line)
489 else:
495 else:
490 # No leading spaces - wait for reset
496 # No leading spaces - wait for reset
491 while line is not None:
497 while line is not None:
492 line = (yield line)
498 line = (yield line)
493
499
494
500
495 _assign_pat = \
501 _assign_pat = \
496 r'''(?P<lhs>(\s*)
502 r'''(?P<lhs>(\s*)
497 ([\w\.]+) # Initial identifier
503 ([\w\.]+) # Initial identifier
498 (\s*,\s*
504 (\s*,\s*
499 \*?[\w\.]+)* # Further identifiers for unpacking
505 \*?[\w\.]+)* # Further identifiers for unpacking
500 \s*?,? # Trailing comma
506 \s*?,? # Trailing comma
501 )
507 )
502 \s*=\s*
508 \s*=\s*
503 '''
509 '''
504
510
505 assign_system_re = re.compile(r'{}!\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
511 assign_system_re = re.compile(r'{}!\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
506 assign_system_template = '%s = get_ipython().getoutput(%r)'
512 assign_system_template = '%s = get_ipython().getoutput(%r)'
507 @StatelessInputTransformer.wrap
513 @StatelessInputTransformer.wrap
508 def assign_from_system(line):
514 def assign_from_system(line):
509 """Transform assignment from system commands (e.g. files = !ls)"""
515 """Transform assignment from system commands (e.g. files = !ls)"""
510 m = assign_system_re.match(line)
516 m = assign_system_re.match(line)
511 if m is None:
517 if m is None:
512 return line
518 return line
513
519
514 return assign_system_template % m.group('lhs', 'cmd')
520 return assign_system_template % m.group('lhs', 'cmd')
515
521
516 assign_magic_re = re.compile(r'{}%\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
522 assign_magic_re = re.compile(r'{}%\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
517 assign_magic_template = '%s = get_ipython().magic(%r)'
523 assign_magic_template = '%s = get_ipython().run_line_magic(%r, %r)'
518 @StatelessInputTransformer.wrap
524 @StatelessInputTransformer.wrap
519 def assign_from_magic(line):
525 def assign_from_magic(line):
520 """Transform assignment from magic commands (e.g. a = %who_ls)"""
526 """Transform assignment from magic commands (e.g. a = %who_ls)"""
521 m = assign_magic_re.match(line)
527 m = assign_magic_re.match(line)
522 if m is None:
528 if m is None:
523 return line
529 return line
524
530 #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
525 return assign_magic_template % m.group('lhs', 'cmd')
531 m_lhs, m_cmd = m.group('lhs', 'cmd')
532 t_magic_name, _, t_magic_arg_s = m_cmd.partition(' ')
533 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
534 return assign_magic_template % (m_lhs, t_magic_name, t_magic_arg_s)
@@ -1,3253 +1,3259 b''
1 # -*- 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.inputsplitter import ESC_MAGIC, ESC_MAGIC2
51 from IPython.core.inputsplitter 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 pass
173 pass
174
174
175
175
176 class ExecutionResult(object):
176 class ExecutionResult(object):
177 """The result of a call to :meth:`InteractiveShell.run_cell`
177 """The result of a call to :meth:`InteractiveShell.run_cell`
178
178
179 Stores information about what took place.
179 Stores information about what took place.
180 """
180 """
181 execution_count = None
181 execution_count = None
182 error_before_exec = None
182 error_before_exec = None
183 error_in_exec = None
183 error_in_exec = None
184 result = None
184 result = None
185
185
186 @property
186 @property
187 def success(self):
187 def success(self):
188 return (self.error_before_exec is None) and (self.error_in_exec is None)
188 return (self.error_before_exec is None) and (self.error_in_exec is None)
189
189
190 def raise_error(self):
190 def raise_error(self):
191 """Reraises error if `success` is `False`, otherwise does nothing"""
191 """Reraises error if `success` is `False`, otherwise does nothing"""
192 if self.error_before_exec is not None:
192 if self.error_before_exec is not None:
193 raise self.error_before_exec
193 raise self.error_before_exec
194 if self.error_in_exec is not None:
194 if self.error_in_exec is not None:
195 raise self.error_in_exec
195 raise self.error_in_exec
196
196
197 def __repr__(self):
197 def __repr__(self):
198 name = self.__class__.__qualname__
198 name = self.__class__.__qualname__
199 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
199 return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s result=%s>' %\
200 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
200 (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.result))
201
201
202
202
203 class InteractiveShell(SingletonConfigurable):
203 class InteractiveShell(SingletonConfigurable):
204 """An enhanced, interactive shell for Python."""
204 """An enhanced, interactive shell for Python."""
205
205
206 _instance = None
206 _instance = None
207
207
208 ast_transformers = List([], help=
208 ast_transformers = List([], help=
209 """
209 """
210 A list of ast.NodeTransformer subclass instances, which will be applied
210 A list of ast.NodeTransformer subclass instances, which will be applied
211 to user input before code is run.
211 to user input before code is run.
212 """
212 """
213 ).tag(config=True)
213 ).tag(config=True)
214
214
215 autocall = Enum((0,1,2), default_value=0, help=
215 autocall = Enum((0,1,2), default_value=0, help=
216 """
216 """
217 Make IPython automatically call any callable object even if you didn't
217 Make IPython automatically call any callable object even if you didn't
218 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
218 type explicit parentheses. For example, 'str 43' becomes 'str(43)'
219 automatically. The value can be '0' to disable the feature, '1' for
219 automatically. The value can be '0' to disable the feature, '1' for
220 'smart' autocall, where it is not applied if there are no more
220 'smart' autocall, where it is not applied if there are no more
221 arguments on the line, and '2' for 'full' autocall, where all callable
221 arguments on the line, and '2' for 'full' autocall, where all callable
222 objects are automatically called (even if no arguments are present).
222 objects are automatically called (even if no arguments are present).
223 """
223 """
224 ).tag(config=True)
224 ).tag(config=True)
225 # TODO: remove all autoindent logic and put into frontends.
225 # TODO: remove all autoindent logic and put into frontends.
226 # We can't do this yet because even runlines uses the autoindent.
226 # We can't do this yet because even runlines uses the autoindent.
227 autoindent = Bool(True, help=
227 autoindent = Bool(True, help=
228 """
228 """
229 Autoindent IPython code entered interactively.
229 Autoindent IPython code entered interactively.
230 """
230 """
231 ).tag(config=True)
231 ).tag(config=True)
232
232
233 automagic = Bool(True, help=
233 automagic = Bool(True, help=
234 """
234 """
235 Enable magic commands to be called without the leading %.
235 Enable magic commands to be called without the leading %.
236 """
236 """
237 ).tag(config=True)
237 ).tag(config=True)
238
238
239 banner1 = Unicode(default_banner,
239 banner1 = Unicode(default_banner,
240 help="""The part of the banner to be printed before the profile"""
240 help="""The part of the banner to be printed before the profile"""
241 ).tag(config=True)
241 ).tag(config=True)
242 banner2 = Unicode('',
242 banner2 = Unicode('',
243 help="""The part of the banner to be printed after the profile"""
243 help="""The part of the banner to be printed after the profile"""
244 ).tag(config=True)
244 ).tag(config=True)
245
245
246 cache_size = Integer(1000, help=
246 cache_size = Integer(1000, help=
247 """
247 """
248 Set the size of the output cache. The default is 1000, you can
248 Set the size of the output cache. The default is 1000, you can
249 change it permanently in your config file. Setting it to 0 completely
249 change it permanently in your config file. Setting it to 0 completely
250 disables the caching system, and the minimum value accepted is 3 (if
250 disables the caching system, and the minimum value accepted is 3 (if
251 you provide a value less than 3, it is reset to 0 and a warning is
251 you provide a value less than 3, it is reset to 0 and a warning is
252 issued). This limit is defined because otherwise you'll spend more
252 issued). This limit is defined because otherwise you'll spend more
253 time re-flushing a too small cache than working
253 time re-flushing a too small cache than working
254 """
254 """
255 ).tag(config=True)
255 ).tag(config=True)
256 color_info = Bool(True, help=
256 color_info = Bool(True, help=
257 """
257 """
258 Use colors for displaying information about objects. Because this
258 Use colors for displaying information about objects. Because this
259 information is passed through a pager (like 'less'), and some pagers
259 information is passed through a pager (like 'less'), and some pagers
260 get confused with color codes, this capability can be turned off.
260 get confused with color codes, this capability can be turned off.
261 """
261 """
262 ).tag(config=True)
262 ).tag(config=True)
263 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
263 colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'),
264 default_value='Neutral',
264 default_value='Neutral',
265 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
265 help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)."
266 ).tag(config=True)
266 ).tag(config=True)
267 debug = Bool(False).tag(config=True)
267 debug = Bool(False).tag(config=True)
268 disable_failing_post_execute = Bool(False,
268 disable_failing_post_execute = Bool(False,
269 help="Don't call post-execute functions that have failed in the past."
269 help="Don't call post-execute functions that have failed in the past."
270 ).tag(config=True)
270 ).tag(config=True)
271 display_formatter = Instance(DisplayFormatter, allow_none=True)
271 display_formatter = Instance(DisplayFormatter, allow_none=True)
272 displayhook_class = Type(DisplayHook)
272 displayhook_class = Type(DisplayHook)
273 display_pub_class = Type(DisplayPublisher)
273 display_pub_class = Type(DisplayPublisher)
274
274
275 sphinxify_docstring = Bool(False, help=
275 sphinxify_docstring = Bool(False, help=
276 """
276 """
277 Enables rich html representation of docstrings. (This requires the
277 Enables rich html representation of docstrings. (This requires the
278 docrepr module).
278 docrepr module).
279 """).tag(config=True)
279 """).tag(config=True)
280
280
281 @observe("sphinxify_docstring")
281 @observe("sphinxify_docstring")
282 def _sphinxify_docstring_changed(self, change):
282 def _sphinxify_docstring_changed(self, change):
283 if change['new']:
283 if change['new']:
284 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
284 warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning)
285
285
286 enable_html_pager = Bool(False, help=
286 enable_html_pager = Bool(False, help=
287 """
287 """
288 (Provisional API) enables html representation in mime bundles sent
288 (Provisional API) enables html representation in mime bundles sent
289 to pagers.
289 to pagers.
290 """).tag(config=True)
290 """).tag(config=True)
291
291
292 @observe("enable_html_pager")
292 @observe("enable_html_pager")
293 def _enable_html_pager_changed(self, change):
293 def _enable_html_pager_changed(self, change):
294 if change['new']:
294 if change['new']:
295 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
295 warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning)
296
296
297 data_pub_class = None
297 data_pub_class = None
298
298
299 exit_now = Bool(False)
299 exit_now = Bool(False)
300 exiter = Instance(ExitAutocall)
300 exiter = Instance(ExitAutocall)
301 @default('exiter')
301 @default('exiter')
302 def _exiter_default(self):
302 def _exiter_default(self):
303 return ExitAutocall(self)
303 return ExitAutocall(self)
304 # Monotonically increasing execution counter
304 # Monotonically increasing execution counter
305 execution_count = Integer(1)
305 execution_count = Integer(1)
306 filename = Unicode("<ipython console>")
306 filename = Unicode("<ipython console>")
307 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
307 ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__
308
308
309 # Input splitter, to transform input line by line and detect when a block
309 # Input splitter, to transform input line by line and detect when a block
310 # is ready to be executed.
310 # is ready to be executed.
311 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
311 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
312 (), {'line_input_checker': True})
312 (), {'line_input_checker': True})
313
313
314 # This InputSplitter instance is used to transform completed cells before
314 # This InputSplitter instance is used to transform completed cells before
315 # running them. It allows cell magics to contain blank lines.
315 # running them. It allows cell magics to contain blank lines.
316 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
316 input_transformer_manager = Instance('IPython.core.inputsplitter.IPythonInputSplitter',
317 (), {'line_input_checker': False})
317 (), {'line_input_checker': False})
318
318
319 logstart = Bool(False, help=
319 logstart = Bool(False, help=
320 """
320 """
321 Start logging to the default log file in overwrite mode.
321 Start logging to the default log file in overwrite mode.
322 Use `logappend` to specify a log file to **append** logs to.
322 Use `logappend` to specify a log file to **append** logs to.
323 """
323 """
324 ).tag(config=True)
324 ).tag(config=True)
325 logfile = Unicode('', help=
325 logfile = Unicode('', help=
326 """
326 """
327 The name of the logfile to use.
327 The name of the logfile to use.
328 """
328 """
329 ).tag(config=True)
329 ).tag(config=True)
330 logappend = Unicode('', help=
330 logappend = Unicode('', help=
331 """
331 """
332 Start logging to the given file in append mode.
332 Start logging to the given file in append mode.
333 Use `logfile` to specify a log file to **overwrite** logs to.
333 Use `logfile` to specify a log file to **overwrite** logs to.
334 """
334 """
335 ).tag(config=True)
335 ).tag(config=True)
336 object_info_string_level = Enum((0,1,2), default_value=0,
336 object_info_string_level = Enum((0,1,2), default_value=0,
337 ).tag(config=True)
337 ).tag(config=True)
338 pdb = Bool(False, help=
338 pdb = Bool(False, help=
339 """
339 """
340 Automatically call the pdb debugger after every exception.
340 Automatically call the pdb debugger after every exception.
341 """
341 """
342 ).tag(config=True)
342 ).tag(config=True)
343 display_page = Bool(False,
343 display_page = Bool(False,
344 help="""If True, anything that would be passed to the pager
344 help="""If True, anything that would be passed to the pager
345 will be displayed as regular output instead."""
345 will be displayed as regular output instead."""
346 ).tag(config=True)
346 ).tag(config=True)
347
347
348 # deprecated prompt traits:
348 # deprecated prompt traits:
349
349
350 prompt_in1 = Unicode('In [\\#]: ',
350 prompt_in1 = Unicode('In [\\#]: ',
351 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
351 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
352 ).tag(config=True)
352 ).tag(config=True)
353 prompt_in2 = Unicode(' .\\D.: ',
353 prompt_in2 = Unicode(' .\\D.: ',
354 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
354 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
355 ).tag(config=True)
355 ).tag(config=True)
356 prompt_out = Unicode('Out[\\#]: ',
356 prompt_out = Unicode('Out[\\#]: ',
357 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
357 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
358 ).tag(config=True)
358 ).tag(config=True)
359 prompts_pad_left = Bool(True,
359 prompts_pad_left = Bool(True,
360 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
360 help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly."
361 ).tag(config=True)
361 ).tag(config=True)
362
362
363 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
363 @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left')
364 def _prompt_trait_changed(self, change):
364 def _prompt_trait_changed(self, change):
365 name = change['name']
365 name = change['name']
366 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
366 warn("InteractiveShell.{name} is deprecated since IPython 4.0"
367 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
367 " and ignored since 5.0, set TerminalInteractiveShell.prompts"
368 " object directly.".format(name=name))
368 " object directly.".format(name=name))
369
369
370 # protect against weird cases where self.config may not exist:
370 # protect against weird cases where self.config may not exist:
371
371
372 show_rewritten_input = Bool(True,
372 show_rewritten_input = Bool(True,
373 help="Show rewritten input, e.g. for autocall."
373 help="Show rewritten input, e.g. for autocall."
374 ).tag(config=True)
374 ).tag(config=True)
375
375
376 quiet = Bool(False).tag(config=True)
376 quiet = Bool(False).tag(config=True)
377
377
378 history_length = Integer(10000,
378 history_length = Integer(10000,
379 help='Total length of command history'
379 help='Total length of command history'
380 ).tag(config=True)
380 ).tag(config=True)
381
381
382 history_load_length = Integer(1000, help=
382 history_load_length = Integer(1000, help=
383 """
383 """
384 The number of saved history entries to be loaded
384 The number of saved history entries to be loaded
385 into the history buffer at startup.
385 into the history buffer at startup.
386 """
386 """
387 ).tag(config=True)
387 ).tag(config=True)
388
388
389 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
389 ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'],
390 default_value='last_expr',
390 default_value='last_expr',
391 help="""
391 help="""
392 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
392 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying
393 which nodes should be run interactively (displaying output from expressions).
393 which nodes should be run interactively (displaying output from expressions).
394 """
394 """
395 ).tag(config=True)
395 ).tag(config=True)
396
396
397 # TODO: this part of prompt management should be moved to the frontends.
397 # TODO: this part of prompt management should be moved to the frontends.
398 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
398 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
399 separate_in = SeparateUnicode('\n').tag(config=True)
399 separate_in = SeparateUnicode('\n').tag(config=True)
400 separate_out = SeparateUnicode('').tag(config=True)
400 separate_out = SeparateUnicode('').tag(config=True)
401 separate_out2 = SeparateUnicode('').tag(config=True)
401 separate_out2 = SeparateUnicode('').tag(config=True)
402 wildcards_case_sensitive = Bool(True).tag(config=True)
402 wildcards_case_sensitive = Bool(True).tag(config=True)
403 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
403 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
404 default_value='Context',
404 default_value='Context',
405 help="Switch modes for the IPython exception handlers."
405 help="Switch modes for the IPython exception handlers."
406 ).tag(config=True)
406 ).tag(config=True)
407
407
408 # Subcomponents of InteractiveShell
408 # Subcomponents of InteractiveShell
409 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
409 alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True)
410 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
410 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
411 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
411 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True)
412 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
412 display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True)
413 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
413 extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True)
414 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
414 payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True)
415 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
415 history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True)
416 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
416 magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True)
417
417
418 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
418 profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True)
419 @property
419 @property
420 def profile(self):
420 def profile(self):
421 if self.profile_dir is not None:
421 if self.profile_dir is not None:
422 name = os.path.basename(self.profile_dir.location)
422 name = os.path.basename(self.profile_dir.location)
423 return name.replace('profile_','')
423 return name.replace('profile_','')
424
424
425
425
426 # Private interface
426 # Private interface
427 _post_execute = Dict()
427 _post_execute = Dict()
428
428
429 # Tracks any GUI loop loaded for pylab
429 # Tracks any GUI loop loaded for pylab
430 pylab_gui_select = None
430 pylab_gui_select = None
431
431
432 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
432 last_execution_succeeded = Bool(True, help='Did last executed command succeeded')
433
433
434 def __init__(self, ipython_dir=None, profile_dir=None,
434 def __init__(self, ipython_dir=None, profile_dir=None,
435 user_module=None, user_ns=None,
435 user_module=None, user_ns=None,
436 custom_exceptions=((), None), **kwargs):
436 custom_exceptions=((), None), **kwargs):
437
437
438 # This is where traits with a config_key argument are updated
438 # This is where traits with a config_key argument are updated
439 # from the values on config.
439 # from the values on config.
440 super(InteractiveShell, self).__init__(**kwargs)
440 super(InteractiveShell, self).__init__(**kwargs)
441 if 'PromptManager' in self.config:
441 if 'PromptManager' in self.config:
442 warn('As of IPython 5.0 `PromptManager` config will have no effect'
442 warn('As of IPython 5.0 `PromptManager` config will have no effect'
443 ' and has been replaced by TerminalInteractiveShell.prompts_class')
443 ' and has been replaced by TerminalInteractiveShell.prompts_class')
444 self.configurables = [self]
444 self.configurables = [self]
445
445
446 # These are relatively independent and stateless
446 # These are relatively independent and stateless
447 self.init_ipython_dir(ipython_dir)
447 self.init_ipython_dir(ipython_dir)
448 self.init_profile_dir(profile_dir)
448 self.init_profile_dir(profile_dir)
449 self.init_instance_attrs()
449 self.init_instance_attrs()
450 self.init_environment()
450 self.init_environment()
451
451
452 # Check if we're in a virtualenv, and set up sys.path.
452 # Check if we're in a virtualenv, and set up sys.path.
453 self.init_virtualenv()
453 self.init_virtualenv()
454
454
455 # Create namespaces (user_ns, user_global_ns, etc.)
455 # Create namespaces (user_ns, user_global_ns, etc.)
456 self.init_create_namespaces(user_module, user_ns)
456 self.init_create_namespaces(user_module, user_ns)
457 # This has to be done after init_create_namespaces because it uses
457 # This has to be done after init_create_namespaces because it uses
458 # something in self.user_ns, but before init_sys_modules, which
458 # something in self.user_ns, but before init_sys_modules, which
459 # is the first thing to modify sys.
459 # is the first thing to modify sys.
460 # TODO: When we override sys.stdout and sys.stderr before this class
460 # TODO: When we override sys.stdout and sys.stderr before this class
461 # is created, we are saving the overridden ones here. Not sure if this
461 # is created, we are saving the overridden ones here. Not sure if this
462 # is what we want to do.
462 # is what we want to do.
463 self.save_sys_module_state()
463 self.save_sys_module_state()
464 self.init_sys_modules()
464 self.init_sys_modules()
465
465
466 # While we're trying to have each part of the code directly access what
466 # While we're trying to have each part of the code directly access what
467 # it needs without keeping redundant references to objects, we have too
467 # it needs without keeping redundant references to objects, we have too
468 # much legacy code that expects ip.db to exist.
468 # much legacy code that expects ip.db to exist.
469 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
469 self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db'))
470
470
471 self.init_history()
471 self.init_history()
472 self.init_encoding()
472 self.init_encoding()
473 self.init_prefilter()
473 self.init_prefilter()
474
474
475 self.init_syntax_highlighting()
475 self.init_syntax_highlighting()
476 self.init_hooks()
476 self.init_hooks()
477 self.init_events()
477 self.init_events()
478 self.init_pushd_popd_magic()
478 self.init_pushd_popd_magic()
479 self.init_user_ns()
479 self.init_user_ns()
480 self.init_logger()
480 self.init_logger()
481 self.init_builtins()
481 self.init_builtins()
482
482
483 # The following was in post_config_initialization
483 # The following was in post_config_initialization
484 self.init_inspector()
484 self.init_inspector()
485 self.raw_input_original = input
485 self.raw_input_original = input
486 self.init_completer()
486 self.init_completer()
487 # TODO: init_io() needs to happen before init_traceback handlers
487 # TODO: init_io() needs to happen before init_traceback handlers
488 # because the traceback handlers hardcode the stdout/stderr streams.
488 # because the traceback handlers hardcode the stdout/stderr streams.
489 # This logic in in debugger.Pdb and should eventually be changed.
489 # This logic in in debugger.Pdb and should eventually be changed.
490 self.init_io()
490 self.init_io()
491 self.init_traceback_handlers(custom_exceptions)
491 self.init_traceback_handlers(custom_exceptions)
492 self.init_prompts()
492 self.init_prompts()
493 self.init_display_formatter()
493 self.init_display_formatter()
494 self.init_display_pub()
494 self.init_display_pub()
495 self.init_data_pub()
495 self.init_data_pub()
496 self.init_displayhook()
496 self.init_displayhook()
497 self.init_magics()
497 self.init_magics()
498 self.init_alias()
498 self.init_alias()
499 self.init_logstart()
499 self.init_logstart()
500 self.init_pdb()
500 self.init_pdb()
501 self.init_extension_manager()
501 self.init_extension_manager()
502 self.init_payload()
502 self.init_payload()
503 self.init_deprecation_warnings()
503 self.init_deprecation_warnings()
504 self.hooks.late_startup_hook()
504 self.hooks.late_startup_hook()
505 self.events.trigger('shell_initialized', self)
505 self.events.trigger('shell_initialized', self)
506 atexit.register(self.atexit_operations)
506 atexit.register(self.atexit_operations)
507
507
508 def get_ipython(self):
508 def get_ipython(self):
509 """Return the currently running IPython instance."""
509 """Return the currently running IPython instance."""
510 return self
510 return self
511
511
512 #-------------------------------------------------------------------------
512 #-------------------------------------------------------------------------
513 # Trait changed handlers
513 # Trait changed handlers
514 #-------------------------------------------------------------------------
514 #-------------------------------------------------------------------------
515 @observe('ipython_dir')
515 @observe('ipython_dir')
516 def _ipython_dir_changed(self, change):
516 def _ipython_dir_changed(self, change):
517 ensure_dir_exists(change['new'])
517 ensure_dir_exists(change['new'])
518
518
519 def set_autoindent(self,value=None):
519 def set_autoindent(self,value=None):
520 """Set the autoindent flag.
520 """Set the autoindent flag.
521
521
522 If called with no arguments, it acts as a toggle."""
522 If called with no arguments, it acts as a toggle."""
523 if value is None:
523 if value is None:
524 self.autoindent = not self.autoindent
524 self.autoindent = not self.autoindent
525 else:
525 else:
526 self.autoindent = value
526 self.autoindent = value
527
527
528 #-------------------------------------------------------------------------
528 #-------------------------------------------------------------------------
529 # init_* methods called by __init__
529 # init_* methods called by __init__
530 #-------------------------------------------------------------------------
530 #-------------------------------------------------------------------------
531
531
532 def init_ipython_dir(self, ipython_dir):
532 def init_ipython_dir(self, ipython_dir):
533 if ipython_dir is not None:
533 if ipython_dir is not None:
534 self.ipython_dir = ipython_dir
534 self.ipython_dir = ipython_dir
535 return
535 return
536
536
537 self.ipython_dir = get_ipython_dir()
537 self.ipython_dir = get_ipython_dir()
538
538
539 def init_profile_dir(self, profile_dir):
539 def init_profile_dir(self, profile_dir):
540 if profile_dir is not None:
540 if profile_dir is not None:
541 self.profile_dir = profile_dir
541 self.profile_dir = profile_dir
542 return
542 return
543 self.profile_dir =\
543 self.profile_dir =\
544 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
544 ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default')
545
545
546 def init_instance_attrs(self):
546 def init_instance_attrs(self):
547 self.more = False
547 self.more = False
548
548
549 # command compiler
549 # command compiler
550 self.compile = CachingCompiler()
550 self.compile = CachingCompiler()
551
551
552 # Make an empty namespace, which extension writers can rely on both
552 # Make an empty namespace, which extension writers can rely on both
553 # existing and NEVER being used by ipython itself. This gives them a
553 # existing and NEVER being used by ipython itself. This gives them a
554 # convenient location for storing additional information and state
554 # convenient location for storing additional information and state
555 # their extensions may require, without fear of collisions with other
555 # their extensions may require, without fear of collisions with other
556 # ipython names that may develop later.
556 # ipython names that may develop later.
557 self.meta = Struct()
557 self.meta = Struct()
558
558
559 # Temporary files used for various purposes. Deleted at exit.
559 # Temporary files used for various purposes. Deleted at exit.
560 self.tempfiles = []
560 self.tempfiles = []
561 self.tempdirs = []
561 self.tempdirs = []
562
562
563 # keep track of where we started running (mainly for crash post-mortem)
563 # keep track of where we started running (mainly for crash post-mortem)
564 # This is not being used anywhere currently.
564 # This is not being used anywhere currently.
565 self.starting_dir = os.getcwd()
565 self.starting_dir = os.getcwd()
566
566
567 # Indentation management
567 # Indentation management
568 self.indent_current_nsp = 0
568 self.indent_current_nsp = 0
569
569
570 # Dict to track post-execution functions that have been registered
570 # Dict to track post-execution functions that have been registered
571 self._post_execute = {}
571 self._post_execute = {}
572
572
573 def init_environment(self):
573 def init_environment(self):
574 """Any changes we need to make to the user's environment."""
574 """Any changes we need to make to the user's environment."""
575 pass
575 pass
576
576
577 def init_encoding(self):
577 def init_encoding(self):
578 # Get system encoding at startup time. Certain terminals (like Emacs
578 # Get system encoding at startup time. Certain terminals (like Emacs
579 # under Win32 have it set to None, and we need to have a known valid
579 # under Win32 have it set to None, and we need to have a known valid
580 # encoding to use in the raw_input() method
580 # encoding to use in the raw_input() method
581 try:
581 try:
582 self.stdin_encoding = sys.stdin.encoding or 'ascii'
582 self.stdin_encoding = sys.stdin.encoding or 'ascii'
583 except AttributeError:
583 except AttributeError:
584 self.stdin_encoding = 'ascii'
584 self.stdin_encoding = 'ascii'
585
585
586
586
587 @observe('colors')
587 @observe('colors')
588 def init_syntax_highlighting(self, changes=None):
588 def init_syntax_highlighting(self, changes=None):
589 # Python source parser/formatter for syntax highlighting
589 # Python source parser/formatter for syntax highlighting
590 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
590 pyformat = PyColorize.Parser(style=self.colors, parent=self).format
591 self.pycolorize = lambda src: pyformat(src,'str')
591 self.pycolorize = lambda src: pyformat(src,'str')
592
592
593 def refresh_style(self):
593 def refresh_style(self):
594 # No-op here, used in subclass
594 # No-op here, used in subclass
595 pass
595 pass
596
596
597 def init_pushd_popd_magic(self):
597 def init_pushd_popd_magic(self):
598 # for pushd/popd management
598 # for pushd/popd management
599 self.home_dir = get_home_dir()
599 self.home_dir = get_home_dir()
600
600
601 self.dir_stack = []
601 self.dir_stack = []
602
602
603 def init_logger(self):
603 def init_logger(self):
604 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
604 self.logger = Logger(self.home_dir, logfname='ipython_log.py',
605 logmode='rotate')
605 logmode='rotate')
606
606
607 def init_logstart(self):
607 def init_logstart(self):
608 """Initialize logging in case it was requested at the command line.
608 """Initialize logging in case it was requested at the command line.
609 """
609 """
610 if self.logappend:
610 if self.logappend:
611 self.magic('logstart %s append' % self.logappend)
611 self.magic('logstart %s append' % self.logappend)
612 elif self.logfile:
612 elif self.logfile:
613 self.magic('logstart %s' % self.logfile)
613 self.magic('logstart %s' % self.logfile)
614 elif self.logstart:
614 elif self.logstart:
615 self.magic('logstart')
615 self.magic('logstart')
616
616
617 def init_deprecation_warnings(self):
617 def init_deprecation_warnings(self):
618 """
618 """
619 register default filter for deprecation warning.
619 register default filter for deprecation warning.
620
620
621 This will allow deprecation warning of function used interactively to show
621 This will allow deprecation warning of function used interactively to show
622 warning to users, and still hide deprecation warning from libraries import.
622 warning to users, and still hide deprecation warning from libraries import.
623 """
623 """
624 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
624 warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__"))
625
625
626 def init_builtins(self):
626 def init_builtins(self):
627 # A single, static flag that we set to True. Its presence indicates
627 # A single, static flag that we set to True. Its presence indicates
628 # that an IPython shell has been created, and we make no attempts at
628 # that an IPython shell has been created, and we make no attempts at
629 # removing on exit or representing the existence of more than one
629 # removing on exit or representing the existence of more than one
630 # IPython at a time.
630 # IPython at a time.
631 builtin_mod.__dict__['__IPYTHON__'] = True
631 builtin_mod.__dict__['__IPYTHON__'] = True
632 builtin_mod.__dict__['display'] = display
632 builtin_mod.__dict__['display'] = display
633
633
634 self.builtin_trap = BuiltinTrap(shell=self)
634 self.builtin_trap = BuiltinTrap(shell=self)
635
635
636 def init_inspector(self):
636 def init_inspector(self):
637 # Object inspector
637 # Object inspector
638 self.inspector = oinspect.Inspector(oinspect.InspectColors,
638 self.inspector = oinspect.Inspector(oinspect.InspectColors,
639 PyColorize.ANSICodeColors,
639 PyColorize.ANSICodeColors,
640 self.colors,
640 self.colors,
641 self.object_info_string_level)
641 self.object_info_string_level)
642
642
643 def init_io(self):
643 def init_io(self):
644 # This will just use sys.stdout and sys.stderr. If you want to
644 # This will just use sys.stdout and sys.stderr. If you want to
645 # override sys.stdout and sys.stderr themselves, you need to do that
645 # override sys.stdout and sys.stderr themselves, you need to do that
646 # *before* instantiating this class, because io holds onto
646 # *before* instantiating this class, because io holds onto
647 # references to the underlying streams.
647 # references to the underlying streams.
648 # io.std* are deprecated, but don't show our own deprecation warnings
648 # io.std* are deprecated, but don't show our own deprecation warnings
649 # during initialization of the deprecated API.
649 # during initialization of the deprecated API.
650 with warnings.catch_warnings():
650 with warnings.catch_warnings():
651 warnings.simplefilter('ignore', DeprecationWarning)
651 warnings.simplefilter('ignore', DeprecationWarning)
652 io.stdout = io.IOStream(sys.stdout)
652 io.stdout = io.IOStream(sys.stdout)
653 io.stderr = io.IOStream(sys.stderr)
653 io.stderr = io.IOStream(sys.stderr)
654
654
655 def init_prompts(self):
655 def init_prompts(self):
656 # Set system prompts, so that scripts can decide if they are running
656 # Set system prompts, so that scripts can decide if they are running
657 # interactively.
657 # interactively.
658 sys.ps1 = 'In : '
658 sys.ps1 = 'In : '
659 sys.ps2 = '...: '
659 sys.ps2 = '...: '
660 sys.ps3 = 'Out: '
660 sys.ps3 = 'Out: '
661
661
662 def init_display_formatter(self):
662 def init_display_formatter(self):
663 self.display_formatter = DisplayFormatter(parent=self)
663 self.display_formatter = DisplayFormatter(parent=self)
664 self.configurables.append(self.display_formatter)
664 self.configurables.append(self.display_formatter)
665
665
666 def init_display_pub(self):
666 def init_display_pub(self):
667 self.display_pub = self.display_pub_class(parent=self)
667 self.display_pub = self.display_pub_class(parent=self)
668 self.configurables.append(self.display_pub)
668 self.configurables.append(self.display_pub)
669
669
670 def init_data_pub(self):
670 def init_data_pub(self):
671 if not self.data_pub_class:
671 if not self.data_pub_class:
672 self.data_pub = None
672 self.data_pub = None
673 return
673 return
674 self.data_pub = self.data_pub_class(parent=self)
674 self.data_pub = self.data_pub_class(parent=self)
675 self.configurables.append(self.data_pub)
675 self.configurables.append(self.data_pub)
676
676
677 def init_displayhook(self):
677 def init_displayhook(self):
678 # Initialize displayhook, set in/out prompts and printing system
678 # Initialize displayhook, set in/out prompts and printing system
679 self.displayhook = self.displayhook_class(
679 self.displayhook = self.displayhook_class(
680 parent=self,
680 parent=self,
681 shell=self,
681 shell=self,
682 cache_size=self.cache_size,
682 cache_size=self.cache_size,
683 )
683 )
684 self.configurables.append(self.displayhook)
684 self.configurables.append(self.displayhook)
685 # This is a context manager that installs/revmoes the displayhook at
685 # This is a context manager that installs/revmoes the displayhook at
686 # the appropriate time.
686 # the appropriate time.
687 self.display_trap = DisplayTrap(hook=self.displayhook)
687 self.display_trap = DisplayTrap(hook=self.displayhook)
688
688
689 def init_virtualenv(self):
689 def init_virtualenv(self):
690 """Add a virtualenv to sys.path so the user can import modules from it.
690 """Add a virtualenv to sys.path so the user can import modules from it.
691 This isn't perfect: it doesn't use the Python interpreter with which the
691 This isn't perfect: it doesn't use the Python interpreter with which the
692 virtualenv was built, and it ignores the --no-site-packages option. A
692 virtualenv was built, and it ignores the --no-site-packages option. A
693 warning will appear suggesting the user installs IPython in the
693 warning will appear suggesting the user installs IPython in the
694 virtualenv, but for many cases, it probably works well enough.
694 virtualenv, but for many cases, it probably works well enough.
695
695
696 Adapted from code snippets online.
696 Adapted from code snippets online.
697
697
698 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
698 http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv
699 """
699 """
700 if 'VIRTUAL_ENV' not in os.environ:
700 if 'VIRTUAL_ENV' not in os.environ:
701 # Not in a virtualenv
701 # Not in a virtualenv
702 return
702 return
703
703
704 # venv detection:
704 # venv detection:
705 # stdlib venv may symlink sys.executable, so we can't use realpath.
705 # stdlib venv may symlink sys.executable, so we can't use realpath.
706 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
706 # but others can symlink *to* the venv Python, so we can't just use sys.executable.
707 # So we just check every item in the symlink tree (generally <= 3)
707 # So we just check every item in the symlink tree (generally <= 3)
708 p = os.path.normcase(sys.executable)
708 p = os.path.normcase(sys.executable)
709 paths = [p]
709 paths = [p]
710 while os.path.islink(p):
710 while os.path.islink(p):
711 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
711 p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
712 paths.append(p)
712 paths.append(p)
713 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
713 p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
714
714
715 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
715 # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible
716 if p_venv.startswith('\\cygdrive'):
716 if p_venv.startswith('\\cygdrive'):
717 p_venv = p_venv[11:]
717 p_venv = p_venv[11:]
718 elif p_venv[1] == ':':
718 elif p_venv[1] == ':':
719 p_venv = p_venv[2:]
719 p_venv = p_venv[2:]
720
720
721 if any(p_venv in p for p in paths):
721 if any(p_venv in p for p in paths):
722 # Running properly in the virtualenv, don't need to do anything
722 # Running properly in the virtualenv, don't need to do anything
723 return
723 return
724
724
725 warn("Attempting to work in a virtualenv. If you encounter problems, please "
725 warn("Attempting to work in a virtualenv. If you encounter problems, please "
726 "install IPython inside the virtualenv.")
726 "install IPython inside the virtualenv.")
727 if sys.platform == "win32":
727 if sys.platform == "win32":
728 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
728 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages')
729 else:
729 else:
730 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
730 virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib',
731 'python%d.%d' % sys.version_info[:2], 'site-packages')
731 'python%d.%d' % sys.version_info[:2], 'site-packages')
732
732
733 import site
733 import site
734 sys.path.insert(0, virtual_env)
734 sys.path.insert(0, virtual_env)
735 site.addsitedir(virtual_env)
735 site.addsitedir(virtual_env)
736
736
737 #-------------------------------------------------------------------------
737 #-------------------------------------------------------------------------
738 # Things related to injections into the sys module
738 # Things related to injections into the sys module
739 #-------------------------------------------------------------------------
739 #-------------------------------------------------------------------------
740
740
741 def save_sys_module_state(self):
741 def save_sys_module_state(self):
742 """Save the state of hooks in the sys module.
742 """Save the state of hooks in the sys module.
743
743
744 This has to be called after self.user_module is created.
744 This has to be called after self.user_module is created.
745 """
745 """
746 self._orig_sys_module_state = {'stdin': sys.stdin,
746 self._orig_sys_module_state = {'stdin': sys.stdin,
747 'stdout': sys.stdout,
747 'stdout': sys.stdout,
748 'stderr': sys.stderr,
748 'stderr': sys.stderr,
749 'excepthook': sys.excepthook}
749 'excepthook': sys.excepthook}
750 self._orig_sys_modules_main_name = self.user_module.__name__
750 self._orig_sys_modules_main_name = self.user_module.__name__
751 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
751 self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__)
752
752
753 def restore_sys_module_state(self):
753 def restore_sys_module_state(self):
754 """Restore the state of the sys module."""
754 """Restore the state of the sys module."""
755 try:
755 try:
756 for k, v in self._orig_sys_module_state.items():
756 for k, v in self._orig_sys_module_state.items():
757 setattr(sys, k, v)
757 setattr(sys, k, v)
758 except AttributeError:
758 except AttributeError:
759 pass
759 pass
760 # Reset what what done in self.init_sys_modules
760 # Reset what what done in self.init_sys_modules
761 if self._orig_sys_modules_main_mod is not None:
761 if self._orig_sys_modules_main_mod is not None:
762 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
762 sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod
763
763
764 #-------------------------------------------------------------------------
764 #-------------------------------------------------------------------------
765 # Things related to the banner
765 # Things related to the banner
766 #-------------------------------------------------------------------------
766 #-------------------------------------------------------------------------
767
767
768 @property
768 @property
769 def banner(self):
769 def banner(self):
770 banner = self.banner1
770 banner = self.banner1
771 if self.profile and self.profile != 'default':
771 if self.profile and self.profile != 'default':
772 banner += '\nIPython profile: %s\n' % self.profile
772 banner += '\nIPython profile: %s\n' % self.profile
773 if self.banner2:
773 if self.banner2:
774 banner += '\n' + self.banner2
774 banner += '\n' + self.banner2
775 return banner
775 return banner
776
776
777 def show_banner(self, banner=None):
777 def show_banner(self, banner=None):
778 if banner is None:
778 if banner is None:
779 banner = self.banner
779 banner = self.banner
780 sys.stdout.write(banner)
780 sys.stdout.write(banner)
781
781
782 #-------------------------------------------------------------------------
782 #-------------------------------------------------------------------------
783 # Things related to hooks
783 # Things related to hooks
784 #-------------------------------------------------------------------------
784 #-------------------------------------------------------------------------
785
785
786 def init_hooks(self):
786 def init_hooks(self):
787 # hooks holds pointers used for user-side customizations
787 # hooks holds pointers used for user-side customizations
788 self.hooks = Struct()
788 self.hooks = Struct()
789
789
790 self.strdispatchers = {}
790 self.strdispatchers = {}
791
791
792 # Set all default hooks, defined in the IPython.hooks module.
792 # Set all default hooks, defined in the IPython.hooks module.
793 hooks = IPython.core.hooks
793 hooks = IPython.core.hooks
794 for hook_name in hooks.__all__:
794 for hook_name in hooks.__all__:
795 # default hooks have priority 100, i.e. low; user hooks should have
795 # default hooks have priority 100, i.e. low; user hooks should have
796 # 0-100 priority
796 # 0-100 priority
797 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
797 self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False)
798
798
799 if self.display_page:
799 if self.display_page:
800 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
800 self.set_hook('show_in_pager', page.as_hook(page.display_page), 90)
801
801
802 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
802 def set_hook(self,name,hook, priority=50, str_key=None, re_key=None,
803 _warn_deprecated=True):
803 _warn_deprecated=True):
804 """set_hook(name,hook) -> sets an internal IPython hook.
804 """set_hook(name,hook) -> sets an internal IPython hook.
805
805
806 IPython exposes some of its internal API as user-modifiable hooks. By
806 IPython exposes some of its internal API as user-modifiable hooks. By
807 adding your function to one of these hooks, you can modify IPython's
807 adding your function to one of these hooks, you can modify IPython's
808 behavior to call at runtime your own routines."""
808 behavior to call at runtime your own routines."""
809
809
810 # At some point in the future, this should validate the hook before it
810 # At some point in the future, this should validate the hook before it
811 # accepts it. Probably at least check that the hook takes the number
811 # accepts it. Probably at least check that the hook takes the number
812 # of args it's supposed to.
812 # of args it's supposed to.
813
813
814 f = types.MethodType(hook,self)
814 f = types.MethodType(hook,self)
815
815
816 # check if the hook is for strdispatcher first
816 # check if the hook is for strdispatcher first
817 if str_key is not None:
817 if str_key is not None:
818 sdp = self.strdispatchers.get(name, StrDispatch())
818 sdp = self.strdispatchers.get(name, StrDispatch())
819 sdp.add_s(str_key, f, priority )
819 sdp.add_s(str_key, f, priority )
820 self.strdispatchers[name] = sdp
820 self.strdispatchers[name] = sdp
821 return
821 return
822 if re_key is not None:
822 if re_key is not None:
823 sdp = self.strdispatchers.get(name, StrDispatch())
823 sdp = self.strdispatchers.get(name, StrDispatch())
824 sdp.add_re(re.compile(re_key), f, priority )
824 sdp.add_re(re.compile(re_key), f, priority )
825 self.strdispatchers[name] = sdp
825 self.strdispatchers[name] = sdp
826 return
826 return
827
827
828 dp = getattr(self.hooks, name, None)
828 dp = getattr(self.hooks, name, None)
829 if name not in IPython.core.hooks.__all__:
829 if name not in IPython.core.hooks.__all__:
830 print("Warning! Hook '%s' is not one of %s" % \
830 print("Warning! Hook '%s' is not one of %s" % \
831 (name, IPython.core.hooks.__all__ ))
831 (name, IPython.core.hooks.__all__ ))
832
832
833 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
833 if _warn_deprecated and (name in IPython.core.hooks.deprecated):
834 alternative = IPython.core.hooks.deprecated[name]
834 alternative = IPython.core.hooks.deprecated[name]
835 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
835 warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2)
836
836
837 if not dp:
837 if not dp:
838 dp = IPython.core.hooks.CommandChainDispatcher()
838 dp = IPython.core.hooks.CommandChainDispatcher()
839
839
840 try:
840 try:
841 dp.add(f,priority)
841 dp.add(f,priority)
842 except AttributeError:
842 except AttributeError:
843 # it was not commandchain, plain old func - replace
843 # it was not commandchain, plain old func - replace
844 dp = f
844 dp = f
845
845
846 setattr(self.hooks,name, dp)
846 setattr(self.hooks,name, dp)
847
847
848 #-------------------------------------------------------------------------
848 #-------------------------------------------------------------------------
849 # Things related to events
849 # Things related to events
850 #-------------------------------------------------------------------------
850 #-------------------------------------------------------------------------
851
851
852 def init_events(self):
852 def init_events(self):
853 self.events = EventManager(self, available_events)
853 self.events = EventManager(self, available_events)
854
854
855 self.events.register("pre_execute", self._clear_warning_registry)
855 self.events.register("pre_execute", self._clear_warning_registry)
856
856
857 def register_post_execute(self, func):
857 def register_post_execute(self, func):
858 """DEPRECATED: Use ip.events.register('post_run_cell', func)
858 """DEPRECATED: Use ip.events.register('post_run_cell', func)
859
859
860 Register a function for calling after code execution.
860 Register a function for calling after code execution.
861 """
861 """
862 warn("ip.register_post_execute is deprecated, use "
862 warn("ip.register_post_execute is deprecated, use "
863 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
863 "ip.events.register('post_run_cell', func) instead.", stacklevel=2)
864 self.events.register('post_run_cell', func)
864 self.events.register('post_run_cell', func)
865
865
866 def _clear_warning_registry(self):
866 def _clear_warning_registry(self):
867 # clear the warning registry, so that different code blocks with
867 # clear the warning registry, so that different code blocks with
868 # overlapping line number ranges don't cause spurious suppression of
868 # overlapping line number ranges don't cause spurious suppression of
869 # warnings (see gh-6611 for details)
869 # warnings (see gh-6611 for details)
870 if "__warningregistry__" in self.user_global_ns:
870 if "__warningregistry__" in self.user_global_ns:
871 del self.user_global_ns["__warningregistry__"]
871 del self.user_global_ns["__warningregistry__"]
872
872
873 #-------------------------------------------------------------------------
873 #-------------------------------------------------------------------------
874 # Things related to the "main" module
874 # Things related to the "main" module
875 #-------------------------------------------------------------------------
875 #-------------------------------------------------------------------------
876
876
877 def new_main_mod(self, filename, modname):
877 def new_main_mod(self, filename, modname):
878 """Return a new 'main' module object for user code execution.
878 """Return a new 'main' module object for user code execution.
879
879
880 ``filename`` should be the path of the script which will be run in the
880 ``filename`` should be the path of the script which will be run in the
881 module. Requests with the same filename will get the same module, with
881 module. Requests with the same filename will get the same module, with
882 its namespace cleared.
882 its namespace cleared.
883
883
884 ``modname`` should be the module name - normally either '__main__' or
884 ``modname`` should be the module name - normally either '__main__' or
885 the basename of the file without the extension.
885 the basename of the file without the extension.
886
886
887 When scripts are executed via %run, we must keep a reference to their
887 When scripts are executed via %run, we must keep a reference to their
888 __main__ module around so that Python doesn't
888 __main__ module around so that Python doesn't
889 clear it, rendering references to module globals useless.
889 clear it, rendering references to module globals useless.
890
890
891 This method keeps said reference in a private dict, keyed by the
891 This method keeps said reference in a private dict, keyed by the
892 absolute path of the script. This way, for multiple executions of the
892 absolute path of the script. This way, for multiple executions of the
893 same script we only keep one copy of the namespace (the last one),
893 same script we only keep one copy of the namespace (the last one),
894 thus preventing memory leaks from old references while allowing the
894 thus preventing memory leaks from old references while allowing the
895 objects from the last execution to be accessible.
895 objects from the last execution to be accessible.
896 """
896 """
897 filename = os.path.abspath(filename)
897 filename = os.path.abspath(filename)
898 try:
898 try:
899 main_mod = self._main_mod_cache[filename]
899 main_mod = self._main_mod_cache[filename]
900 except KeyError:
900 except KeyError:
901 main_mod = self._main_mod_cache[filename] = types.ModuleType(
901 main_mod = self._main_mod_cache[filename] = types.ModuleType(
902 modname,
902 modname,
903 doc="Module created for script run in IPython")
903 doc="Module created for script run in IPython")
904 else:
904 else:
905 main_mod.__dict__.clear()
905 main_mod.__dict__.clear()
906 main_mod.__name__ = modname
906 main_mod.__name__ = modname
907
907
908 main_mod.__file__ = filename
908 main_mod.__file__ = filename
909 # It seems pydoc (and perhaps others) needs any module instance to
909 # It seems pydoc (and perhaps others) needs any module instance to
910 # implement a __nonzero__ method
910 # implement a __nonzero__ method
911 main_mod.__nonzero__ = lambda : True
911 main_mod.__nonzero__ = lambda : True
912
912
913 return main_mod
913 return main_mod
914
914
915 def clear_main_mod_cache(self):
915 def clear_main_mod_cache(self):
916 """Clear the cache of main modules.
916 """Clear the cache of main modules.
917
917
918 Mainly for use by utilities like %reset.
918 Mainly for use by utilities like %reset.
919
919
920 Examples
920 Examples
921 --------
921 --------
922
922
923 In [15]: import IPython
923 In [15]: import IPython
924
924
925 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
925 In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython')
926
926
927 In [17]: len(_ip._main_mod_cache) > 0
927 In [17]: len(_ip._main_mod_cache) > 0
928 Out[17]: True
928 Out[17]: True
929
929
930 In [18]: _ip.clear_main_mod_cache()
930 In [18]: _ip.clear_main_mod_cache()
931
931
932 In [19]: len(_ip._main_mod_cache) == 0
932 In [19]: len(_ip._main_mod_cache) == 0
933 Out[19]: True
933 Out[19]: True
934 """
934 """
935 self._main_mod_cache.clear()
935 self._main_mod_cache.clear()
936
936
937 #-------------------------------------------------------------------------
937 #-------------------------------------------------------------------------
938 # Things related to debugging
938 # Things related to debugging
939 #-------------------------------------------------------------------------
939 #-------------------------------------------------------------------------
940
940
941 def init_pdb(self):
941 def init_pdb(self):
942 # Set calling of pdb on exceptions
942 # Set calling of pdb on exceptions
943 # self.call_pdb is a property
943 # self.call_pdb is a property
944 self.call_pdb = self.pdb
944 self.call_pdb = self.pdb
945
945
946 def _get_call_pdb(self):
946 def _get_call_pdb(self):
947 return self._call_pdb
947 return self._call_pdb
948
948
949 def _set_call_pdb(self,val):
949 def _set_call_pdb(self,val):
950
950
951 if val not in (0,1,False,True):
951 if val not in (0,1,False,True):
952 raise ValueError('new call_pdb value must be boolean')
952 raise ValueError('new call_pdb value must be boolean')
953
953
954 # store value in instance
954 # store value in instance
955 self._call_pdb = val
955 self._call_pdb = val
956
956
957 # notify the actual exception handlers
957 # notify the actual exception handlers
958 self.InteractiveTB.call_pdb = val
958 self.InteractiveTB.call_pdb = val
959
959
960 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
960 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
961 'Control auto-activation of pdb at exceptions')
961 'Control auto-activation of pdb at exceptions')
962
962
963 def debugger(self,force=False):
963 def debugger(self,force=False):
964 """Call the pdb debugger.
964 """Call the pdb debugger.
965
965
966 Keywords:
966 Keywords:
967
967
968 - force(False): by default, this routine checks the instance call_pdb
968 - force(False): by default, this routine checks the instance call_pdb
969 flag and does not actually invoke the debugger if the flag is false.
969 flag and does not actually invoke the debugger if the flag is false.
970 The 'force' option forces the debugger to activate even if the flag
970 The 'force' option forces the debugger to activate even if the flag
971 is false.
971 is false.
972 """
972 """
973
973
974 if not (force or self.call_pdb):
974 if not (force or self.call_pdb):
975 return
975 return
976
976
977 if not hasattr(sys,'last_traceback'):
977 if not hasattr(sys,'last_traceback'):
978 error('No traceback has been produced, nothing to debug.')
978 error('No traceback has been produced, nothing to debug.')
979 return
979 return
980
980
981 self.InteractiveTB.debugger(force=True)
981 self.InteractiveTB.debugger(force=True)
982
982
983 #-------------------------------------------------------------------------
983 #-------------------------------------------------------------------------
984 # Things related to IPython's various namespaces
984 # Things related to IPython's various namespaces
985 #-------------------------------------------------------------------------
985 #-------------------------------------------------------------------------
986 default_user_namespaces = True
986 default_user_namespaces = True
987
987
988 def init_create_namespaces(self, user_module=None, user_ns=None):
988 def init_create_namespaces(self, user_module=None, user_ns=None):
989 # Create the namespace where the user will operate. user_ns is
989 # Create the namespace where the user will operate. user_ns is
990 # normally the only one used, and it is passed to the exec calls as
990 # normally the only one used, and it is passed to the exec calls as
991 # the locals argument. But we do carry a user_global_ns namespace
991 # the locals argument. But we do carry a user_global_ns namespace
992 # given as the exec 'globals' argument, This is useful in embedding
992 # given as the exec 'globals' argument, This is useful in embedding
993 # situations where the ipython shell opens in a context where the
993 # situations where the ipython shell opens in a context where the
994 # distinction between locals and globals is meaningful. For
994 # distinction between locals and globals is meaningful. For
995 # non-embedded contexts, it is just the same object as the user_ns dict.
995 # non-embedded contexts, it is just the same object as the user_ns dict.
996
996
997 # FIXME. For some strange reason, __builtins__ is showing up at user
997 # FIXME. For some strange reason, __builtins__ is showing up at user
998 # level as a dict instead of a module. This is a manual fix, but I
998 # level as a dict instead of a module. This is a manual fix, but I
999 # should really track down where the problem is coming from. Alex
999 # should really track down where the problem is coming from. Alex
1000 # Schmolck reported this problem first.
1000 # Schmolck reported this problem first.
1001
1001
1002 # A useful post by Alex Martelli on this topic:
1002 # A useful post by Alex Martelli on this topic:
1003 # Re: inconsistent value from __builtins__
1003 # Re: inconsistent value from __builtins__
1004 # Von: Alex Martelli <aleaxit@yahoo.com>
1004 # Von: Alex Martelli <aleaxit@yahoo.com>
1005 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1005 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
1006 # Gruppen: comp.lang.python
1006 # Gruppen: comp.lang.python
1007
1007
1008 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1008 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
1009 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1009 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
1010 # > <type 'dict'>
1010 # > <type 'dict'>
1011 # > >>> print type(__builtins__)
1011 # > >>> print type(__builtins__)
1012 # > <type 'module'>
1012 # > <type 'module'>
1013 # > Is this difference in return value intentional?
1013 # > Is this difference in return value intentional?
1014
1014
1015 # Well, it's documented that '__builtins__' can be either a dictionary
1015 # Well, it's documented that '__builtins__' can be either a dictionary
1016 # or a module, and it's been that way for a long time. Whether it's
1016 # or a module, and it's been that way for a long time. Whether it's
1017 # intentional (or sensible), I don't know. In any case, the idea is
1017 # intentional (or sensible), I don't know. In any case, the idea is
1018 # that if you need to access the built-in namespace directly, you
1018 # that if you need to access the built-in namespace directly, you
1019 # should start with "import __builtin__" (note, no 's') which will
1019 # should start with "import __builtin__" (note, no 's') which will
1020 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1020 # definitely give you a module. Yeah, it's somewhat confusing:-(.
1021
1021
1022 # These routines return a properly built module and dict as needed by
1022 # These routines return a properly built module and dict as needed by
1023 # the rest of the code, and can also be used by extension writers to
1023 # the rest of the code, and can also be used by extension writers to
1024 # generate properly initialized namespaces.
1024 # generate properly initialized namespaces.
1025 if (user_ns is not None) or (user_module is not None):
1025 if (user_ns is not None) or (user_module is not None):
1026 self.default_user_namespaces = False
1026 self.default_user_namespaces = False
1027 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1027 self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns)
1028
1028
1029 # A record of hidden variables we have added to the user namespace, so
1029 # A record of hidden variables we have added to the user namespace, so
1030 # we can list later only variables defined in actual interactive use.
1030 # we can list later only variables defined in actual interactive use.
1031 self.user_ns_hidden = {}
1031 self.user_ns_hidden = {}
1032
1032
1033 # Now that FakeModule produces a real module, we've run into a nasty
1033 # Now that FakeModule produces a real module, we've run into a nasty
1034 # problem: after script execution (via %run), the module where the user
1034 # problem: after script execution (via %run), the module where the user
1035 # code ran is deleted. Now that this object is a true module (needed
1035 # code ran is deleted. Now that this object is a true module (needed
1036 # so doctest and other tools work correctly), the Python module
1036 # so doctest and other tools work correctly), the Python module
1037 # teardown mechanism runs over it, and sets to None every variable
1037 # teardown mechanism runs over it, and sets to None every variable
1038 # present in that module. Top-level references to objects from the
1038 # present in that module. Top-level references to objects from the
1039 # script survive, because the user_ns is updated with them. However,
1039 # script survive, because the user_ns is updated with them. However,
1040 # calling functions defined in the script that use other things from
1040 # calling functions defined in the script that use other things from
1041 # the script will fail, because the function's closure had references
1041 # the script will fail, because the function's closure had references
1042 # to the original objects, which are now all None. So we must protect
1042 # to the original objects, which are now all None. So we must protect
1043 # these modules from deletion by keeping a cache.
1043 # these modules from deletion by keeping a cache.
1044 #
1044 #
1045 # To avoid keeping stale modules around (we only need the one from the
1045 # To avoid keeping stale modules around (we only need the one from the
1046 # last run), we use a dict keyed with the full path to the script, so
1046 # last run), we use a dict keyed with the full path to the script, so
1047 # only the last version of the module is held in the cache. Note,
1047 # only the last version of the module is held in the cache. Note,
1048 # however, that we must cache the module *namespace contents* (their
1048 # however, that we must cache the module *namespace contents* (their
1049 # __dict__). Because if we try to cache the actual modules, old ones
1049 # __dict__). Because if we try to cache the actual modules, old ones
1050 # (uncached) could be destroyed while still holding references (such as
1050 # (uncached) could be destroyed while still holding references (such as
1051 # those held by GUI objects that tend to be long-lived)>
1051 # those held by GUI objects that tend to be long-lived)>
1052 #
1052 #
1053 # The %reset command will flush this cache. See the cache_main_mod()
1053 # The %reset command will flush this cache. See the cache_main_mod()
1054 # and clear_main_mod_cache() methods for details on use.
1054 # and clear_main_mod_cache() methods for details on use.
1055
1055
1056 # This is the cache used for 'main' namespaces
1056 # This is the cache used for 'main' namespaces
1057 self._main_mod_cache = {}
1057 self._main_mod_cache = {}
1058
1058
1059 # A table holding all the namespaces IPython deals with, so that
1059 # A table holding all the namespaces IPython deals with, so that
1060 # introspection facilities can search easily.
1060 # introspection facilities can search easily.
1061 self.ns_table = {'user_global':self.user_module.__dict__,
1061 self.ns_table = {'user_global':self.user_module.__dict__,
1062 'user_local':self.user_ns,
1062 'user_local':self.user_ns,
1063 'builtin':builtin_mod.__dict__
1063 'builtin':builtin_mod.__dict__
1064 }
1064 }
1065
1065
1066 @property
1066 @property
1067 def user_global_ns(self):
1067 def user_global_ns(self):
1068 return self.user_module.__dict__
1068 return self.user_module.__dict__
1069
1069
1070 def prepare_user_module(self, user_module=None, user_ns=None):
1070 def prepare_user_module(self, user_module=None, user_ns=None):
1071 """Prepare the module and namespace in which user code will be run.
1071 """Prepare the module and namespace in which user code will be run.
1072
1072
1073 When IPython is started normally, both parameters are None: a new module
1073 When IPython is started normally, both parameters are None: a new module
1074 is created automatically, and its __dict__ used as the namespace.
1074 is created automatically, and its __dict__ used as the namespace.
1075
1075
1076 If only user_module is provided, its __dict__ is used as the namespace.
1076 If only user_module is provided, its __dict__ is used as the namespace.
1077 If only user_ns is provided, a dummy module is created, and user_ns
1077 If only user_ns is provided, a dummy module is created, and user_ns
1078 becomes the global namespace. If both are provided (as they may be
1078 becomes the global namespace. If both are provided (as they may be
1079 when embedding), user_ns is the local namespace, and user_module
1079 when embedding), user_ns is the local namespace, and user_module
1080 provides the global namespace.
1080 provides the global namespace.
1081
1081
1082 Parameters
1082 Parameters
1083 ----------
1083 ----------
1084 user_module : module, optional
1084 user_module : module, optional
1085 The current user module in which IPython is being run. If None,
1085 The current user module in which IPython is being run. If None,
1086 a clean module will be created.
1086 a clean module will be created.
1087 user_ns : dict, optional
1087 user_ns : dict, optional
1088 A namespace in which to run interactive commands.
1088 A namespace in which to run interactive commands.
1089
1089
1090 Returns
1090 Returns
1091 -------
1091 -------
1092 A tuple of user_module and user_ns, each properly initialised.
1092 A tuple of user_module and user_ns, each properly initialised.
1093 """
1093 """
1094 if user_module is None and user_ns is not None:
1094 if user_module is None and user_ns is not None:
1095 user_ns.setdefault("__name__", "__main__")
1095 user_ns.setdefault("__name__", "__main__")
1096 user_module = DummyMod()
1096 user_module = DummyMod()
1097 user_module.__dict__ = user_ns
1097 user_module.__dict__ = user_ns
1098
1098
1099 if user_module is None:
1099 if user_module is None:
1100 user_module = types.ModuleType("__main__",
1100 user_module = types.ModuleType("__main__",
1101 doc="Automatically created module for IPython interactive environment")
1101 doc="Automatically created module for IPython interactive environment")
1102
1102
1103 # We must ensure that __builtin__ (without the final 's') is always
1103 # We must ensure that __builtin__ (without the final 's') is always
1104 # available and pointing to the __builtin__ *module*. For more details:
1104 # available and pointing to the __builtin__ *module*. For more details:
1105 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1105 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1106 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1106 user_module.__dict__.setdefault('__builtin__', builtin_mod)
1107 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1107 user_module.__dict__.setdefault('__builtins__', builtin_mod)
1108
1108
1109 if user_ns is None:
1109 if user_ns is None:
1110 user_ns = user_module.__dict__
1110 user_ns = user_module.__dict__
1111
1111
1112 return user_module, user_ns
1112 return user_module, user_ns
1113
1113
1114 def init_sys_modules(self):
1114 def init_sys_modules(self):
1115 # We need to insert into sys.modules something that looks like a
1115 # We need to insert into sys.modules something that looks like a
1116 # module but which accesses the IPython namespace, for shelve and
1116 # module but which accesses the IPython namespace, for shelve and
1117 # pickle to work interactively. Normally they rely on getting
1117 # pickle to work interactively. Normally they rely on getting
1118 # everything out of __main__, but for embedding purposes each IPython
1118 # everything out of __main__, but for embedding purposes each IPython
1119 # instance has its own private namespace, so we can't go shoving
1119 # instance has its own private namespace, so we can't go shoving
1120 # everything into __main__.
1120 # everything into __main__.
1121
1121
1122 # note, however, that we should only do this for non-embedded
1122 # note, however, that we should only do this for non-embedded
1123 # ipythons, which really mimic the __main__.__dict__ with their own
1123 # ipythons, which really mimic the __main__.__dict__ with their own
1124 # namespace. Embedded instances, on the other hand, should not do
1124 # namespace. Embedded instances, on the other hand, should not do
1125 # this because they need to manage the user local/global namespaces
1125 # this because they need to manage the user local/global namespaces
1126 # only, but they live within a 'normal' __main__ (meaning, they
1126 # only, but they live within a 'normal' __main__ (meaning, they
1127 # shouldn't overtake the execution environment of the script they're
1127 # shouldn't overtake the execution environment of the script they're
1128 # embedded in).
1128 # embedded in).
1129
1129
1130 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1130 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
1131 main_name = self.user_module.__name__
1131 main_name = self.user_module.__name__
1132 sys.modules[main_name] = self.user_module
1132 sys.modules[main_name] = self.user_module
1133
1133
1134 def init_user_ns(self):
1134 def init_user_ns(self):
1135 """Initialize all user-visible namespaces to their minimum defaults.
1135 """Initialize all user-visible namespaces to their minimum defaults.
1136
1136
1137 Certain history lists are also initialized here, as they effectively
1137 Certain history lists are also initialized here, as they effectively
1138 act as user namespaces.
1138 act as user namespaces.
1139
1139
1140 Notes
1140 Notes
1141 -----
1141 -----
1142 All data structures here are only filled in, they are NOT reset by this
1142 All data structures here are only filled in, they are NOT reset by this
1143 method. If they were not empty before, data will simply be added to
1143 method. If they were not empty before, data will simply be added to
1144 therm.
1144 therm.
1145 """
1145 """
1146 # This function works in two parts: first we put a few things in
1146 # This function works in two parts: first we put a few things in
1147 # user_ns, and we sync that contents into user_ns_hidden so that these
1147 # user_ns, and we sync that contents into user_ns_hidden so that these
1148 # initial variables aren't shown by %who. After the sync, we add the
1148 # initial variables aren't shown by %who. After the sync, we add the
1149 # rest of what we *do* want the user to see with %who even on a new
1149 # rest of what we *do* want the user to see with %who even on a new
1150 # session (probably nothing, so they really only see their own stuff)
1150 # session (probably nothing, so they really only see their own stuff)
1151
1151
1152 # The user dict must *always* have a __builtin__ reference to the
1152 # The user dict must *always* have a __builtin__ reference to the
1153 # Python standard __builtin__ namespace, which must be imported.
1153 # Python standard __builtin__ namespace, which must be imported.
1154 # This is so that certain operations in prompt evaluation can be
1154 # This is so that certain operations in prompt evaluation can be
1155 # reliably executed with builtins. Note that we can NOT use
1155 # reliably executed with builtins. Note that we can NOT use
1156 # __builtins__ (note the 's'), because that can either be a dict or a
1156 # __builtins__ (note the 's'), because that can either be a dict or a
1157 # module, and can even mutate at runtime, depending on the context
1157 # module, and can even mutate at runtime, depending on the context
1158 # (Python makes no guarantees on it). In contrast, __builtin__ is
1158 # (Python makes no guarantees on it). In contrast, __builtin__ is
1159 # always a module object, though it must be explicitly imported.
1159 # always a module object, though it must be explicitly imported.
1160
1160
1161 # For more details:
1161 # For more details:
1162 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1162 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
1163 ns = {}
1163 ns = {}
1164
1164
1165 # make global variables for user access to the histories
1165 # make global variables for user access to the histories
1166 ns['_ih'] = self.history_manager.input_hist_parsed
1166 ns['_ih'] = self.history_manager.input_hist_parsed
1167 ns['_oh'] = self.history_manager.output_hist
1167 ns['_oh'] = self.history_manager.output_hist
1168 ns['_dh'] = self.history_manager.dir_hist
1168 ns['_dh'] = self.history_manager.dir_hist
1169
1169
1170 # user aliases to input and output histories. These shouldn't show up
1170 # user aliases to input and output histories. These shouldn't show up
1171 # in %who, as they can have very large reprs.
1171 # in %who, as they can have very large reprs.
1172 ns['In'] = self.history_manager.input_hist_parsed
1172 ns['In'] = self.history_manager.input_hist_parsed
1173 ns['Out'] = self.history_manager.output_hist
1173 ns['Out'] = self.history_manager.output_hist
1174
1174
1175 # Store myself as the public api!!!
1175 # Store myself as the public api!!!
1176 ns['get_ipython'] = self.get_ipython
1176 ns['get_ipython'] = self.get_ipython
1177
1177
1178 ns['exit'] = self.exiter
1178 ns['exit'] = self.exiter
1179 ns['quit'] = self.exiter
1179 ns['quit'] = self.exiter
1180
1180
1181 # Sync what we've added so far to user_ns_hidden so these aren't seen
1181 # Sync what we've added so far to user_ns_hidden so these aren't seen
1182 # by %who
1182 # by %who
1183 self.user_ns_hidden.update(ns)
1183 self.user_ns_hidden.update(ns)
1184
1184
1185 # Anything put into ns now would show up in %who. Think twice before
1185 # Anything put into ns now would show up in %who. Think twice before
1186 # putting anything here, as we really want %who to show the user their
1186 # putting anything here, as we really want %who to show the user their
1187 # stuff, not our variables.
1187 # stuff, not our variables.
1188
1188
1189 # Finally, update the real user's namespace
1189 # Finally, update the real user's namespace
1190 self.user_ns.update(ns)
1190 self.user_ns.update(ns)
1191
1191
1192 @property
1192 @property
1193 def all_ns_refs(self):
1193 def all_ns_refs(self):
1194 """Get a list of references to all the namespace dictionaries in which
1194 """Get a list of references to all the namespace dictionaries in which
1195 IPython might store a user-created object.
1195 IPython might store a user-created object.
1196
1196
1197 Note that this does not include the displayhook, which also caches
1197 Note that this does not include the displayhook, which also caches
1198 objects from the output."""
1198 objects from the output."""
1199 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1199 return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \
1200 [m.__dict__ for m in self._main_mod_cache.values()]
1200 [m.__dict__ for m in self._main_mod_cache.values()]
1201
1201
1202 def reset(self, new_session=True):
1202 def reset(self, new_session=True):
1203 """Clear all internal namespaces, and attempt to release references to
1203 """Clear all internal namespaces, and attempt to release references to
1204 user objects.
1204 user objects.
1205
1205
1206 If new_session is True, a new history session will be opened.
1206 If new_session is True, a new history session will be opened.
1207 """
1207 """
1208 # Clear histories
1208 # Clear histories
1209 self.history_manager.reset(new_session)
1209 self.history_manager.reset(new_session)
1210 # Reset counter used to index all histories
1210 # Reset counter used to index all histories
1211 if new_session:
1211 if new_session:
1212 self.execution_count = 1
1212 self.execution_count = 1
1213
1213
1214 # Flush cached output items
1214 # Flush cached output items
1215 if self.displayhook.do_full_cache:
1215 if self.displayhook.do_full_cache:
1216 self.displayhook.flush()
1216 self.displayhook.flush()
1217
1217
1218 # The main execution namespaces must be cleared very carefully,
1218 # The main execution namespaces must be cleared very carefully,
1219 # skipping the deletion of the builtin-related keys, because doing so
1219 # skipping the deletion of the builtin-related keys, because doing so
1220 # would cause errors in many object's __del__ methods.
1220 # would cause errors in many object's __del__ methods.
1221 if self.user_ns is not self.user_global_ns:
1221 if self.user_ns is not self.user_global_ns:
1222 self.user_ns.clear()
1222 self.user_ns.clear()
1223 ns = self.user_global_ns
1223 ns = self.user_global_ns
1224 drop_keys = set(ns.keys())
1224 drop_keys = set(ns.keys())
1225 drop_keys.discard('__builtin__')
1225 drop_keys.discard('__builtin__')
1226 drop_keys.discard('__builtins__')
1226 drop_keys.discard('__builtins__')
1227 drop_keys.discard('__name__')
1227 drop_keys.discard('__name__')
1228 for k in drop_keys:
1228 for k in drop_keys:
1229 del ns[k]
1229 del ns[k]
1230
1230
1231 self.user_ns_hidden.clear()
1231 self.user_ns_hidden.clear()
1232
1232
1233 # Restore the user namespaces to minimal usability
1233 # Restore the user namespaces to minimal usability
1234 self.init_user_ns()
1234 self.init_user_ns()
1235
1235
1236 # Restore the default and user aliases
1236 # Restore the default and user aliases
1237 self.alias_manager.clear_aliases()
1237 self.alias_manager.clear_aliases()
1238 self.alias_manager.init_aliases()
1238 self.alias_manager.init_aliases()
1239
1239
1240 # Flush the private list of module references kept for script
1240 # Flush the private list of module references kept for script
1241 # execution protection
1241 # execution protection
1242 self.clear_main_mod_cache()
1242 self.clear_main_mod_cache()
1243
1243
1244 def del_var(self, varname, by_name=False):
1244 def del_var(self, varname, by_name=False):
1245 """Delete a variable from the various namespaces, so that, as
1245 """Delete a variable from the various namespaces, so that, as
1246 far as possible, we're not keeping any hidden references to it.
1246 far as possible, we're not keeping any hidden references to it.
1247
1247
1248 Parameters
1248 Parameters
1249 ----------
1249 ----------
1250 varname : str
1250 varname : str
1251 The name of the variable to delete.
1251 The name of the variable to delete.
1252 by_name : bool
1252 by_name : bool
1253 If True, delete variables with the given name in each
1253 If True, delete variables with the given name in each
1254 namespace. If False (default), find the variable in the user
1254 namespace. If False (default), find the variable in the user
1255 namespace, and delete references to it.
1255 namespace, and delete references to it.
1256 """
1256 """
1257 if varname in ('__builtin__', '__builtins__'):
1257 if varname in ('__builtin__', '__builtins__'):
1258 raise ValueError("Refusing to delete %s" % varname)
1258 raise ValueError("Refusing to delete %s" % varname)
1259
1259
1260 ns_refs = self.all_ns_refs
1260 ns_refs = self.all_ns_refs
1261
1261
1262 if by_name: # Delete by name
1262 if by_name: # Delete by name
1263 for ns in ns_refs:
1263 for ns in ns_refs:
1264 try:
1264 try:
1265 del ns[varname]
1265 del ns[varname]
1266 except KeyError:
1266 except KeyError:
1267 pass
1267 pass
1268 else: # Delete by object
1268 else: # Delete by object
1269 try:
1269 try:
1270 obj = self.user_ns[varname]
1270 obj = self.user_ns[varname]
1271 except KeyError:
1271 except KeyError:
1272 raise NameError("name '%s' is not defined" % varname)
1272 raise NameError("name '%s' is not defined" % varname)
1273 # Also check in output history
1273 # Also check in output history
1274 ns_refs.append(self.history_manager.output_hist)
1274 ns_refs.append(self.history_manager.output_hist)
1275 for ns in ns_refs:
1275 for ns in ns_refs:
1276 to_delete = [n for n, o in ns.items() if o is obj]
1276 to_delete = [n for n, o in ns.items() if o is obj]
1277 for name in to_delete:
1277 for name in to_delete:
1278 del ns[name]
1278 del ns[name]
1279
1279
1280 # displayhook keeps extra references, but not in a dictionary
1280 # displayhook keeps extra references, but not in a dictionary
1281 for name in ('_', '__', '___'):
1281 for name in ('_', '__', '___'):
1282 if getattr(self.displayhook, name) is obj:
1282 if getattr(self.displayhook, name) is obj:
1283 setattr(self.displayhook, name, None)
1283 setattr(self.displayhook, name, None)
1284
1284
1285 def reset_selective(self, regex=None):
1285 def reset_selective(self, regex=None):
1286 """Clear selective variables from internal namespaces based on a
1286 """Clear selective variables from internal namespaces based on a
1287 specified regular expression.
1287 specified regular expression.
1288
1288
1289 Parameters
1289 Parameters
1290 ----------
1290 ----------
1291 regex : string or compiled pattern, optional
1291 regex : string or compiled pattern, optional
1292 A regular expression pattern that will be used in searching
1292 A regular expression pattern that will be used in searching
1293 variable names in the users namespaces.
1293 variable names in the users namespaces.
1294 """
1294 """
1295 if regex is not None:
1295 if regex is not None:
1296 try:
1296 try:
1297 m = re.compile(regex)
1297 m = re.compile(regex)
1298 except TypeError:
1298 except TypeError:
1299 raise TypeError('regex must be a string or compiled pattern')
1299 raise TypeError('regex must be a string or compiled pattern')
1300 # Search for keys in each namespace that match the given regex
1300 # Search for keys in each namespace that match the given regex
1301 # If a match is found, delete the key/value pair.
1301 # If a match is found, delete the key/value pair.
1302 for ns in self.all_ns_refs:
1302 for ns in self.all_ns_refs:
1303 for var in ns:
1303 for var in ns:
1304 if m.search(var):
1304 if m.search(var):
1305 del ns[var]
1305 del ns[var]
1306
1306
1307 def push(self, variables, interactive=True):
1307 def push(self, variables, interactive=True):
1308 """Inject a group of variables into the IPython user namespace.
1308 """Inject a group of variables into the IPython user namespace.
1309
1309
1310 Parameters
1310 Parameters
1311 ----------
1311 ----------
1312 variables : dict, str or list/tuple of str
1312 variables : dict, str or list/tuple of str
1313 The variables to inject into the user's namespace. If a dict, a
1313 The variables to inject into the user's namespace. If a dict, a
1314 simple update is done. If a str, the string is assumed to have
1314 simple update is done. If a str, the string is assumed to have
1315 variable names separated by spaces. A list/tuple of str can also
1315 variable names separated by spaces. A list/tuple of str can also
1316 be used to give the variable names. If just the variable names are
1316 be used to give the variable names. If just the variable names are
1317 give (list/tuple/str) then the variable values looked up in the
1317 give (list/tuple/str) then the variable values looked up in the
1318 callers frame.
1318 callers frame.
1319 interactive : bool
1319 interactive : bool
1320 If True (default), the variables will be listed with the ``who``
1320 If True (default), the variables will be listed with the ``who``
1321 magic.
1321 magic.
1322 """
1322 """
1323 vdict = None
1323 vdict = None
1324
1324
1325 # We need a dict of name/value pairs to do namespace updates.
1325 # We need a dict of name/value pairs to do namespace updates.
1326 if isinstance(variables, dict):
1326 if isinstance(variables, dict):
1327 vdict = variables
1327 vdict = variables
1328 elif isinstance(variables, (str, list, tuple)):
1328 elif isinstance(variables, (str, list, tuple)):
1329 if isinstance(variables, str):
1329 if isinstance(variables, str):
1330 vlist = variables.split()
1330 vlist = variables.split()
1331 else:
1331 else:
1332 vlist = variables
1332 vlist = variables
1333 vdict = {}
1333 vdict = {}
1334 cf = sys._getframe(1)
1334 cf = sys._getframe(1)
1335 for name in vlist:
1335 for name in vlist:
1336 try:
1336 try:
1337 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1337 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1338 except:
1338 except:
1339 print('Could not get variable %s from %s' %
1339 print('Could not get variable %s from %s' %
1340 (name,cf.f_code.co_name))
1340 (name,cf.f_code.co_name))
1341 else:
1341 else:
1342 raise ValueError('variables must be a dict/str/list/tuple')
1342 raise ValueError('variables must be a dict/str/list/tuple')
1343
1343
1344 # Propagate variables to user namespace
1344 # Propagate variables to user namespace
1345 self.user_ns.update(vdict)
1345 self.user_ns.update(vdict)
1346
1346
1347 # And configure interactive visibility
1347 # And configure interactive visibility
1348 user_ns_hidden = self.user_ns_hidden
1348 user_ns_hidden = self.user_ns_hidden
1349 if interactive:
1349 if interactive:
1350 for name in vdict:
1350 for name in vdict:
1351 user_ns_hidden.pop(name, None)
1351 user_ns_hidden.pop(name, None)
1352 else:
1352 else:
1353 user_ns_hidden.update(vdict)
1353 user_ns_hidden.update(vdict)
1354
1354
1355 def drop_by_id(self, variables):
1355 def drop_by_id(self, variables):
1356 """Remove a dict of variables from the user namespace, if they are the
1356 """Remove a dict of variables from the user namespace, if they are the
1357 same as the values in the dictionary.
1357 same as the values in the dictionary.
1358
1358
1359 This is intended for use by extensions: variables that they've added can
1359 This is intended for use by extensions: variables that they've added can
1360 be taken back out if they are unloaded, without removing any that the
1360 be taken back out if they are unloaded, without removing any that the
1361 user has overwritten.
1361 user has overwritten.
1362
1362
1363 Parameters
1363 Parameters
1364 ----------
1364 ----------
1365 variables : dict
1365 variables : dict
1366 A dictionary mapping object names (as strings) to the objects.
1366 A dictionary mapping object names (as strings) to the objects.
1367 """
1367 """
1368 for name, obj in variables.items():
1368 for name, obj in variables.items():
1369 if name in self.user_ns and self.user_ns[name] is obj:
1369 if name in self.user_ns and self.user_ns[name] is obj:
1370 del self.user_ns[name]
1370 del self.user_ns[name]
1371 self.user_ns_hidden.pop(name, None)
1371 self.user_ns_hidden.pop(name, None)
1372
1372
1373 #-------------------------------------------------------------------------
1373 #-------------------------------------------------------------------------
1374 # Things related to object introspection
1374 # Things related to object introspection
1375 #-------------------------------------------------------------------------
1375 #-------------------------------------------------------------------------
1376
1376
1377 def _ofind(self, oname, namespaces=None):
1377 def _ofind(self, oname, namespaces=None):
1378 """Find an object in the available namespaces.
1378 """Find an object in the available namespaces.
1379
1379
1380 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1380 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1381
1381
1382 Has special code to detect magic functions.
1382 Has special code to detect magic functions.
1383 """
1383 """
1384 oname = oname.strip()
1384 oname = oname.strip()
1385 if not oname.startswith(ESC_MAGIC) and \
1385 if not oname.startswith(ESC_MAGIC) and \
1386 not oname.startswith(ESC_MAGIC2) and \
1386 not oname.startswith(ESC_MAGIC2) and \
1387 not all(a.isidentifier() for a in oname.split(".")):
1387 not all(a.isidentifier() for a in oname.split(".")):
1388 return {'found': False}
1388 return {'found': False}
1389
1389
1390 if namespaces is None:
1390 if namespaces is None:
1391 # Namespaces to search in:
1391 # Namespaces to search in:
1392 # Put them in a list. The order is important so that we
1392 # Put them in a list. The order is important so that we
1393 # find things in the same order that Python finds them.
1393 # find things in the same order that Python finds them.
1394 namespaces = [ ('Interactive', self.user_ns),
1394 namespaces = [ ('Interactive', self.user_ns),
1395 ('Interactive (global)', self.user_global_ns),
1395 ('Interactive (global)', self.user_global_ns),
1396 ('Python builtin', builtin_mod.__dict__),
1396 ('Python builtin', builtin_mod.__dict__),
1397 ]
1397 ]
1398
1398
1399 ismagic = False
1399 ismagic = False
1400 isalias = False
1400 isalias = False
1401 found = False
1401 found = False
1402 ospace = None
1402 ospace = None
1403 parent = None
1403 parent = None
1404 obj = None
1404 obj = None
1405
1405
1406 # Look for the given name by splitting it in parts. If the head is
1406 # Look for the given name by splitting it in parts. If the head is
1407 # found, then we look for all the remaining parts as members, and only
1407 # found, then we look for all the remaining parts as members, and only
1408 # declare success if we can find them all.
1408 # declare success if we can find them all.
1409 oname_parts = oname.split('.')
1409 oname_parts = oname.split('.')
1410 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1410 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1411 for nsname,ns in namespaces:
1411 for nsname,ns in namespaces:
1412 try:
1412 try:
1413 obj = ns[oname_head]
1413 obj = ns[oname_head]
1414 except KeyError:
1414 except KeyError:
1415 continue
1415 continue
1416 else:
1416 else:
1417 for idx, part in enumerate(oname_rest):
1417 for idx, part in enumerate(oname_rest):
1418 try:
1418 try:
1419 parent = obj
1419 parent = obj
1420 # The last part is looked up in a special way to avoid
1420 # The last part is looked up in a special way to avoid
1421 # descriptor invocation as it may raise or have side
1421 # descriptor invocation as it may raise or have side
1422 # effects.
1422 # effects.
1423 if idx == len(oname_rest) - 1:
1423 if idx == len(oname_rest) - 1:
1424 obj = self._getattr_property(obj, part)
1424 obj = self._getattr_property(obj, part)
1425 else:
1425 else:
1426 obj = getattr(obj, part)
1426 obj = getattr(obj, part)
1427 except:
1427 except:
1428 # Blanket except b/c some badly implemented objects
1428 # Blanket except b/c some badly implemented objects
1429 # allow __getattr__ to raise exceptions other than
1429 # allow __getattr__ to raise exceptions other than
1430 # AttributeError, which then crashes IPython.
1430 # AttributeError, which then crashes IPython.
1431 break
1431 break
1432 else:
1432 else:
1433 # If we finish the for loop (no break), we got all members
1433 # If we finish the for loop (no break), we got all members
1434 found = True
1434 found = True
1435 ospace = nsname
1435 ospace = nsname
1436 break # namespace loop
1436 break # namespace loop
1437
1437
1438 # Try to see if it's magic
1438 # Try to see if it's magic
1439 if not found:
1439 if not found:
1440 obj = None
1440 obj = None
1441 if oname.startswith(ESC_MAGIC2):
1441 if oname.startswith(ESC_MAGIC2):
1442 oname = oname.lstrip(ESC_MAGIC2)
1442 oname = oname.lstrip(ESC_MAGIC2)
1443 obj = self.find_cell_magic(oname)
1443 obj = self.find_cell_magic(oname)
1444 elif oname.startswith(ESC_MAGIC):
1444 elif oname.startswith(ESC_MAGIC):
1445 oname = oname.lstrip(ESC_MAGIC)
1445 oname = oname.lstrip(ESC_MAGIC)
1446 obj = self.find_line_magic(oname)
1446 obj = self.find_line_magic(oname)
1447 else:
1447 else:
1448 # search without prefix, so run? will find %run?
1448 # search without prefix, so run? will find %run?
1449 obj = self.find_line_magic(oname)
1449 obj = self.find_line_magic(oname)
1450 if obj is None:
1450 if obj is None:
1451 obj = self.find_cell_magic(oname)
1451 obj = self.find_cell_magic(oname)
1452 if obj is not None:
1452 if obj is not None:
1453 found = True
1453 found = True
1454 ospace = 'IPython internal'
1454 ospace = 'IPython internal'
1455 ismagic = True
1455 ismagic = True
1456 isalias = isinstance(obj, Alias)
1456 isalias = isinstance(obj, Alias)
1457
1457
1458 # Last try: special-case some literals like '', [], {}, etc:
1458 # Last try: special-case some literals like '', [], {}, etc:
1459 if not found and oname_head in ["''",'""','[]','{}','()']:
1459 if not found and oname_head in ["''",'""','[]','{}','()']:
1460 obj = eval(oname_head)
1460 obj = eval(oname_head)
1461 found = True
1461 found = True
1462 ospace = 'Interactive'
1462 ospace = 'Interactive'
1463
1463
1464 return {
1464 return {
1465 'obj':obj,
1465 'obj':obj,
1466 'found':found,
1466 'found':found,
1467 'parent':parent,
1467 'parent':parent,
1468 'ismagic':ismagic,
1468 'ismagic':ismagic,
1469 'isalias':isalias,
1469 'isalias':isalias,
1470 'namespace':ospace
1470 'namespace':ospace
1471 }
1471 }
1472
1472
1473 @staticmethod
1473 @staticmethod
1474 def _getattr_property(obj, attrname):
1474 def _getattr_property(obj, attrname):
1475 """Property-aware getattr to use in object finding.
1475 """Property-aware getattr to use in object finding.
1476
1476
1477 If attrname represents a property, return it unevaluated (in case it has
1477 If attrname represents a property, return it unevaluated (in case it has
1478 side effects or raises an error.
1478 side effects or raises an error.
1479
1479
1480 """
1480 """
1481 if not isinstance(obj, type):
1481 if not isinstance(obj, type):
1482 try:
1482 try:
1483 # `getattr(type(obj), attrname)` is not guaranteed to return
1483 # `getattr(type(obj), attrname)` is not guaranteed to return
1484 # `obj`, but does so for property:
1484 # `obj`, but does so for property:
1485 #
1485 #
1486 # property.__get__(self, None, cls) -> self
1486 # property.__get__(self, None, cls) -> self
1487 #
1487 #
1488 # The universal alternative is to traverse the mro manually
1488 # The universal alternative is to traverse the mro manually
1489 # searching for attrname in class dicts.
1489 # searching for attrname in class dicts.
1490 attr = getattr(type(obj), attrname)
1490 attr = getattr(type(obj), attrname)
1491 except AttributeError:
1491 except AttributeError:
1492 pass
1492 pass
1493 else:
1493 else:
1494 # This relies on the fact that data descriptors (with both
1494 # This relies on the fact that data descriptors (with both
1495 # __get__ & __set__ magic methods) take precedence over
1495 # __get__ & __set__ magic methods) take precedence over
1496 # instance-level attributes:
1496 # instance-level attributes:
1497 #
1497 #
1498 # class A(object):
1498 # class A(object):
1499 # @property
1499 # @property
1500 # def foobar(self): return 123
1500 # def foobar(self): return 123
1501 # a = A()
1501 # a = A()
1502 # a.__dict__['foobar'] = 345
1502 # a.__dict__['foobar'] = 345
1503 # a.foobar # == 123
1503 # a.foobar # == 123
1504 #
1504 #
1505 # So, a property may be returned right away.
1505 # So, a property may be returned right away.
1506 if isinstance(attr, property):
1506 if isinstance(attr, property):
1507 return attr
1507 return attr
1508
1508
1509 # Nothing helped, fall back.
1509 # Nothing helped, fall back.
1510 return getattr(obj, attrname)
1510 return getattr(obj, attrname)
1511
1511
1512 def _object_find(self, oname, namespaces=None):
1512 def _object_find(self, oname, namespaces=None):
1513 """Find an object and return a struct with info about it."""
1513 """Find an object and return a struct with info about it."""
1514 return Struct(self._ofind(oname, namespaces))
1514 return Struct(self._ofind(oname, namespaces))
1515
1515
1516 def _inspect(self, meth, oname, namespaces=None, **kw):
1516 def _inspect(self, meth, oname, namespaces=None, **kw):
1517 """Generic interface to the inspector system.
1517 """Generic interface to the inspector system.
1518
1518
1519 This function is meant to be called by pdef, pdoc & friends.
1519 This function is meant to be called by pdef, pdoc & friends.
1520 """
1520 """
1521 info = self._object_find(oname, namespaces)
1521 info = self._object_find(oname, namespaces)
1522 docformat = sphinxify if self.sphinxify_docstring else None
1522 docformat = sphinxify if self.sphinxify_docstring else None
1523 if info.found:
1523 if info.found:
1524 pmethod = getattr(self.inspector, meth)
1524 pmethod = getattr(self.inspector, meth)
1525 # TODO: only apply format_screen to the plain/text repr of the mime
1525 # TODO: only apply format_screen to the plain/text repr of the mime
1526 # bundle.
1526 # bundle.
1527 formatter = format_screen if info.ismagic else docformat
1527 formatter = format_screen if info.ismagic else docformat
1528 if meth == 'pdoc':
1528 if meth == 'pdoc':
1529 pmethod(info.obj, oname, formatter)
1529 pmethod(info.obj, oname, formatter)
1530 elif meth == 'pinfo':
1530 elif meth == 'pinfo':
1531 pmethod(info.obj, oname, formatter, info,
1531 pmethod(info.obj, oname, formatter, info,
1532 enable_html_pager=self.enable_html_pager, **kw)
1532 enable_html_pager=self.enable_html_pager, **kw)
1533 else:
1533 else:
1534 pmethod(info.obj, oname)
1534 pmethod(info.obj, oname)
1535 else:
1535 else:
1536 print('Object `%s` not found.' % oname)
1536 print('Object `%s` not found.' % oname)
1537 return 'not found' # so callers can take other action
1537 return 'not found' # so callers can take other action
1538
1538
1539 def object_inspect(self, oname, detail_level=0):
1539 def object_inspect(self, oname, detail_level=0):
1540 """Get object info about oname"""
1540 """Get object info about oname"""
1541 with self.builtin_trap:
1541 with self.builtin_trap:
1542 info = self._object_find(oname)
1542 info = self._object_find(oname)
1543 if info.found:
1543 if info.found:
1544 return self.inspector.info(info.obj, oname, info=info,
1544 return self.inspector.info(info.obj, oname, info=info,
1545 detail_level=detail_level
1545 detail_level=detail_level
1546 )
1546 )
1547 else:
1547 else:
1548 return oinspect.object_info(name=oname, found=False)
1548 return oinspect.object_info(name=oname, found=False)
1549
1549
1550 def object_inspect_text(self, oname, detail_level=0):
1550 def object_inspect_text(self, oname, detail_level=0):
1551 """Get object info as formatted text"""
1551 """Get object info as formatted text"""
1552 return self.object_inspect_mime(oname, detail_level)['text/plain']
1552 return self.object_inspect_mime(oname, detail_level)['text/plain']
1553
1553
1554 def object_inspect_mime(self, oname, detail_level=0):
1554 def object_inspect_mime(self, oname, detail_level=0):
1555 """Get object info as a mimebundle of formatted representations.
1555 """Get object info as a mimebundle of formatted representations.
1556
1556
1557 A mimebundle is a dictionary, keyed by mime-type.
1557 A mimebundle is a dictionary, keyed by mime-type.
1558 It must always have the key `'text/plain'`.
1558 It must always have the key `'text/plain'`.
1559 """
1559 """
1560 with self.builtin_trap:
1560 with self.builtin_trap:
1561 info = self._object_find(oname)
1561 info = self._object_find(oname)
1562 if info.found:
1562 if info.found:
1563 return self.inspector._get_info(info.obj, oname, info=info,
1563 return self.inspector._get_info(info.obj, oname, info=info,
1564 detail_level=detail_level
1564 detail_level=detail_level
1565 )
1565 )
1566 else:
1566 else:
1567 raise KeyError(oname)
1567 raise KeyError(oname)
1568
1568
1569 #-------------------------------------------------------------------------
1569 #-------------------------------------------------------------------------
1570 # Things related to history management
1570 # Things related to history management
1571 #-------------------------------------------------------------------------
1571 #-------------------------------------------------------------------------
1572
1572
1573 def init_history(self):
1573 def init_history(self):
1574 """Sets up the command history, and starts regular autosaves."""
1574 """Sets up the command history, and starts regular autosaves."""
1575 self.history_manager = HistoryManager(shell=self, parent=self)
1575 self.history_manager = HistoryManager(shell=self, parent=self)
1576 self.configurables.append(self.history_manager)
1576 self.configurables.append(self.history_manager)
1577
1577
1578 #-------------------------------------------------------------------------
1578 #-------------------------------------------------------------------------
1579 # Things related to exception handling and tracebacks (not debugging)
1579 # Things related to exception handling and tracebacks (not debugging)
1580 #-------------------------------------------------------------------------
1580 #-------------------------------------------------------------------------
1581
1581
1582 debugger_cls = Pdb
1582 debugger_cls = Pdb
1583
1583
1584 def init_traceback_handlers(self, custom_exceptions):
1584 def init_traceback_handlers(self, custom_exceptions):
1585 # Syntax error handler.
1585 # Syntax error handler.
1586 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1586 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self)
1587
1587
1588 # The interactive one is initialized with an offset, meaning we always
1588 # The interactive one is initialized with an offset, meaning we always
1589 # want to remove the topmost item in the traceback, which is our own
1589 # want to remove the topmost item in the traceback, which is our own
1590 # internal code. Valid modes: ['Plain','Context','Verbose']
1590 # internal code. Valid modes: ['Plain','Context','Verbose']
1591 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1591 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1592 color_scheme='NoColor',
1592 color_scheme='NoColor',
1593 tb_offset = 1,
1593 tb_offset = 1,
1594 check_cache=check_linecache_ipython,
1594 check_cache=check_linecache_ipython,
1595 debugger_cls=self.debugger_cls, parent=self)
1595 debugger_cls=self.debugger_cls, parent=self)
1596
1596
1597 # The instance will store a pointer to the system-wide exception hook,
1597 # The instance will store a pointer to the system-wide exception hook,
1598 # so that runtime code (such as magics) can access it. This is because
1598 # so that runtime code (such as magics) can access it. This is because
1599 # during the read-eval loop, it may get temporarily overwritten.
1599 # during the read-eval loop, it may get temporarily overwritten.
1600 self.sys_excepthook = sys.excepthook
1600 self.sys_excepthook = sys.excepthook
1601
1601
1602 # and add any custom exception handlers the user may have specified
1602 # and add any custom exception handlers the user may have specified
1603 self.set_custom_exc(*custom_exceptions)
1603 self.set_custom_exc(*custom_exceptions)
1604
1604
1605 # Set the exception mode
1605 # Set the exception mode
1606 self.InteractiveTB.set_mode(mode=self.xmode)
1606 self.InteractiveTB.set_mode(mode=self.xmode)
1607
1607
1608 def set_custom_exc(self, exc_tuple, handler):
1608 def set_custom_exc(self, exc_tuple, handler):
1609 """set_custom_exc(exc_tuple, handler)
1609 """set_custom_exc(exc_tuple, handler)
1610
1610
1611 Set a custom exception handler, which will be called if any of the
1611 Set a custom exception handler, which will be called if any of the
1612 exceptions in exc_tuple occur in the mainloop (specifically, in the
1612 exceptions in exc_tuple occur in the mainloop (specifically, in the
1613 run_code() method).
1613 run_code() method).
1614
1614
1615 Parameters
1615 Parameters
1616 ----------
1616 ----------
1617
1617
1618 exc_tuple : tuple of exception classes
1618 exc_tuple : tuple of exception classes
1619 A *tuple* of exception classes, for which to call the defined
1619 A *tuple* of exception classes, for which to call the defined
1620 handler. It is very important that you use a tuple, and NOT A
1620 handler. It is very important that you use a tuple, and NOT A
1621 LIST here, because of the way Python's except statement works. If
1621 LIST here, because of the way Python's except statement works. If
1622 you only want to trap a single exception, use a singleton tuple::
1622 you only want to trap a single exception, use a singleton tuple::
1623
1623
1624 exc_tuple == (MyCustomException,)
1624 exc_tuple == (MyCustomException,)
1625
1625
1626 handler : callable
1626 handler : callable
1627 handler must have the following signature::
1627 handler must have the following signature::
1628
1628
1629 def my_handler(self, etype, value, tb, tb_offset=None):
1629 def my_handler(self, etype, value, tb, tb_offset=None):
1630 ...
1630 ...
1631 return structured_traceback
1631 return structured_traceback
1632
1632
1633 Your handler must return a structured traceback (a list of strings),
1633 Your handler must return a structured traceback (a list of strings),
1634 or None.
1634 or None.
1635
1635
1636 This will be made into an instance method (via types.MethodType)
1636 This will be made into an instance method (via types.MethodType)
1637 of IPython itself, and it will be called if any of the exceptions
1637 of IPython itself, and it will be called if any of the exceptions
1638 listed in the exc_tuple are caught. If the handler is None, an
1638 listed in the exc_tuple are caught. If the handler is None, an
1639 internal basic one is used, which just prints basic info.
1639 internal basic one is used, which just prints basic info.
1640
1640
1641 To protect IPython from crashes, if your handler ever raises an
1641 To protect IPython from crashes, if your handler ever raises an
1642 exception or returns an invalid result, it will be immediately
1642 exception or returns an invalid result, it will be immediately
1643 disabled.
1643 disabled.
1644
1644
1645 WARNING: by putting in your own exception handler into IPython's main
1645 WARNING: by putting in your own exception handler into IPython's main
1646 execution loop, you run a very good chance of nasty crashes. This
1646 execution loop, you run a very good chance of nasty crashes. This
1647 facility should only be used if you really know what you are doing."""
1647 facility should only be used if you really know what you are doing."""
1648 if not isinstance(exc_tuple, tuple):
1648 if not isinstance(exc_tuple, tuple):
1649 raise TypeError("The custom exceptions must be given as a tuple.")
1649 raise TypeError("The custom exceptions must be given as a tuple.")
1650
1650
1651 def dummy_handler(self, etype, value, tb, tb_offset=None):
1651 def dummy_handler(self, etype, value, tb, tb_offset=None):
1652 print('*** Simple custom exception handler ***')
1652 print('*** Simple custom exception handler ***')
1653 print('Exception type :', etype)
1653 print('Exception type :', etype)
1654 print('Exception value:', value)
1654 print('Exception value:', value)
1655 print('Traceback :', tb)
1655 print('Traceback :', tb)
1656
1656
1657 def validate_stb(stb):
1657 def validate_stb(stb):
1658 """validate structured traceback return type
1658 """validate structured traceback return type
1659
1659
1660 return type of CustomTB *should* be a list of strings, but allow
1660 return type of CustomTB *should* be a list of strings, but allow
1661 single strings or None, which are harmless.
1661 single strings or None, which are harmless.
1662
1662
1663 This function will *always* return a list of strings,
1663 This function will *always* return a list of strings,
1664 and will raise a TypeError if stb is inappropriate.
1664 and will raise a TypeError if stb is inappropriate.
1665 """
1665 """
1666 msg = "CustomTB must return list of strings, not %r" % stb
1666 msg = "CustomTB must return list of strings, not %r" % stb
1667 if stb is None:
1667 if stb is None:
1668 return []
1668 return []
1669 elif isinstance(stb, str):
1669 elif isinstance(stb, str):
1670 return [stb]
1670 return [stb]
1671 elif not isinstance(stb, list):
1671 elif not isinstance(stb, list):
1672 raise TypeError(msg)
1672 raise TypeError(msg)
1673 # it's a list
1673 # it's a list
1674 for line in stb:
1674 for line in stb:
1675 # check every element
1675 # check every element
1676 if not isinstance(line, str):
1676 if not isinstance(line, str):
1677 raise TypeError(msg)
1677 raise TypeError(msg)
1678 return stb
1678 return stb
1679
1679
1680 if handler is None:
1680 if handler is None:
1681 wrapped = dummy_handler
1681 wrapped = dummy_handler
1682 else:
1682 else:
1683 def wrapped(self,etype,value,tb,tb_offset=None):
1683 def wrapped(self,etype,value,tb,tb_offset=None):
1684 """wrap CustomTB handler, to protect IPython from user code
1684 """wrap CustomTB handler, to protect IPython from user code
1685
1685
1686 This makes it harder (but not impossible) for custom exception
1686 This makes it harder (but not impossible) for custom exception
1687 handlers to crash IPython.
1687 handlers to crash IPython.
1688 """
1688 """
1689 try:
1689 try:
1690 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1690 stb = handler(self,etype,value,tb,tb_offset=tb_offset)
1691 return validate_stb(stb)
1691 return validate_stb(stb)
1692 except:
1692 except:
1693 # clear custom handler immediately
1693 # clear custom handler immediately
1694 self.set_custom_exc((), None)
1694 self.set_custom_exc((), None)
1695 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1695 print("Custom TB Handler failed, unregistering", file=sys.stderr)
1696 # show the exception in handler first
1696 # show the exception in handler first
1697 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1697 stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
1698 print(self.InteractiveTB.stb2text(stb))
1698 print(self.InteractiveTB.stb2text(stb))
1699 print("The original exception:")
1699 print("The original exception:")
1700 stb = self.InteractiveTB.structured_traceback(
1700 stb = self.InteractiveTB.structured_traceback(
1701 (etype,value,tb), tb_offset=tb_offset
1701 (etype,value,tb), tb_offset=tb_offset
1702 )
1702 )
1703 return stb
1703 return stb
1704
1704
1705 self.CustomTB = types.MethodType(wrapped,self)
1705 self.CustomTB = types.MethodType(wrapped,self)
1706 self.custom_exceptions = exc_tuple
1706 self.custom_exceptions = exc_tuple
1707
1707
1708 def excepthook(self, etype, value, tb):
1708 def excepthook(self, etype, value, tb):
1709 """One more defense for GUI apps that call sys.excepthook.
1709 """One more defense for GUI apps that call sys.excepthook.
1710
1710
1711 GUI frameworks like wxPython trap exceptions and call
1711 GUI frameworks like wxPython trap exceptions and call
1712 sys.excepthook themselves. I guess this is a feature that
1712 sys.excepthook themselves. I guess this is a feature that
1713 enables them to keep running after exceptions that would
1713 enables them to keep running after exceptions that would
1714 otherwise kill their mainloop. This is a bother for IPython
1714 otherwise kill their mainloop. This is a bother for IPython
1715 which excepts to catch all of the program exceptions with a try:
1715 which excepts to catch all of the program exceptions with a try:
1716 except: statement.
1716 except: statement.
1717
1717
1718 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1718 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1719 any app directly invokes sys.excepthook, it will look to the user like
1719 any app directly invokes sys.excepthook, it will look to the user like
1720 IPython crashed. In order to work around this, we can disable the
1720 IPython crashed. In order to work around this, we can disable the
1721 CrashHandler and replace it with this excepthook instead, which prints a
1721 CrashHandler and replace it with this excepthook instead, which prints a
1722 regular traceback using our InteractiveTB. In this fashion, apps which
1722 regular traceback using our InteractiveTB. In this fashion, apps which
1723 call sys.excepthook will generate a regular-looking exception from
1723 call sys.excepthook will generate a regular-looking exception from
1724 IPython, and the CrashHandler will only be triggered by real IPython
1724 IPython, and the CrashHandler will only be triggered by real IPython
1725 crashes.
1725 crashes.
1726
1726
1727 This hook should be used sparingly, only in places which are not likely
1727 This hook should be used sparingly, only in places which are not likely
1728 to be true IPython errors.
1728 to be true IPython errors.
1729 """
1729 """
1730 self.showtraceback((etype, value, tb), tb_offset=0)
1730 self.showtraceback((etype, value, tb), tb_offset=0)
1731
1731
1732 def _get_exc_info(self, exc_tuple=None):
1732 def _get_exc_info(self, exc_tuple=None):
1733 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1733 """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
1734
1734
1735 Ensures sys.last_type,value,traceback hold the exc_info we found,
1735 Ensures sys.last_type,value,traceback hold the exc_info we found,
1736 from whichever source.
1736 from whichever source.
1737
1737
1738 raises ValueError if none of these contain any information
1738 raises ValueError if none of these contain any information
1739 """
1739 """
1740 if exc_tuple is None:
1740 if exc_tuple is None:
1741 etype, value, tb = sys.exc_info()
1741 etype, value, tb = sys.exc_info()
1742 else:
1742 else:
1743 etype, value, tb = exc_tuple
1743 etype, value, tb = exc_tuple
1744
1744
1745 if etype is None:
1745 if etype is None:
1746 if hasattr(sys, 'last_type'):
1746 if hasattr(sys, 'last_type'):
1747 etype, value, tb = sys.last_type, sys.last_value, \
1747 etype, value, tb = sys.last_type, sys.last_value, \
1748 sys.last_traceback
1748 sys.last_traceback
1749
1749
1750 if etype is None:
1750 if etype is None:
1751 raise ValueError("No exception to find")
1751 raise ValueError("No exception to find")
1752
1752
1753 # Now store the exception info in sys.last_type etc.
1753 # Now store the exception info in sys.last_type etc.
1754 # WARNING: these variables are somewhat deprecated and not
1754 # WARNING: these variables are somewhat deprecated and not
1755 # necessarily safe to use in a threaded environment, but tools
1755 # necessarily safe to use in a threaded environment, but tools
1756 # like pdb depend on their existence, so let's set them. If we
1756 # like pdb depend on their existence, so let's set them. If we
1757 # find problems in the field, we'll need to revisit their use.
1757 # find problems in the field, we'll need to revisit their use.
1758 sys.last_type = etype
1758 sys.last_type = etype
1759 sys.last_value = value
1759 sys.last_value = value
1760 sys.last_traceback = tb
1760 sys.last_traceback = tb
1761
1761
1762 return etype, value, tb
1762 return etype, value, tb
1763
1763
1764 def show_usage_error(self, exc):
1764 def show_usage_error(self, exc):
1765 """Show a short message for UsageErrors
1765 """Show a short message for UsageErrors
1766
1766
1767 These are special exceptions that shouldn't show a traceback.
1767 These are special exceptions that shouldn't show a traceback.
1768 """
1768 """
1769 print("UsageError: %s" % exc, file=sys.stderr)
1769 print("UsageError: %s" % exc, file=sys.stderr)
1770
1770
1771 def get_exception_only(self, exc_tuple=None):
1771 def get_exception_only(self, exc_tuple=None):
1772 """
1772 """
1773 Return as a string (ending with a newline) the exception that
1773 Return as a string (ending with a newline) the exception that
1774 just occurred, without any traceback.
1774 just occurred, without any traceback.
1775 """
1775 """
1776 etype, value, tb = self._get_exc_info(exc_tuple)
1776 etype, value, tb = self._get_exc_info(exc_tuple)
1777 msg = traceback.format_exception_only(etype, value)
1777 msg = traceback.format_exception_only(etype, value)
1778 return ''.join(msg)
1778 return ''.join(msg)
1779
1779
1780 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1780 def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None,
1781 exception_only=False, running_compiled_code=False):
1781 exception_only=False, running_compiled_code=False):
1782 """Display the exception that just occurred.
1782 """Display the exception that just occurred.
1783
1783
1784 If nothing is known about the exception, this is the method which
1784 If nothing is known about the exception, this is the method which
1785 should be used throughout the code for presenting user tracebacks,
1785 should be used throughout the code for presenting user tracebacks,
1786 rather than directly invoking the InteractiveTB object.
1786 rather than directly invoking the InteractiveTB object.
1787
1787
1788 A specific showsyntaxerror() also exists, but this method can take
1788 A specific showsyntaxerror() also exists, but this method can take
1789 care of calling it if needed, so unless you are explicitly catching a
1789 care of calling it if needed, so unless you are explicitly catching a
1790 SyntaxError exception, don't try to analyze the stack manually and
1790 SyntaxError exception, don't try to analyze the stack manually and
1791 simply call this method."""
1791 simply call this method."""
1792
1792
1793 try:
1793 try:
1794 try:
1794 try:
1795 etype, value, tb = self._get_exc_info(exc_tuple)
1795 etype, value, tb = self._get_exc_info(exc_tuple)
1796 except ValueError:
1796 except ValueError:
1797 print('No traceback available to show.', file=sys.stderr)
1797 print('No traceback available to show.', file=sys.stderr)
1798 return
1798 return
1799
1799
1800 if issubclass(etype, SyntaxError):
1800 if issubclass(etype, SyntaxError):
1801 # Though this won't be called by syntax errors in the input
1801 # Though this won't be called by syntax errors in the input
1802 # line, there may be SyntaxError cases with imported code.
1802 # line, there may be SyntaxError cases with imported code.
1803 self.showsyntaxerror(filename, running_compiled_code)
1803 self.showsyntaxerror(filename, running_compiled_code)
1804 elif etype is UsageError:
1804 elif etype is UsageError:
1805 self.show_usage_error(value)
1805 self.show_usage_error(value)
1806 else:
1806 else:
1807 if exception_only:
1807 if exception_only:
1808 stb = ['An exception has occurred, use %tb to see '
1808 stb = ['An exception has occurred, use %tb to see '
1809 'the full traceback.\n']
1809 'the full traceback.\n']
1810 stb.extend(self.InteractiveTB.get_exception_only(etype,
1810 stb.extend(self.InteractiveTB.get_exception_only(etype,
1811 value))
1811 value))
1812 else:
1812 else:
1813 try:
1813 try:
1814 # Exception classes can customise their traceback - we
1814 # Exception classes can customise their traceback - we
1815 # use this in IPython.parallel for exceptions occurring
1815 # use this in IPython.parallel for exceptions occurring
1816 # in the engines. This should return a list of strings.
1816 # in the engines. This should return a list of strings.
1817 stb = value._render_traceback_()
1817 stb = value._render_traceback_()
1818 except Exception:
1818 except Exception:
1819 stb = self.InteractiveTB.structured_traceback(etype,
1819 stb = self.InteractiveTB.structured_traceback(etype,
1820 value, tb, tb_offset=tb_offset)
1820 value, tb, tb_offset=tb_offset)
1821
1821
1822 self._showtraceback(etype, value, stb)
1822 self._showtraceback(etype, value, stb)
1823 if self.call_pdb:
1823 if self.call_pdb:
1824 # drop into debugger
1824 # drop into debugger
1825 self.debugger(force=True)
1825 self.debugger(force=True)
1826 return
1826 return
1827
1827
1828 # Actually show the traceback
1828 # Actually show the traceback
1829 self._showtraceback(etype, value, stb)
1829 self._showtraceback(etype, value, stb)
1830
1830
1831 except KeyboardInterrupt:
1831 except KeyboardInterrupt:
1832 print('\n' + self.get_exception_only(), file=sys.stderr)
1832 print('\n' + self.get_exception_only(), file=sys.stderr)
1833
1833
1834 def _showtraceback(self, etype, evalue, stb):
1834 def _showtraceback(self, etype, evalue, stb):
1835 """Actually show a traceback.
1835 """Actually show a traceback.
1836
1836
1837 Subclasses may override this method to put the traceback on a different
1837 Subclasses may override this method to put the traceback on a different
1838 place, like a side channel.
1838 place, like a side channel.
1839 """
1839 """
1840 print(self.InteractiveTB.stb2text(stb))
1840 print(self.InteractiveTB.stb2text(stb))
1841
1841
1842 def showsyntaxerror(self, filename=None, running_compiled_code=False):
1842 def showsyntaxerror(self, filename=None, running_compiled_code=False):
1843 """Display the syntax error that just occurred.
1843 """Display the syntax error that just occurred.
1844
1844
1845 This doesn't display a stack trace because there isn't one.
1845 This doesn't display a stack trace because there isn't one.
1846
1846
1847 If a filename is given, it is stuffed in the exception instead
1847 If a filename is given, it is stuffed in the exception instead
1848 of what was there before (because Python's parser always uses
1848 of what was there before (because Python's parser always uses
1849 "<string>" when reading from a string).
1849 "<string>" when reading from a string).
1850
1850
1851 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
1851 If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
1852 longer stack trace will be displayed.
1852 longer stack trace will be displayed.
1853 """
1853 """
1854 etype, value, last_traceback = self._get_exc_info()
1854 etype, value, last_traceback = self._get_exc_info()
1855
1855
1856 if filename and issubclass(etype, SyntaxError):
1856 if filename and issubclass(etype, SyntaxError):
1857 try:
1857 try:
1858 value.filename = filename
1858 value.filename = filename
1859 except:
1859 except:
1860 # Not the format we expect; leave it alone
1860 # Not the format we expect; leave it alone
1861 pass
1861 pass
1862
1862
1863 # If the error occured when executing compiled code, we should provide full stacktrace.
1863 # If the error occured when executing compiled code, we should provide full stacktrace.
1864 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
1864 elist = traceback.extract_tb(last_traceback) if running_compiled_code else []
1865 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
1865 stb = self.SyntaxTB.structured_traceback(etype, value, elist)
1866 self._showtraceback(etype, value, stb)
1866 self._showtraceback(etype, value, stb)
1867
1867
1868 # This is overridden in TerminalInteractiveShell to show a message about
1868 # This is overridden in TerminalInteractiveShell to show a message about
1869 # the %paste magic.
1869 # the %paste magic.
1870 def showindentationerror(self):
1870 def showindentationerror(self):
1871 """Called by run_cell when there's an IndentationError in code entered
1871 """Called by run_cell when there's an IndentationError in code entered
1872 at the prompt.
1872 at the prompt.
1873
1873
1874 This is overridden in TerminalInteractiveShell to show a message about
1874 This is overridden in TerminalInteractiveShell to show a message about
1875 the %paste magic."""
1875 the %paste magic."""
1876 self.showsyntaxerror()
1876 self.showsyntaxerror()
1877
1877
1878 #-------------------------------------------------------------------------
1878 #-------------------------------------------------------------------------
1879 # Things related to readline
1879 # Things related to readline
1880 #-------------------------------------------------------------------------
1880 #-------------------------------------------------------------------------
1881
1881
1882 def init_readline(self):
1882 def init_readline(self):
1883 """DEPRECATED
1883 """DEPRECATED
1884
1884
1885 Moved to terminal subclass, here only to simplify the init logic."""
1885 Moved to terminal subclass, here only to simplify the init logic."""
1886 # Set a number of methods that depend on readline to be no-op
1886 # Set a number of methods that depend on readline to be no-op
1887 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1887 warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated',
1888 DeprecationWarning, stacklevel=2)
1888 DeprecationWarning, stacklevel=2)
1889 self.set_custom_completer = no_op
1889 self.set_custom_completer = no_op
1890
1890
1891 @skip_doctest
1891 @skip_doctest
1892 def set_next_input(self, s, replace=False):
1892 def set_next_input(self, s, replace=False):
1893 """ Sets the 'default' input string for the next command line.
1893 """ Sets the 'default' input string for the next command line.
1894
1894
1895 Example::
1895 Example::
1896
1896
1897 In [1]: _ip.set_next_input("Hello Word")
1897 In [1]: _ip.set_next_input("Hello Word")
1898 In [2]: Hello Word_ # cursor is here
1898 In [2]: Hello Word_ # cursor is here
1899 """
1899 """
1900 self.rl_next_input = s
1900 self.rl_next_input = s
1901
1901
1902 def _indent_current_str(self):
1902 def _indent_current_str(self):
1903 """return the current level of indentation as a string"""
1903 """return the current level of indentation as a string"""
1904 return self.input_splitter.indent_spaces * ' '
1904 return self.input_splitter.indent_spaces * ' '
1905
1905
1906 #-------------------------------------------------------------------------
1906 #-------------------------------------------------------------------------
1907 # Things related to text completion
1907 # Things related to text completion
1908 #-------------------------------------------------------------------------
1908 #-------------------------------------------------------------------------
1909
1909
1910 def init_completer(self):
1910 def init_completer(self):
1911 """Initialize the completion machinery.
1911 """Initialize the completion machinery.
1912
1912
1913 This creates completion machinery that can be used by client code,
1913 This creates completion machinery that can be used by client code,
1914 either interactively in-process (typically triggered by the readline
1914 either interactively in-process (typically triggered by the readline
1915 library), programmatically (such as in test suites) or out-of-process
1915 library), programmatically (such as in test suites) or out-of-process
1916 (typically over the network by remote frontends).
1916 (typically over the network by remote frontends).
1917 """
1917 """
1918 from IPython.core.completer import IPCompleter
1918 from IPython.core.completer import IPCompleter
1919 from IPython.core.completerlib import (module_completer,
1919 from IPython.core.completerlib import (module_completer,
1920 magic_run_completer, cd_completer, reset_completer)
1920 magic_run_completer, cd_completer, reset_completer)
1921
1921
1922 self.Completer = IPCompleter(shell=self,
1922 self.Completer = IPCompleter(shell=self,
1923 namespace=self.user_ns,
1923 namespace=self.user_ns,
1924 global_namespace=self.user_global_ns,
1924 global_namespace=self.user_global_ns,
1925 parent=self,
1925 parent=self,
1926 )
1926 )
1927 self.configurables.append(self.Completer)
1927 self.configurables.append(self.Completer)
1928
1928
1929 # Add custom completers to the basic ones built into IPCompleter
1929 # Add custom completers to the basic ones built into IPCompleter
1930 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1930 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1931 self.strdispatchers['complete_command'] = sdisp
1931 self.strdispatchers['complete_command'] = sdisp
1932 self.Completer.custom_completers = sdisp
1932 self.Completer.custom_completers = sdisp
1933
1933
1934 self.set_hook('complete_command', module_completer, str_key = 'import')
1934 self.set_hook('complete_command', module_completer, str_key = 'import')
1935 self.set_hook('complete_command', module_completer, str_key = 'from')
1935 self.set_hook('complete_command', module_completer, str_key = 'from')
1936 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1936 self.set_hook('complete_command', module_completer, str_key = '%aimport')
1937 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1937 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1938 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1938 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1939 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1939 self.set_hook('complete_command', reset_completer, str_key = '%reset')
1940
1940
1941
1941
1942 def complete(self, text, line=None, cursor_pos=None):
1942 def complete(self, text, line=None, cursor_pos=None):
1943 """Return the completed text and a list of completions.
1943 """Return the completed text and a list of completions.
1944
1944
1945 Parameters
1945 Parameters
1946 ----------
1946 ----------
1947
1947
1948 text : string
1948 text : string
1949 A string of text to be completed on. It can be given as empty and
1949 A string of text to be completed on. It can be given as empty and
1950 instead a line/position pair are given. In this case, the
1950 instead a line/position pair are given. In this case, the
1951 completer itself will split the line like readline does.
1951 completer itself will split the line like readline does.
1952
1952
1953 line : string, optional
1953 line : string, optional
1954 The complete line that text is part of.
1954 The complete line that text is part of.
1955
1955
1956 cursor_pos : int, optional
1956 cursor_pos : int, optional
1957 The position of the cursor on the input line.
1957 The position of the cursor on the input line.
1958
1958
1959 Returns
1959 Returns
1960 -------
1960 -------
1961 text : string
1961 text : string
1962 The actual text that was completed.
1962 The actual text that was completed.
1963
1963
1964 matches : list
1964 matches : list
1965 A sorted list with all possible completions.
1965 A sorted list with all possible completions.
1966
1966
1967 The optional arguments allow the completion to take more context into
1967 The optional arguments allow the completion to take more context into
1968 account, and are part of the low-level completion API.
1968 account, and are part of the low-level completion API.
1969
1969
1970 This is a wrapper around the completion mechanism, similar to what
1970 This is a wrapper around the completion mechanism, similar to what
1971 readline does at the command line when the TAB key is hit. By
1971 readline does at the command line when the TAB key is hit. By
1972 exposing it as a method, it can be used by other non-readline
1972 exposing it as a method, it can be used by other non-readline
1973 environments (such as GUIs) for text completion.
1973 environments (such as GUIs) for text completion.
1974
1974
1975 Simple usage example:
1975 Simple usage example:
1976
1976
1977 In [1]: x = 'hello'
1977 In [1]: x = 'hello'
1978
1978
1979 In [2]: _ip.complete('x.l')
1979 In [2]: _ip.complete('x.l')
1980 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1980 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1981 """
1981 """
1982
1982
1983 # Inject names into __builtin__ so we can complete on the added names.
1983 # Inject names into __builtin__ so we can complete on the added names.
1984 with self.builtin_trap:
1984 with self.builtin_trap:
1985 return self.Completer.complete(text, line, cursor_pos)
1985 return self.Completer.complete(text, line, cursor_pos)
1986
1986
1987 def set_custom_completer(self, completer, pos=0):
1987 def set_custom_completer(self, completer, pos=0):
1988 """Adds a new custom completer function.
1988 """Adds a new custom completer function.
1989
1989
1990 The position argument (defaults to 0) is the index in the completers
1990 The position argument (defaults to 0) is the index in the completers
1991 list where you want the completer to be inserted."""
1991 list where you want the completer to be inserted."""
1992
1992
1993 newcomp = types.MethodType(completer,self.Completer)
1993 newcomp = types.MethodType(completer,self.Completer)
1994 self.Completer.matchers.insert(pos,newcomp)
1994 self.Completer.matchers.insert(pos,newcomp)
1995
1995
1996 def set_completer_frame(self, frame=None):
1996 def set_completer_frame(self, frame=None):
1997 """Set the frame of the completer."""
1997 """Set the frame of the completer."""
1998 if frame:
1998 if frame:
1999 self.Completer.namespace = frame.f_locals
1999 self.Completer.namespace = frame.f_locals
2000 self.Completer.global_namespace = frame.f_globals
2000 self.Completer.global_namespace = frame.f_globals
2001 else:
2001 else:
2002 self.Completer.namespace = self.user_ns
2002 self.Completer.namespace = self.user_ns
2003 self.Completer.global_namespace = self.user_global_ns
2003 self.Completer.global_namespace = self.user_global_ns
2004
2004
2005 #-------------------------------------------------------------------------
2005 #-------------------------------------------------------------------------
2006 # Things related to magics
2006 # Things related to magics
2007 #-------------------------------------------------------------------------
2007 #-------------------------------------------------------------------------
2008
2008
2009 def init_magics(self):
2009 def init_magics(self):
2010 from IPython.core import magics as m
2010 from IPython.core import magics as m
2011 self.magics_manager = magic.MagicsManager(shell=self,
2011 self.magics_manager = magic.MagicsManager(shell=self,
2012 parent=self,
2012 parent=self,
2013 user_magics=m.UserMagics(self))
2013 user_magics=m.UserMagics(self))
2014 self.configurables.append(self.magics_manager)
2014 self.configurables.append(self.magics_manager)
2015
2015
2016 # Expose as public API from the magics manager
2016 # Expose as public API from the magics manager
2017 self.register_magics = self.magics_manager.register
2017 self.register_magics = self.magics_manager.register
2018
2018
2019 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2019 self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics,
2020 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2020 m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics,
2021 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2021 m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics,
2022 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2022 m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics,
2023 )
2023 )
2024
2024
2025 # Register Magic Aliases
2025 # Register Magic Aliases
2026 mman = self.magics_manager
2026 mman = self.magics_manager
2027 # FIXME: magic aliases should be defined by the Magics classes
2027 # FIXME: magic aliases should be defined by the Magics classes
2028 # or in MagicsManager, not here
2028 # or in MagicsManager, not here
2029 mman.register_alias('ed', 'edit')
2029 mman.register_alias('ed', 'edit')
2030 mman.register_alias('hist', 'history')
2030 mman.register_alias('hist', 'history')
2031 mman.register_alias('rep', 'recall')
2031 mman.register_alias('rep', 'recall')
2032 mman.register_alias('SVG', 'svg', 'cell')
2032 mman.register_alias('SVG', 'svg', 'cell')
2033 mman.register_alias('HTML', 'html', 'cell')
2033 mman.register_alias('HTML', 'html', 'cell')
2034 mman.register_alias('file', 'writefile', 'cell')
2034 mman.register_alias('file', 'writefile', 'cell')
2035
2035
2036 # FIXME: Move the color initialization to the DisplayHook, which
2036 # FIXME: Move the color initialization to the DisplayHook, which
2037 # should be split into a prompt manager and displayhook. We probably
2037 # should be split into a prompt manager and displayhook. We probably
2038 # even need a centralize colors management object.
2038 # even need a centralize colors management object.
2039 self.magic('colors %s' % self.colors)
2039 self.run_line_magic('colors', self.colors)
2040
2040
2041 # Defined here so that it's included in the documentation
2041 # Defined here so that it's included in the documentation
2042 @functools.wraps(magic.MagicsManager.register_function)
2042 @functools.wraps(magic.MagicsManager.register_function)
2043 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2043 def register_magic_function(self, func, magic_kind='line', magic_name=None):
2044 self.magics_manager.register_function(func,
2044 self.magics_manager.register_function(func,
2045 magic_kind=magic_kind, magic_name=magic_name)
2045 magic_kind=magic_kind, magic_name=magic_name)
2046
2046
2047 def run_line_magic(self, magic_name, line):
2047 def run_line_magic(self, magic_name, line, _stack_depth=1):
2048 """Execute the given line magic.
2048 """Execute the given line magic.
2049
2049
2050 Parameters
2050 Parameters
2051 ----------
2051 ----------
2052 magic_name : str
2052 magic_name : str
2053 Name of the desired magic function, without '%' prefix.
2053 Name of the desired magic function, without '%' prefix.
2054
2054
2055 line : str
2055 line : str
2056 The rest of the input line as a single string.
2056 The rest of the input line as a single string.
2057
2058 _stack_depth : int
2059 If run_line_magic() is called from magic() then _stack_depth=2.
2060 This is added to ensure backward compatibility for use of 'get_ipython().magic()'
2057 """
2061 """
2058 fn = self.find_line_magic(magic_name)
2062 fn = self.find_line_magic(magic_name)
2059 if fn is None:
2063 if fn is None:
2060 cm = self.find_cell_magic(magic_name)
2064 cm = self.find_cell_magic(magic_name)
2061 etpl = "Line magic function `%%%s` not found%s."
2065 etpl = "Line magic function `%%%s` not found%s."
2062 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2066 extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, '
2063 'did you mean that instead?)' % magic_name )
2067 'did you mean that instead?)' % magic_name )
2064 error(etpl % (magic_name, extra))
2068 error(etpl % (magic_name, extra))
2065 else:
2069 else:
2066 # Note: this is the distance in the stack to the user's frame.
2070 # Note: this is the distance in the stack to the user's frame.
2067 # This will need to be updated if the internal calling logic gets
2071 # This will need to be updated if the internal calling logic gets
2068 # refactored, or else we'll be expanding the wrong variables.
2072 # refactored, or else we'll be expanding the wrong variables.
2069 stack_depth = 2
2073
2074 # Determine stack_depth depending on where run_line_magic() has been called
2075 stack_depth = _stack_depth
2070 magic_arg_s = self.var_expand(line, stack_depth)
2076 magic_arg_s = self.var_expand(line, stack_depth)
2071 # Put magic args in a list so we can call with f(*a) syntax
2077 # Put magic args in a list so we can call with f(*a) syntax
2072 args = [magic_arg_s]
2078 args = [magic_arg_s]
2073 kwargs = {}
2079 kwargs = {}
2074 # Grab local namespace if we need it:
2080 # Grab local namespace if we need it:
2075 if getattr(fn, "needs_local_scope", False):
2081 if getattr(fn, "needs_local_scope", False):
2076 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2082 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
2077 with self.builtin_trap:
2083 with self.builtin_trap:
2078 result = fn(*args,**kwargs)
2084 result = fn(*args,**kwargs)
2079 return result
2085 return result
2080
2086
2081 def run_cell_magic(self, magic_name, line, cell):
2087 def run_cell_magic(self, magic_name, line, cell):
2082 """Execute the given cell magic.
2088 """Execute the given cell magic.
2083
2089
2084 Parameters
2090 Parameters
2085 ----------
2091 ----------
2086 magic_name : str
2092 magic_name : str
2087 Name of the desired magic function, without '%' prefix.
2093 Name of the desired magic function, without '%' prefix.
2088
2094
2089 line : str
2095 line : str
2090 The rest of the first input line as a single string.
2096 The rest of the first input line as a single string.
2091
2097
2092 cell : str
2098 cell : str
2093 The body of the cell as a (possibly multiline) string.
2099 The body of the cell as a (possibly multiline) string.
2094 """
2100 """
2095 fn = self.find_cell_magic(magic_name)
2101 fn = self.find_cell_magic(magic_name)
2096 if fn is None:
2102 if fn is None:
2097 lm = self.find_line_magic(magic_name)
2103 lm = self.find_line_magic(magic_name)
2098 etpl = "Cell magic `%%{0}` not found{1}."
2104 etpl = "Cell magic `%%{0}` not found{1}."
2099 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2105 extra = '' if lm is None else (' (But line magic `%{0}` exists, '
2100 'did you mean that instead?)'.format(magic_name))
2106 'did you mean that instead?)'.format(magic_name))
2101 error(etpl.format(magic_name, extra))
2107 error(etpl.format(magic_name, extra))
2102 elif cell == '':
2108 elif cell == '':
2103 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2109 message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
2104 if self.find_line_magic(magic_name) is not None:
2110 if self.find_line_magic(magic_name) is not None:
2105 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2111 message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
2106 raise UsageError(message)
2112 raise UsageError(message)
2107 else:
2113 else:
2108 # Note: this is the distance in the stack to the user's frame.
2114 # Note: this is the distance in the stack to the user's frame.
2109 # This will need to be updated if the internal calling logic gets
2115 # This will need to be updated if the internal calling logic gets
2110 # refactored, or else we'll be expanding the wrong variables.
2116 # refactored, or else we'll be expanding the wrong variables.
2111 stack_depth = 2
2117 stack_depth = 2
2112 magic_arg_s = self.var_expand(line, stack_depth)
2118 magic_arg_s = self.var_expand(line, stack_depth)
2113 with self.builtin_trap:
2119 with self.builtin_trap:
2114 result = fn(magic_arg_s, cell)
2120 result = fn(magic_arg_s, cell)
2115 return result
2121 return result
2116
2122
2117 def find_line_magic(self, magic_name):
2123 def find_line_magic(self, magic_name):
2118 """Find and return a line magic by name.
2124 """Find and return a line magic by name.
2119
2125
2120 Returns None if the magic isn't found."""
2126 Returns None if the magic isn't found."""
2121 return self.magics_manager.magics['line'].get(magic_name)
2127 return self.magics_manager.magics['line'].get(magic_name)
2122
2128
2123 def find_cell_magic(self, magic_name):
2129 def find_cell_magic(self, magic_name):
2124 """Find and return a cell magic by name.
2130 """Find and return a cell magic by name.
2125
2131
2126 Returns None if the magic isn't found."""
2132 Returns None if the magic isn't found."""
2127 return self.magics_manager.magics['cell'].get(magic_name)
2133 return self.magics_manager.magics['cell'].get(magic_name)
2128
2134
2129 def find_magic(self, magic_name, magic_kind='line'):
2135 def find_magic(self, magic_name, magic_kind='line'):
2130 """Find and return a magic of the given type by name.
2136 """Find and return a magic of the given type by name.
2131
2137
2132 Returns None if the magic isn't found."""
2138 Returns None if the magic isn't found."""
2133 return self.magics_manager.magics[magic_kind].get(magic_name)
2139 return self.magics_manager.magics[magic_kind].get(magic_name)
2134
2140
2135 def magic(self, arg_s):
2141 def magic(self, arg_s):
2136 """DEPRECATED. Use run_line_magic() instead.
2142 """DEPRECATED. Use run_line_magic() instead.
2137
2143
2138 Call a magic function by name.
2144 Call a magic function by name.
2139
2145
2140 Input: a string containing the name of the magic function to call and
2146 Input: a string containing the name of the magic function to call and
2141 any additional arguments to be passed to the magic.
2147 any additional arguments to be passed to the magic.
2142
2148
2143 magic('name -opt foo bar') is equivalent to typing at the ipython
2149 magic('name -opt foo bar') is equivalent to typing at the ipython
2144 prompt:
2150 prompt:
2145
2151
2146 In[1]: %name -opt foo bar
2152 In[1]: %name -opt foo bar
2147
2153
2148 To call a magic without arguments, simply use magic('name').
2154 To call a magic without arguments, simply use magic('name').
2149
2155
2150 This provides a proper Python function to call IPython's magics in any
2156 This provides a proper Python function to call IPython's magics in any
2151 valid Python code you can type at the interpreter, including loops and
2157 valid Python code you can type at the interpreter, including loops and
2152 compound statements.
2158 compound statements.
2153 """
2159 """
2154 # TODO: should we issue a loud deprecation warning here?
2160 # TODO: should we issue a loud deprecation warning here?
2155 magic_name, _, magic_arg_s = arg_s.partition(' ')
2161 magic_name, _, magic_arg_s = arg_s.partition(' ')
2156 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2162 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
2157 return self.run_line_magic(magic_name, magic_arg_s)
2163 return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
2158
2164
2159 #-------------------------------------------------------------------------
2165 #-------------------------------------------------------------------------
2160 # Things related to macros
2166 # Things related to macros
2161 #-------------------------------------------------------------------------
2167 #-------------------------------------------------------------------------
2162
2168
2163 def define_macro(self, name, themacro):
2169 def define_macro(self, name, themacro):
2164 """Define a new macro
2170 """Define a new macro
2165
2171
2166 Parameters
2172 Parameters
2167 ----------
2173 ----------
2168 name : str
2174 name : str
2169 The name of the macro.
2175 The name of the macro.
2170 themacro : str or Macro
2176 themacro : str or Macro
2171 The action to do upon invoking the macro. If a string, a new
2177 The action to do upon invoking the macro. If a string, a new
2172 Macro object is created by passing the string to it.
2178 Macro object is created by passing the string to it.
2173 """
2179 """
2174
2180
2175 from IPython.core import macro
2181 from IPython.core import macro
2176
2182
2177 if isinstance(themacro, str):
2183 if isinstance(themacro, str):
2178 themacro = macro.Macro(themacro)
2184 themacro = macro.Macro(themacro)
2179 if not isinstance(themacro, macro.Macro):
2185 if not isinstance(themacro, macro.Macro):
2180 raise ValueError('A macro must be a string or a Macro instance.')
2186 raise ValueError('A macro must be a string or a Macro instance.')
2181 self.user_ns[name] = themacro
2187 self.user_ns[name] = themacro
2182
2188
2183 #-------------------------------------------------------------------------
2189 #-------------------------------------------------------------------------
2184 # Things related to the running of system commands
2190 # Things related to the running of system commands
2185 #-------------------------------------------------------------------------
2191 #-------------------------------------------------------------------------
2186
2192
2187 def system_piped(self, cmd):
2193 def system_piped(self, cmd):
2188 """Call the given cmd in a subprocess, piping stdout/err
2194 """Call the given cmd in a subprocess, piping stdout/err
2189
2195
2190 Parameters
2196 Parameters
2191 ----------
2197 ----------
2192 cmd : str
2198 cmd : str
2193 Command to execute (can not end in '&', as background processes are
2199 Command to execute (can not end in '&', as background processes are
2194 not supported. Should not be a command that expects input
2200 not supported. Should not be a command that expects input
2195 other than simple text.
2201 other than simple text.
2196 """
2202 """
2197 if cmd.rstrip().endswith('&'):
2203 if cmd.rstrip().endswith('&'):
2198 # this is *far* from a rigorous test
2204 # this is *far* from a rigorous test
2199 # We do not support backgrounding processes because we either use
2205 # We do not support backgrounding processes because we either use
2200 # pexpect or pipes to read from. Users can always just call
2206 # pexpect or pipes to read from. Users can always just call
2201 # os.system() or use ip.system=ip.system_raw
2207 # os.system() or use ip.system=ip.system_raw
2202 # if they really want a background process.
2208 # if they really want a background process.
2203 raise OSError("Background processes not supported.")
2209 raise OSError("Background processes not supported.")
2204
2210
2205 # we explicitly do NOT return the subprocess status code, because
2211 # we explicitly do NOT return the subprocess status code, because
2206 # a non-None value would trigger :func:`sys.displayhook` calls.
2212 # a non-None value would trigger :func:`sys.displayhook` calls.
2207 # Instead, we store the exit_code in user_ns.
2213 # Instead, we store the exit_code in user_ns.
2208 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2214 self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
2209
2215
2210 def system_raw(self, cmd):
2216 def system_raw(self, cmd):
2211 """Call the given cmd in a subprocess using os.system on Windows or
2217 """Call the given cmd in a subprocess using os.system on Windows or
2212 subprocess.call using the system shell on other platforms.
2218 subprocess.call using the system shell on other platforms.
2213
2219
2214 Parameters
2220 Parameters
2215 ----------
2221 ----------
2216 cmd : str
2222 cmd : str
2217 Command to execute.
2223 Command to execute.
2218 """
2224 """
2219 cmd = self.var_expand(cmd, depth=1)
2225 cmd = self.var_expand(cmd, depth=1)
2220 # protect os.system from UNC paths on Windows, which it can't handle:
2226 # protect os.system from UNC paths on Windows, which it can't handle:
2221 if sys.platform == 'win32':
2227 if sys.platform == 'win32':
2222 from IPython.utils._process_win32 import AvoidUNCPath
2228 from IPython.utils._process_win32 import AvoidUNCPath
2223 with AvoidUNCPath() as path:
2229 with AvoidUNCPath() as path:
2224 if path is not None:
2230 if path is not None:
2225 cmd = '"pushd %s &&"%s' % (path, cmd)
2231 cmd = '"pushd %s &&"%s' % (path, cmd)
2226 try:
2232 try:
2227 ec = os.system(cmd)
2233 ec = os.system(cmd)
2228 except KeyboardInterrupt:
2234 except KeyboardInterrupt:
2229 print('\n' + self.get_exception_only(), file=sys.stderr)
2235 print('\n' + self.get_exception_only(), file=sys.stderr)
2230 ec = -2
2236 ec = -2
2231 else:
2237 else:
2232 # For posix the result of the subprocess.call() below is an exit
2238 # For posix the result of the subprocess.call() below is an exit
2233 # code, which by convention is zero for success, positive for
2239 # code, which by convention is zero for success, positive for
2234 # program failure. Exit codes above 128 are reserved for signals,
2240 # program failure. Exit codes above 128 are reserved for signals,
2235 # and the formula for converting a signal to an exit code is usually
2241 # and the formula for converting a signal to an exit code is usually
2236 # signal_number+128. To more easily differentiate between exit
2242 # signal_number+128. To more easily differentiate between exit
2237 # codes and signals, ipython uses negative numbers. For instance
2243 # codes and signals, ipython uses negative numbers. For instance
2238 # since control-c is signal 2 but exit code 130, ipython's
2244 # since control-c is signal 2 but exit code 130, ipython's
2239 # _exit_code variable will read -2. Note that some shells like
2245 # _exit_code variable will read -2. Note that some shells like
2240 # csh and fish don't follow sh/bash conventions for exit codes.
2246 # csh and fish don't follow sh/bash conventions for exit codes.
2241 executable = os.environ.get('SHELL', None)
2247 executable = os.environ.get('SHELL', None)
2242 try:
2248 try:
2243 # Use env shell instead of default /bin/sh
2249 # Use env shell instead of default /bin/sh
2244 ec = subprocess.call(cmd, shell=True, executable=executable)
2250 ec = subprocess.call(cmd, shell=True, executable=executable)
2245 except KeyboardInterrupt:
2251 except KeyboardInterrupt:
2246 # intercept control-C; a long traceback is not useful here
2252 # intercept control-C; a long traceback is not useful here
2247 print('\n' + self.get_exception_only(), file=sys.stderr)
2253 print('\n' + self.get_exception_only(), file=sys.stderr)
2248 ec = 130
2254 ec = 130
2249 if ec > 128:
2255 if ec > 128:
2250 ec = -(ec - 128)
2256 ec = -(ec - 128)
2251
2257
2252 # We explicitly do NOT return the subprocess status code, because
2258 # We explicitly do NOT return the subprocess status code, because
2253 # a non-None value would trigger :func:`sys.displayhook` calls.
2259 # a non-None value would trigger :func:`sys.displayhook` calls.
2254 # Instead, we store the exit_code in user_ns. Note the semantics
2260 # Instead, we store the exit_code in user_ns. Note the semantics
2255 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2261 # of _exit_code: for control-c, _exit_code == -signal.SIGNIT,
2256 # but raising SystemExit(_exit_code) will give status 254!
2262 # but raising SystemExit(_exit_code) will give status 254!
2257 self.user_ns['_exit_code'] = ec
2263 self.user_ns['_exit_code'] = ec
2258
2264
2259 # use piped system by default, because it is better behaved
2265 # use piped system by default, because it is better behaved
2260 system = system_piped
2266 system = system_piped
2261
2267
2262 def getoutput(self, cmd, split=True, depth=0):
2268 def getoutput(self, cmd, split=True, depth=0):
2263 """Get output (possibly including stderr) from a subprocess.
2269 """Get output (possibly including stderr) from a subprocess.
2264
2270
2265 Parameters
2271 Parameters
2266 ----------
2272 ----------
2267 cmd : str
2273 cmd : str
2268 Command to execute (can not end in '&', as background processes are
2274 Command to execute (can not end in '&', as background processes are
2269 not supported.
2275 not supported.
2270 split : bool, optional
2276 split : bool, optional
2271 If True, split the output into an IPython SList. Otherwise, an
2277 If True, split the output into an IPython SList. Otherwise, an
2272 IPython LSString is returned. These are objects similar to normal
2278 IPython LSString is returned. These are objects similar to normal
2273 lists and strings, with a few convenience attributes for easier
2279 lists and strings, with a few convenience attributes for easier
2274 manipulation of line-based output. You can use '?' on them for
2280 manipulation of line-based output. You can use '?' on them for
2275 details.
2281 details.
2276 depth : int, optional
2282 depth : int, optional
2277 How many frames above the caller are the local variables which should
2283 How many frames above the caller are the local variables which should
2278 be expanded in the command string? The default (0) assumes that the
2284 be expanded in the command string? The default (0) assumes that the
2279 expansion variables are in the stack frame calling this function.
2285 expansion variables are in the stack frame calling this function.
2280 """
2286 """
2281 if cmd.rstrip().endswith('&'):
2287 if cmd.rstrip().endswith('&'):
2282 # this is *far* from a rigorous test
2288 # this is *far* from a rigorous test
2283 raise OSError("Background processes not supported.")
2289 raise OSError("Background processes not supported.")
2284 out = getoutput(self.var_expand(cmd, depth=depth+1))
2290 out = getoutput(self.var_expand(cmd, depth=depth+1))
2285 if split:
2291 if split:
2286 out = SList(out.splitlines())
2292 out = SList(out.splitlines())
2287 else:
2293 else:
2288 out = LSString(out)
2294 out = LSString(out)
2289 return out
2295 return out
2290
2296
2291 #-------------------------------------------------------------------------
2297 #-------------------------------------------------------------------------
2292 # Things related to aliases
2298 # Things related to aliases
2293 #-------------------------------------------------------------------------
2299 #-------------------------------------------------------------------------
2294
2300
2295 def init_alias(self):
2301 def init_alias(self):
2296 self.alias_manager = AliasManager(shell=self, parent=self)
2302 self.alias_manager = AliasManager(shell=self, parent=self)
2297 self.configurables.append(self.alias_manager)
2303 self.configurables.append(self.alias_manager)
2298
2304
2299 #-------------------------------------------------------------------------
2305 #-------------------------------------------------------------------------
2300 # Things related to extensions
2306 # Things related to extensions
2301 #-------------------------------------------------------------------------
2307 #-------------------------------------------------------------------------
2302
2308
2303 def init_extension_manager(self):
2309 def init_extension_manager(self):
2304 self.extension_manager = ExtensionManager(shell=self, parent=self)
2310 self.extension_manager = ExtensionManager(shell=self, parent=self)
2305 self.configurables.append(self.extension_manager)
2311 self.configurables.append(self.extension_manager)
2306
2312
2307 #-------------------------------------------------------------------------
2313 #-------------------------------------------------------------------------
2308 # Things related to payloads
2314 # Things related to payloads
2309 #-------------------------------------------------------------------------
2315 #-------------------------------------------------------------------------
2310
2316
2311 def init_payload(self):
2317 def init_payload(self):
2312 self.payload_manager = PayloadManager(parent=self)
2318 self.payload_manager = PayloadManager(parent=self)
2313 self.configurables.append(self.payload_manager)
2319 self.configurables.append(self.payload_manager)
2314
2320
2315 #-------------------------------------------------------------------------
2321 #-------------------------------------------------------------------------
2316 # Things related to the prefilter
2322 # Things related to the prefilter
2317 #-------------------------------------------------------------------------
2323 #-------------------------------------------------------------------------
2318
2324
2319 def init_prefilter(self):
2325 def init_prefilter(self):
2320 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2326 self.prefilter_manager = PrefilterManager(shell=self, parent=self)
2321 self.configurables.append(self.prefilter_manager)
2327 self.configurables.append(self.prefilter_manager)
2322 # Ultimately this will be refactored in the new interpreter code, but
2328 # Ultimately this will be refactored in the new interpreter code, but
2323 # for now, we should expose the main prefilter method (there's legacy
2329 # for now, we should expose the main prefilter method (there's legacy
2324 # code out there that may rely on this).
2330 # code out there that may rely on this).
2325 self.prefilter = self.prefilter_manager.prefilter_lines
2331 self.prefilter = self.prefilter_manager.prefilter_lines
2326
2332
2327 def auto_rewrite_input(self, cmd):
2333 def auto_rewrite_input(self, cmd):
2328 """Print to the screen the rewritten form of the user's command.
2334 """Print to the screen the rewritten form of the user's command.
2329
2335
2330 This shows visual feedback by rewriting input lines that cause
2336 This shows visual feedback by rewriting input lines that cause
2331 automatic calling to kick in, like::
2337 automatic calling to kick in, like::
2332
2338
2333 /f x
2339 /f x
2334
2340
2335 into::
2341 into::
2336
2342
2337 ------> f(x)
2343 ------> f(x)
2338
2344
2339 after the user's input prompt. This helps the user understand that the
2345 after the user's input prompt. This helps the user understand that the
2340 input line was transformed automatically by IPython.
2346 input line was transformed automatically by IPython.
2341 """
2347 """
2342 if not self.show_rewritten_input:
2348 if not self.show_rewritten_input:
2343 return
2349 return
2344
2350
2345 # This is overridden in TerminalInteractiveShell to use fancy prompts
2351 # This is overridden in TerminalInteractiveShell to use fancy prompts
2346 print("------> " + cmd)
2352 print("------> " + cmd)
2347
2353
2348 #-------------------------------------------------------------------------
2354 #-------------------------------------------------------------------------
2349 # Things related to extracting values/expressions from kernel and user_ns
2355 # Things related to extracting values/expressions from kernel and user_ns
2350 #-------------------------------------------------------------------------
2356 #-------------------------------------------------------------------------
2351
2357
2352 def _user_obj_error(self):
2358 def _user_obj_error(self):
2353 """return simple exception dict
2359 """return simple exception dict
2354
2360
2355 for use in user_expressions
2361 for use in user_expressions
2356 """
2362 """
2357
2363
2358 etype, evalue, tb = self._get_exc_info()
2364 etype, evalue, tb = self._get_exc_info()
2359 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2365 stb = self.InteractiveTB.get_exception_only(etype, evalue)
2360
2366
2361 exc_info = {
2367 exc_info = {
2362 u'status' : 'error',
2368 u'status' : 'error',
2363 u'traceback' : stb,
2369 u'traceback' : stb,
2364 u'ename' : etype.__name__,
2370 u'ename' : etype.__name__,
2365 u'evalue' : py3compat.safe_unicode(evalue),
2371 u'evalue' : py3compat.safe_unicode(evalue),
2366 }
2372 }
2367
2373
2368 return exc_info
2374 return exc_info
2369
2375
2370 def _format_user_obj(self, obj):
2376 def _format_user_obj(self, obj):
2371 """format a user object to display dict
2377 """format a user object to display dict
2372
2378
2373 for use in user_expressions
2379 for use in user_expressions
2374 """
2380 """
2375
2381
2376 data, md = self.display_formatter.format(obj)
2382 data, md = self.display_formatter.format(obj)
2377 value = {
2383 value = {
2378 'status' : 'ok',
2384 'status' : 'ok',
2379 'data' : data,
2385 'data' : data,
2380 'metadata' : md,
2386 'metadata' : md,
2381 }
2387 }
2382 return value
2388 return value
2383
2389
2384 def user_expressions(self, expressions):
2390 def user_expressions(self, expressions):
2385 """Evaluate a dict of expressions in the user's namespace.
2391 """Evaluate a dict of expressions in the user's namespace.
2386
2392
2387 Parameters
2393 Parameters
2388 ----------
2394 ----------
2389 expressions : dict
2395 expressions : dict
2390 A dict with string keys and string values. The expression values
2396 A dict with string keys and string values. The expression values
2391 should be valid Python expressions, each of which will be evaluated
2397 should be valid Python expressions, each of which will be evaluated
2392 in the user namespace.
2398 in the user namespace.
2393
2399
2394 Returns
2400 Returns
2395 -------
2401 -------
2396 A dict, keyed like the input expressions dict, with the rich mime-typed
2402 A dict, keyed like the input expressions dict, with the rich mime-typed
2397 display_data of each value.
2403 display_data of each value.
2398 """
2404 """
2399 out = {}
2405 out = {}
2400 user_ns = self.user_ns
2406 user_ns = self.user_ns
2401 global_ns = self.user_global_ns
2407 global_ns = self.user_global_ns
2402
2408
2403 for key, expr in expressions.items():
2409 for key, expr in expressions.items():
2404 try:
2410 try:
2405 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2411 value = self._format_user_obj(eval(expr, global_ns, user_ns))
2406 except:
2412 except:
2407 value = self._user_obj_error()
2413 value = self._user_obj_error()
2408 out[key] = value
2414 out[key] = value
2409 return out
2415 return out
2410
2416
2411 #-------------------------------------------------------------------------
2417 #-------------------------------------------------------------------------
2412 # Things related to the running of code
2418 # Things related to the running of code
2413 #-------------------------------------------------------------------------
2419 #-------------------------------------------------------------------------
2414
2420
2415 def ex(self, cmd):
2421 def ex(self, cmd):
2416 """Execute a normal python statement in user namespace."""
2422 """Execute a normal python statement in user namespace."""
2417 with self.builtin_trap:
2423 with self.builtin_trap:
2418 exec(cmd, self.user_global_ns, self.user_ns)
2424 exec(cmd, self.user_global_ns, self.user_ns)
2419
2425
2420 def ev(self, expr):
2426 def ev(self, expr):
2421 """Evaluate python expression expr in user namespace.
2427 """Evaluate python expression expr in user namespace.
2422
2428
2423 Returns the result of evaluation
2429 Returns the result of evaluation
2424 """
2430 """
2425 with self.builtin_trap:
2431 with self.builtin_trap:
2426 return eval(expr, self.user_global_ns, self.user_ns)
2432 return eval(expr, self.user_global_ns, self.user_ns)
2427
2433
2428 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2434 def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
2429 """A safe version of the builtin execfile().
2435 """A safe version of the builtin execfile().
2430
2436
2431 This version will never throw an exception, but instead print
2437 This version will never throw an exception, but instead print
2432 helpful error messages to the screen. This only works on pure
2438 helpful error messages to the screen. This only works on pure
2433 Python files with the .py extension.
2439 Python files with the .py extension.
2434
2440
2435 Parameters
2441 Parameters
2436 ----------
2442 ----------
2437 fname : string
2443 fname : string
2438 The name of the file to be executed.
2444 The name of the file to be executed.
2439 where : tuple
2445 where : tuple
2440 One or two namespaces, passed to execfile() as (globals,locals).
2446 One or two namespaces, passed to execfile() as (globals,locals).
2441 If only one is given, it is passed as both.
2447 If only one is given, it is passed as both.
2442 exit_ignore : bool (False)
2448 exit_ignore : bool (False)
2443 If True, then silence SystemExit for non-zero status (it is always
2449 If True, then silence SystemExit for non-zero status (it is always
2444 silenced for zero status, as it is so common).
2450 silenced for zero status, as it is so common).
2445 raise_exceptions : bool (False)
2451 raise_exceptions : bool (False)
2446 If True raise exceptions everywhere. Meant for testing.
2452 If True raise exceptions everywhere. Meant for testing.
2447 shell_futures : bool (False)
2453 shell_futures : bool (False)
2448 If True, the code will share future statements with the interactive
2454 If True, the code will share future statements with the interactive
2449 shell. It will both be affected by previous __future__ imports, and
2455 shell. It will both be affected by previous __future__ imports, and
2450 any __future__ imports in the code will affect the shell. If False,
2456 any __future__ imports in the code will affect the shell. If False,
2451 __future__ imports are not shared in either direction.
2457 __future__ imports are not shared in either direction.
2452
2458
2453 """
2459 """
2454 fname = os.path.abspath(os.path.expanduser(fname))
2460 fname = os.path.abspath(os.path.expanduser(fname))
2455
2461
2456 # Make sure we can open the file
2462 # Make sure we can open the file
2457 try:
2463 try:
2458 with open(fname):
2464 with open(fname):
2459 pass
2465 pass
2460 except:
2466 except:
2461 warn('Could not open file <%s> for safe execution.' % fname)
2467 warn('Could not open file <%s> for safe execution.' % fname)
2462 return
2468 return
2463
2469
2464 # Find things also in current directory. This is needed to mimic the
2470 # Find things also in current directory. This is needed to mimic the
2465 # behavior of running a script from the system command line, where
2471 # behavior of running a script from the system command line, where
2466 # Python inserts the script's directory into sys.path
2472 # Python inserts the script's directory into sys.path
2467 dname = os.path.dirname(fname)
2473 dname = os.path.dirname(fname)
2468
2474
2469 with prepended_to_syspath(dname), self.builtin_trap:
2475 with prepended_to_syspath(dname), self.builtin_trap:
2470 try:
2476 try:
2471 glob, loc = (where + (None, ))[:2]
2477 glob, loc = (where + (None, ))[:2]
2472 py3compat.execfile(
2478 py3compat.execfile(
2473 fname, glob, loc,
2479 fname, glob, loc,
2474 self.compile if shell_futures else None)
2480 self.compile if shell_futures else None)
2475 except SystemExit as status:
2481 except SystemExit as status:
2476 # If the call was made with 0 or None exit status (sys.exit(0)
2482 # If the call was made with 0 or None exit status (sys.exit(0)
2477 # or sys.exit() ), don't bother showing a traceback, as both of
2483 # or sys.exit() ), don't bother showing a traceback, as both of
2478 # these are considered normal by the OS:
2484 # these are considered normal by the OS:
2479 # > python -c'import sys;sys.exit(0)'; echo $?
2485 # > python -c'import sys;sys.exit(0)'; echo $?
2480 # 0
2486 # 0
2481 # > python -c'import sys;sys.exit()'; echo $?
2487 # > python -c'import sys;sys.exit()'; echo $?
2482 # 0
2488 # 0
2483 # For other exit status, we show the exception unless
2489 # For other exit status, we show the exception unless
2484 # explicitly silenced, but only in short form.
2490 # explicitly silenced, but only in short form.
2485 if status.code:
2491 if status.code:
2486 if raise_exceptions:
2492 if raise_exceptions:
2487 raise
2493 raise
2488 if not exit_ignore:
2494 if not exit_ignore:
2489 self.showtraceback(exception_only=True)
2495 self.showtraceback(exception_only=True)
2490 except:
2496 except:
2491 if raise_exceptions:
2497 if raise_exceptions:
2492 raise
2498 raise
2493 # tb offset is 2 because we wrap execfile
2499 # tb offset is 2 because we wrap execfile
2494 self.showtraceback(tb_offset=2)
2500 self.showtraceback(tb_offset=2)
2495
2501
2496 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2502 def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
2497 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2503 """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
2498
2504
2499 Parameters
2505 Parameters
2500 ----------
2506 ----------
2501 fname : str
2507 fname : str
2502 The name of the file to execute. The filename must have a
2508 The name of the file to execute. The filename must have a
2503 .ipy or .ipynb extension.
2509 .ipy or .ipynb extension.
2504 shell_futures : bool (False)
2510 shell_futures : bool (False)
2505 If True, the code will share future statements with the interactive
2511 If True, the code will share future statements with the interactive
2506 shell. It will both be affected by previous __future__ imports, and
2512 shell. It will both be affected by previous __future__ imports, and
2507 any __future__ imports in the code will affect the shell. If False,
2513 any __future__ imports in the code will affect the shell. If False,
2508 __future__ imports are not shared in either direction.
2514 __future__ imports are not shared in either direction.
2509 raise_exceptions : bool (False)
2515 raise_exceptions : bool (False)
2510 If True raise exceptions everywhere. Meant for testing.
2516 If True raise exceptions everywhere. Meant for testing.
2511 """
2517 """
2512 fname = os.path.abspath(os.path.expanduser(fname))
2518 fname = os.path.abspath(os.path.expanduser(fname))
2513
2519
2514 # Make sure we can open the file
2520 # Make sure we can open the file
2515 try:
2521 try:
2516 with open(fname):
2522 with open(fname):
2517 pass
2523 pass
2518 except:
2524 except:
2519 warn('Could not open file <%s> for safe execution.' % fname)
2525 warn('Could not open file <%s> for safe execution.' % fname)
2520 return
2526 return
2521
2527
2522 # Find things also in current directory. This is needed to mimic the
2528 # Find things also in current directory. This is needed to mimic the
2523 # behavior of running a script from the system command line, where
2529 # behavior of running a script from the system command line, where
2524 # Python inserts the script's directory into sys.path
2530 # Python inserts the script's directory into sys.path
2525 dname = os.path.dirname(fname)
2531 dname = os.path.dirname(fname)
2526
2532
2527 def get_cells():
2533 def get_cells():
2528 """generator for sequence of code blocks to run"""
2534 """generator for sequence of code blocks to run"""
2529 if fname.endswith('.ipynb'):
2535 if fname.endswith('.ipynb'):
2530 from nbformat import read
2536 from nbformat import read
2531 nb = read(fname, as_version=4)
2537 nb = read(fname, as_version=4)
2532 if not nb.cells:
2538 if not nb.cells:
2533 return
2539 return
2534 for cell in nb.cells:
2540 for cell in nb.cells:
2535 if cell.cell_type == 'code':
2541 if cell.cell_type == 'code':
2536 yield cell.source
2542 yield cell.source
2537 else:
2543 else:
2538 with open(fname) as f:
2544 with open(fname) as f:
2539 yield f.read()
2545 yield f.read()
2540
2546
2541 with prepended_to_syspath(dname):
2547 with prepended_to_syspath(dname):
2542 try:
2548 try:
2543 for cell in get_cells():
2549 for cell in get_cells():
2544 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2550 result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
2545 if raise_exceptions:
2551 if raise_exceptions:
2546 result.raise_error()
2552 result.raise_error()
2547 elif not result.success:
2553 elif not result.success:
2548 break
2554 break
2549 except:
2555 except:
2550 if raise_exceptions:
2556 if raise_exceptions:
2551 raise
2557 raise
2552 self.showtraceback()
2558 self.showtraceback()
2553 warn('Unknown failure executing file: <%s>' % fname)
2559 warn('Unknown failure executing file: <%s>' % fname)
2554
2560
2555 def safe_run_module(self, mod_name, where):
2561 def safe_run_module(self, mod_name, where):
2556 """A safe version of runpy.run_module().
2562 """A safe version of runpy.run_module().
2557
2563
2558 This version will never throw an exception, but instead print
2564 This version will never throw an exception, but instead print
2559 helpful error messages to the screen.
2565 helpful error messages to the screen.
2560
2566
2561 `SystemExit` exceptions with status code 0 or None are ignored.
2567 `SystemExit` exceptions with status code 0 or None are ignored.
2562
2568
2563 Parameters
2569 Parameters
2564 ----------
2570 ----------
2565 mod_name : string
2571 mod_name : string
2566 The name of the module to be executed.
2572 The name of the module to be executed.
2567 where : dict
2573 where : dict
2568 The globals namespace.
2574 The globals namespace.
2569 """
2575 """
2570 try:
2576 try:
2571 try:
2577 try:
2572 where.update(
2578 where.update(
2573 runpy.run_module(str(mod_name), run_name="__main__",
2579 runpy.run_module(str(mod_name), run_name="__main__",
2574 alter_sys=True)
2580 alter_sys=True)
2575 )
2581 )
2576 except SystemExit as status:
2582 except SystemExit as status:
2577 if status.code:
2583 if status.code:
2578 raise
2584 raise
2579 except:
2585 except:
2580 self.showtraceback()
2586 self.showtraceback()
2581 warn('Unknown failure executing module: <%s>' % mod_name)
2587 warn('Unknown failure executing module: <%s>' % mod_name)
2582
2588
2583 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2589 def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
2584 """Run a complete IPython cell.
2590 """Run a complete IPython cell.
2585
2591
2586 Parameters
2592 Parameters
2587 ----------
2593 ----------
2588 raw_cell : str
2594 raw_cell : str
2589 The code (including IPython code such as %magic functions) to run.
2595 The code (including IPython code such as %magic functions) to run.
2590 store_history : bool
2596 store_history : bool
2591 If True, the raw and translated cell will be stored in IPython's
2597 If True, the raw and translated cell will be stored in IPython's
2592 history. For user code calling back into IPython's machinery, this
2598 history. For user code calling back into IPython's machinery, this
2593 should be set to False.
2599 should be set to False.
2594 silent : bool
2600 silent : bool
2595 If True, avoid side-effects, such as implicit displayhooks and
2601 If True, avoid side-effects, such as implicit displayhooks and
2596 and logging. silent=True forces store_history=False.
2602 and logging. silent=True forces store_history=False.
2597 shell_futures : bool
2603 shell_futures : bool
2598 If True, the code will share future statements with the interactive
2604 If True, the code will share future statements with the interactive
2599 shell. It will both be affected by previous __future__ imports, and
2605 shell. It will both be affected by previous __future__ imports, and
2600 any __future__ imports in the code will affect the shell. If False,
2606 any __future__ imports in the code will affect the shell. If False,
2601 __future__ imports are not shared in either direction.
2607 __future__ imports are not shared in either direction.
2602
2608
2603 Returns
2609 Returns
2604 -------
2610 -------
2605 result : :class:`ExecutionResult`
2611 result : :class:`ExecutionResult`
2606 """
2612 """
2607 result = ExecutionResult()
2613 result = ExecutionResult()
2608
2614
2609 if (not raw_cell) or raw_cell.isspace():
2615 if (not raw_cell) or raw_cell.isspace():
2610 self.last_execution_succeeded = True
2616 self.last_execution_succeeded = True
2611 return result
2617 return result
2612
2618
2613 if silent:
2619 if silent:
2614 store_history = False
2620 store_history = False
2615
2621
2616 if store_history:
2622 if store_history:
2617 result.execution_count = self.execution_count
2623 result.execution_count = self.execution_count
2618
2624
2619 def error_before_exec(value):
2625 def error_before_exec(value):
2620 result.error_before_exec = value
2626 result.error_before_exec = value
2621 self.last_execution_succeeded = False
2627 self.last_execution_succeeded = False
2622 return result
2628 return result
2623
2629
2624 self.events.trigger('pre_execute')
2630 self.events.trigger('pre_execute')
2625 if not silent:
2631 if not silent:
2626 self.events.trigger('pre_run_cell')
2632 self.events.trigger('pre_run_cell')
2627
2633
2628 # If any of our input transformation (input_transformer_manager or
2634 # If any of our input transformation (input_transformer_manager or
2629 # prefilter_manager) raises an exception, we store it in this variable
2635 # prefilter_manager) raises an exception, we store it in this variable
2630 # so that we can display the error after logging the input and storing
2636 # so that we can display the error after logging the input and storing
2631 # it in the history.
2637 # it in the history.
2632 preprocessing_exc_tuple = None
2638 preprocessing_exc_tuple = None
2633 try:
2639 try:
2634 # Static input transformations
2640 # Static input transformations
2635 cell = self.input_transformer_manager.transform_cell(raw_cell)
2641 cell = self.input_transformer_manager.transform_cell(raw_cell)
2636 except SyntaxError:
2642 except SyntaxError:
2637 preprocessing_exc_tuple = sys.exc_info()
2643 preprocessing_exc_tuple = sys.exc_info()
2638 cell = raw_cell # cell has to exist so it can be stored/logged
2644 cell = raw_cell # cell has to exist so it can be stored/logged
2639 else:
2645 else:
2640 if len(cell.splitlines()) == 1:
2646 if len(cell.splitlines()) == 1:
2641 # Dynamic transformations - only applied for single line commands
2647 # Dynamic transformations - only applied for single line commands
2642 with self.builtin_trap:
2648 with self.builtin_trap:
2643 try:
2649 try:
2644 # use prefilter_lines to handle trailing newlines
2650 # use prefilter_lines to handle trailing newlines
2645 # restore trailing newline for ast.parse
2651 # restore trailing newline for ast.parse
2646 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2652 cell = self.prefilter_manager.prefilter_lines(cell) + '\n'
2647 except Exception:
2653 except Exception:
2648 # don't allow prefilter errors to crash IPython
2654 # don't allow prefilter errors to crash IPython
2649 preprocessing_exc_tuple = sys.exc_info()
2655 preprocessing_exc_tuple = sys.exc_info()
2650
2656
2651 # Store raw and processed history
2657 # Store raw and processed history
2652 if store_history:
2658 if store_history:
2653 self.history_manager.store_inputs(self.execution_count,
2659 self.history_manager.store_inputs(self.execution_count,
2654 cell, raw_cell)
2660 cell, raw_cell)
2655 if not silent:
2661 if not silent:
2656 self.logger.log(cell, raw_cell)
2662 self.logger.log(cell, raw_cell)
2657
2663
2658 # Display the exception if input processing failed.
2664 # Display the exception if input processing failed.
2659 if preprocessing_exc_tuple is not None:
2665 if preprocessing_exc_tuple is not None:
2660 self.showtraceback(preprocessing_exc_tuple)
2666 self.showtraceback(preprocessing_exc_tuple)
2661 if store_history:
2667 if store_history:
2662 self.execution_count += 1
2668 self.execution_count += 1
2663 return error_before_exec(preprocessing_exc_tuple[2])
2669 return error_before_exec(preprocessing_exc_tuple[2])
2664
2670
2665 # Our own compiler remembers the __future__ environment. If we want to
2671 # Our own compiler remembers the __future__ environment. If we want to
2666 # run code with a separate __future__ environment, use the default
2672 # run code with a separate __future__ environment, use the default
2667 # compiler
2673 # compiler
2668 compiler = self.compile if shell_futures else CachingCompiler()
2674 compiler = self.compile if shell_futures else CachingCompiler()
2669
2675
2670 with self.builtin_trap:
2676 with self.builtin_trap:
2671 cell_name = self.compile.cache(cell, self.execution_count)
2677 cell_name = self.compile.cache(cell, self.execution_count)
2672
2678
2673 with self.display_trap:
2679 with self.display_trap:
2674 # Compile to bytecode
2680 # Compile to bytecode
2675 try:
2681 try:
2676 code_ast = compiler.ast_parse(cell, filename=cell_name)
2682 code_ast = compiler.ast_parse(cell, filename=cell_name)
2677 except self.custom_exceptions as e:
2683 except self.custom_exceptions as e:
2678 etype, value, tb = sys.exc_info()
2684 etype, value, tb = sys.exc_info()
2679 self.CustomTB(etype, value, tb)
2685 self.CustomTB(etype, value, tb)
2680 return error_before_exec(e)
2686 return error_before_exec(e)
2681 except IndentationError as e:
2687 except IndentationError as e:
2682 self.showindentationerror()
2688 self.showindentationerror()
2683 if store_history:
2689 if store_history:
2684 self.execution_count += 1
2690 self.execution_count += 1
2685 return error_before_exec(e)
2691 return error_before_exec(e)
2686 except (OverflowError, SyntaxError, ValueError, TypeError,
2692 except (OverflowError, SyntaxError, ValueError, TypeError,
2687 MemoryError) as e:
2693 MemoryError) as e:
2688 self.showsyntaxerror()
2694 self.showsyntaxerror()
2689 if store_history:
2695 if store_history:
2690 self.execution_count += 1
2696 self.execution_count += 1
2691 return error_before_exec(e)
2697 return error_before_exec(e)
2692
2698
2693 # Apply AST transformations
2699 # Apply AST transformations
2694 try:
2700 try:
2695 code_ast = self.transform_ast(code_ast)
2701 code_ast = self.transform_ast(code_ast)
2696 except InputRejected as e:
2702 except InputRejected as e:
2697 self.showtraceback()
2703 self.showtraceback()
2698 if store_history:
2704 if store_history:
2699 self.execution_count += 1
2705 self.execution_count += 1
2700 return error_before_exec(e)
2706 return error_before_exec(e)
2701
2707
2702 # Give the displayhook a reference to our ExecutionResult so it
2708 # Give the displayhook a reference to our ExecutionResult so it
2703 # can fill in the output value.
2709 # can fill in the output value.
2704 self.displayhook.exec_result = result
2710 self.displayhook.exec_result = result
2705
2711
2706 # Execute the user code
2712 # Execute the user code
2707 interactivity = "none" if silent else self.ast_node_interactivity
2713 interactivity = "none" if silent else self.ast_node_interactivity
2708 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2714 has_raised = self.run_ast_nodes(code_ast.body, cell_name,
2709 interactivity=interactivity, compiler=compiler, result=result)
2715 interactivity=interactivity, compiler=compiler, result=result)
2710
2716
2711 self.last_execution_succeeded = not has_raised
2717 self.last_execution_succeeded = not has_raised
2712
2718
2713 # Reset this so later displayed values do not modify the
2719 # Reset this so later displayed values do not modify the
2714 # ExecutionResult
2720 # ExecutionResult
2715 self.displayhook.exec_result = None
2721 self.displayhook.exec_result = None
2716
2722
2717 self.events.trigger('post_execute')
2723 self.events.trigger('post_execute')
2718 if not silent:
2724 if not silent:
2719 self.events.trigger('post_run_cell')
2725 self.events.trigger('post_run_cell')
2720
2726
2721 if store_history:
2727 if store_history:
2722 # Write output to the database. Does nothing unless
2728 # Write output to the database. Does nothing unless
2723 # history output logging is enabled.
2729 # history output logging is enabled.
2724 self.history_manager.store_output(self.execution_count)
2730 self.history_manager.store_output(self.execution_count)
2725 # Each cell is a *single* input, regardless of how many lines it has
2731 # Each cell is a *single* input, regardless of how many lines it has
2726 self.execution_count += 1
2732 self.execution_count += 1
2727
2733
2728 return result
2734 return result
2729
2735
2730 def transform_ast(self, node):
2736 def transform_ast(self, node):
2731 """Apply the AST transformations from self.ast_transformers
2737 """Apply the AST transformations from self.ast_transformers
2732
2738
2733 Parameters
2739 Parameters
2734 ----------
2740 ----------
2735 node : ast.Node
2741 node : ast.Node
2736 The root node to be transformed. Typically called with the ast.Module
2742 The root node to be transformed. Typically called with the ast.Module
2737 produced by parsing user input.
2743 produced by parsing user input.
2738
2744
2739 Returns
2745 Returns
2740 -------
2746 -------
2741 An ast.Node corresponding to the node it was called with. Note that it
2747 An ast.Node corresponding to the node it was called with. Note that it
2742 may also modify the passed object, so don't rely on references to the
2748 may also modify the passed object, so don't rely on references to the
2743 original AST.
2749 original AST.
2744 """
2750 """
2745 for transformer in self.ast_transformers:
2751 for transformer in self.ast_transformers:
2746 try:
2752 try:
2747 node = transformer.visit(node)
2753 node = transformer.visit(node)
2748 except InputRejected:
2754 except InputRejected:
2749 # User-supplied AST transformers can reject an input by raising
2755 # User-supplied AST transformers can reject an input by raising
2750 # an InputRejected. Short-circuit in this case so that we
2756 # an InputRejected. Short-circuit in this case so that we
2751 # don't unregister the transform.
2757 # don't unregister the transform.
2752 raise
2758 raise
2753 except Exception:
2759 except Exception:
2754 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2760 warn("AST transformer %r threw an error. It will be unregistered." % transformer)
2755 self.ast_transformers.remove(transformer)
2761 self.ast_transformers.remove(transformer)
2756
2762
2757 if self.ast_transformers:
2763 if self.ast_transformers:
2758 ast.fix_missing_locations(node)
2764 ast.fix_missing_locations(node)
2759 return node
2765 return node
2760
2766
2761
2767
2762 def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
2768 def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr',
2763 compiler=compile, result=None):
2769 compiler=compile, result=None):
2764 """Run a sequence of AST nodes. The execution mode depends on the
2770 """Run a sequence of AST nodes. The execution mode depends on the
2765 interactivity parameter.
2771 interactivity parameter.
2766
2772
2767 Parameters
2773 Parameters
2768 ----------
2774 ----------
2769 nodelist : list
2775 nodelist : list
2770 A sequence of AST nodes to run.
2776 A sequence of AST nodes to run.
2771 cell_name : str
2777 cell_name : str
2772 Will be passed to the compiler as the filename of the cell. Typically
2778 Will be passed to the compiler as the filename of the cell. Typically
2773 the value returned by ip.compile.cache(cell).
2779 the value returned by ip.compile.cache(cell).
2774 interactivity : str
2780 interactivity : str
2775 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
2781 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
2776 specifying which nodes should be run interactively (displaying output
2782 specifying which nodes should be run interactively (displaying output
2777 from expressions). 'last_expr' will run the last node interactively
2783 from expressions). 'last_expr' will run the last node interactively
2778 only if it is an expression (i.e. expressions in loops or other blocks
2784 only if it is an expression (i.e. expressions in loops or other blocks
2779 are not displayed) 'last_expr_or_assign' will run the last expression
2785 are not displayed) 'last_expr_or_assign' will run the last expression
2780 or the last assignment. Other values for this parameter will raise a
2786 or the last assignment. Other values for this parameter will raise a
2781 ValueError.
2787 ValueError.
2782 compiler : callable
2788 compiler : callable
2783 A function with the same interface as the built-in compile(), to turn
2789 A function with the same interface as the built-in compile(), to turn
2784 the AST nodes into code objects. Default is the built-in compile().
2790 the AST nodes into code objects. Default is the built-in compile().
2785 result : ExecutionResult, optional
2791 result : ExecutionResult, optional
2786 An object to store exceptions that occur during execution.
2792 An object to store exceptions that occur during execution.
2787
2793
2788 Returns
2794 Returns
2789 -------
2795 -------
2790 True if an exception occurred while running code, False if it finished
2796 True if an exception occurred while running code, False if it finished
2791 running.
2797 running.
2792 """
2798 """
2793 if not nodelist:
2799 if not nodelist:
2794 return
2800 return
2795
2801
2796 if interactivity == 'last_expr_or_assign':
2802 if interactivity == 'last_expr_or_assign':
2797 if isinstance(nodelist[-1], _assign_nodes):
2803 if isinstance(nodelist[-1], _assign_nodes):
2798 asg = nodelist[-1]
2804 asg = nodelist[-1]
2799 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
2805 if isinstance(asg, ast.Assign) and len(asg.targets) == 1:
2800 target = asg.targets[0]
2806 target = asg.targets[0]
2801 elif isinstance(asg, _single_targets_nodes):
2807 elif isinstance(asg, _single_targets_nodes):
2802 target = asg.target
2808 target = asg.target
2803 else:
2809 else:
2804 target = None
2810 target = None
2805 if isinstance(target, ast.Name):
2811 if isinstance(target, ast.Name):
2806 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
2812 nnode = ast.Expr(ast.Name(target.id, ast.Load()))
2807 ast.fix_missing_locations(nnode)
2813 ast.fix_missing_locations(nnode)
2808 nodelist.append(nnode)
2814 nodelist.append(nnode)
2809 interactivity = 'last_expr'
2815 interactivity = 'last_expr'
2810
2816
2811 if interactivity == 'last_expr':
2817 if interactivity == 'last_expr':
2812 if isinstance(nodelist[-1], ast.Expr):
2818 if isinstance(nodelist[-1], ast.Expr):
2813 interactivity = "last"
2819 interactivity = "last"
2814 else:
2820 else:
2815 interactivity = "none"
2821 interactivity = "none"
2816
2822
2817 if interactivity == 'none':
2823 if interactivity == 'none':
2818 to_run_exec, to_run_interactive = nodelist, []
2824 to_run_exec, to_run_interactive = nodelist, []
2819 elif interactivity == 'last':
2825 elif interactivity == 'last':
2820 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2826 to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:]
2821 elif interactivity == 'all':
2827 elif interactivity == 'all':
2822 to_run_exec, to_run_interactive = [], nodelist
2828 to_run_exec, to_run_interactive = [], nodelist
2823 else:
2829 else:
2824 raise ValueError("Interactivity was %r" % interactivity)
2830 raise ValueError("Interactivity was %r" % interactivity)
2825
2831
2826 try:
2832 try:
2827 for i, node in enumerate(to_run_exec):
2833 for i, node in enumerate(to_run_exec):
2828 mod = ast.Module([node])
2834 mod = ast.Module([node])
2829 code = compiler(mod, cell_name, "exec")
2835 code = compiler(mod, cell_name, "exec")
2830 if self.run_code(code, result):
2836 if self.run_code(code, result):
2831 return True
2837 return True
2832
2838
2833 for i, node in enumerate(to_run_interactive):
2839 for i, node in enumerate(to_run_interactive):
2834 mod = ast.Interactive([node])
2840 mod = ast.Interactive([node])
2835 code = compiler(mod, cell_name, "single")
2841 code = compiler(mod, cell_name, "single")
2836 if self.run_code(code, result):
2842 if self.run_code(code, result):
2837 return True
2843 return True
2838
2844
2839 # Flush softspace
2845 # Flush softspace
2840 if softspace(sys.stdout, 0):
2846 if softspace(sys.stdout, 0):
2841 print()
2847 print()
2842
2848
2843 except:
2849 except:
2844 # It's possible to have exceptions raised here, typically by
2850 # It's possible to have exceptions raised here, typically by
2845 # compilation of odd code (such as a naked 'return' outside a
2851 # compilation of odd code (such as a naked 'return' outside a
2846 # function) that did parse but isn't valid. Typically the exception
2852 # function) that did parse but isn't valid. Typically the exception
2847 # is a SyntaxError, but it's safest just to catch anything and show
2853 # is a SyntaxError, but it's safest just to catch anything and show
2848 # the user a traceback.
2854 # the user a traceback.
2849
2855
2850 # We do only one try/except outside the loop to minimize the impact
2856 # We do only one try/except outside the loop to minimize the impact
2851 # on runtime, and also because if any node in the node list is
2857 # on runtime, and also because if any node in the node list is
2852 # broken, we should stop execution completely.
2858 # broken, we should stop execution completely.
2853 if result:
2859 if result:
2854 result.error_before_exec = sys.exc_info()[1]
2860 result.error_before_exec = sys.exc_info()[1]
2855 self.showtraceback()
2861 self.showtraceback()
2856 return True
2862 return True
2857
2863
2858 return False
2864 return False
2859
2865
2860 def run_code(self, code_obj, result=None):
2866 def run_code(self, code_obj, result=None):
2861 """Execute a code object.
2867 """Execute a code object.
2862
2868
2863 When an exception occurs, self.showtraceback() is called to display a
2869 When an exception occurs, self.showtraceback() is called to display a
2864 traceback.
2870 traceback.
2865
2871
2866 Parameters
2872 Parameters
2867 ----------
2873 ----------
2868 code_obj : code object
2874 code_obj : code object
2869 A compiled code object, to be executed
2875 A compiled code object, to be executed
2870 result : ExecutionResult, optional
2876 result : ExecutionResult, optional
2871 An object to store exceptions that occur during execution.
2877 An object to store exceptions that occur during execution.
2872
2878
2873 Returns
2879 Returns
2874 -------
2880 -------
2875 False : successful execution.
2881 False : successful execution.
2876 True : an error occurred.
2882 True : an error occurred.
2877 """
2883 """
2878 # Set our own excepthook in case the user code tries to call it
2884 # Set our own excepthook in case the user code tries to call it
2879 # directly, so that the IPython crash handler doesn't get triggered
2885 # directly, so that the IPython crash handler doesn't get triggered
2880 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2886 old_excepthook, sys.excepthook = sys.excepthook, self.excepthook
2881
2887
2882 # we save the original sys.excepthook in the instance, in case config
2888 # we save the original sys.excepthook in the instance, in case config
2883 # code (such as magics) needs access to it.
2889 # code (such as magics) needs access to it.
2884 self.sys_excepthook = old_excepthook
2890 self.sys_excepthook = old_excepthook
2885 outflag = True # happens in more places, so it's easier as default
2891 outflag = True # happens in more places, so it's easier as default
2886 try:
2892 try:
2887 try:
2893 try:
2888 self.hooks.pre_run_code_hook()
2894 self.hooks.pre_run_code_hook()
2889 #rprint('Running code', repr(code_obj)) # dbg
2895 #rprint('Running code', repr(code_obj)) # dbg
2890 exec(code_obj, self.user_global_ns, self.user_ns)
2896 exec(code_obj, self.user_global_ns, self.user_ns)
2891 finally:
2897 finally:
2892 # Reset our crash handler in place
2898 # Reset our crash handler in place
2893 sys.excepthook = old_excepthook
2899 sys.excepthook = old_excepthook
2894 except SystemExit as e:
2900 except SystemExit as e:
2895 if result is not None:
2901 if result is not None:
2896 result.error_in_exec = e
2902 result.error_in_exec = e
2897 self.showtraceback(exception_only=True)
2903 self.showtraceback(exception_only=True)
2898 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2904 warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
2899 except self.custom_exceptions:
2905 except self.custom_exceptions:
2900 etype, value, tb = sys.exc_info()
2906 etype, value, tb = sys.exc_info()
2901 if result is not None:
2907 if result is not None:
2902 result.error_in_exec = value
2908 result.error_in_exec = value
2903 self.CustomTB(etype, value, tb)
2909 self.CustomTB(etype, value, tb)
2904 except:
2910 except:
2905 if result is not None:
2911 if result is not None:
2906 result.error_in_exec = sys.exc_info()[1]
2912 result.error_in_exec = sys.exc_info()[1]
2907 self.showtraceback(running_compiled_code=True)
2913 self.showtraceback(running_compiled_code=True)
2908 else:
2914 else:
2909 outflag = False
2915 outflag = False
2910 return outflag
2916 return outflag
2911
2917
2912 # For backwards compatibility
2918 # For backwards compatibility
2913 runcode = run_code
2919 runcode = run_code
2914
2920
2915 #-------------------------------------------------------------------------
2921 #-------------------------------------------------------------------------
2916 # Things related to GUI support and pylab
2922 # Things related to GUI support and pylab
2917 #-------------------------------------------------------------------------
2923 #-------------------------------------------------------------------------
2918
2924
2919 active_eventloop = None
2925 active_eventloop = None
2920
2926
2921 def enable_gui(self, gui=None):
2927 def enable_gui(self, gui=None):
2922 raise NotImplementedError('Implement enable_gui in a subclass')
2928 raise NotImplementedError('Implement enable_gui in a subclass')
2923
2929
2924 def enable_matplotlib(self, gui=None):
2930 def enable_matplotlib(self, gui=None):
2925 """Enable interactive matplotlib and inline figure support.
2931 """Enable interactive matplotlib and inline figure support.
2926
2932
2927 This takes the following steps:
2933 This takes the following steps:
2928
2934
2929 1. select the appropriate eventloop and matplotlib backend
2935 1. select the appropriate eventloop and matplotlib backend
2930 2. set up matplotlib for interactive use with that backend
2936 2. set up matplotlib for interactive use with that backend
2931 3. configure formatters for inline figure display
2937 3. configure formatters for inline figure display
2932 4. enable the selected gui eventloop
2938 4. enable the selected gui eventloop
2933
2939
2934 Parameters
2940 Parameters
2935 ----------
2941 ----------
2936 gui : optional, string
2942 gui : optional, string
2937 If given, dictates the choice of matplotlib GUI backend to use
2943 If given, dictates the choice of matplotlib GUI backend to use
2938 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2944 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2939 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2945 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2940 matplotlib (as dictated by the matplotlib build-time options plus the
2946 matplotlib (as dictated by the matplotlib build-time options plus the
2941 user's matplotlibrc configuration file). Note that not all backends
2947 user's matplotlibrc configuration file). Note that not all backends
2942 make sense in all contexts, for example a terminal ipython can't
2948 make sense in all contexts, for example a terminal ipython can't
2943 display figures inline.
2949 display figures inline.
2944 """
2950 """
2945 from IPython.core import pylabtools as pt
2951 from IPython.core import pylabtools as pt
2946 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2952 gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
2947
2953
2948 if gui != 'inline':
2954 if gui != 'inline':
2949 # If we have our first gui selection, store it
2955 # If we have our first gui selection, store it
2950 if self.pylab_gui_select is None:
2956 if self.pylab_gui_select is None:
2951 self.pylab_gui_select = gui
2957 self.pylab_gui_select = gui
2952 # Otherwise if they are different
2958 # Otherwise if they are different
2953 elif gui != self.pylab_gui_select:
2959 elif gui != self.pylab_gui_select:
2954 print('Warning: Cannot change to a different GUI toolkit: %s.'
2960 print('Warning: Cannot change to a different GUI toolkit: %s.'
2955 ' Using %s instead.' % (gui, self.pylab_gui_select))
2961 ' Using %s instead.' % (gui, self.pylab_gui_select))
2956 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2962 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
2957
2963
2958 pt.activate_matplotlib(backend)
2964 pt.activate_matplotlib(backend)
2959 pt.configure_inline_support(self, backend)
2965 pt.configure_inline_support(self, backend)
2960
2966
2961 # Now we must activate the gui pylab wants to use, and fix %run to take
2967 # Now we must activate the gui pylab wants to use, and fix %run to take
2962 # plot updates into account
2968 # plot updates into account
2963 self.enable_gui(gui)
2969 self.enable_gui(gui)
2964 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2970 self.magics_manager.registry['ExecutionMagics'].default_runner = \
2965 pt.mpl_runner(self.safe_execfile)
2971 pt.mpl_runner(self.safe_execfile)
2966
2972
2967 return gui, backend
2973 return gui, backend
2968
2974
2969 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2975 def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
2970 """Activate pylab support at runtime.
2976 """Activate pylab support at runtime.
2971
2977
2972 This turns on support for matplotlib, preloads into the interactive
2978 This turns on support for matplotlib, preloads into the interactive
2973 namespace all of numpy and pylab, and configures IPython to correctly
2979 namespace all of numpy and pylab, and configures IPython to correctly
2974 interact with the GUI event loop. The GUI backend to be used can be
2980 interact with the GUI event loop. The GUI backend to be used can be
2975 optionally selected with the optional ``gui`` argument.
2981 optionally selected with the optional ``gui`` argument.
2976
2982
2977 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2983 This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
2978
2984
2979 Parameters
2985 Parameters
2980 ----------
2986 ----------
2981 gui : optional, string
2987 gui : optional, string
2982 If given, dictates the choice of matplotlib GUI backend to use
2988 If given, dictates the choice of matplotlib GUI backend to use
2983 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2989 (should be one of IPython's supported backends, 'qt', 'osx', 'tk',
2984 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2990 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
2985 matplotlib (as dictated by the matplotlib build-time options plus the
2991 matplotlib (as dictated by the matplotlib build-time options plus the
2986 user's matplotlibrc configuration file). Note that not all backends
2992 user's matplotlibrc configuration file). Note that not all backends
2987 make sense in all contexts, for example a terminal ipython can't
2993 make sense in all contexts, for example a terminal ipython can't
2988 display figures inline.
2994 display figures inline.
2989 import_all : optional, bool, default: True
2995 import_all : optional, bool, default: True
2990 Whether to do `from numpy import *` and `from pylab import *`
2996 Whether to do `from numpy import *` and `from pylab import *`
2991 in addition to module imports.
2997 in addition to module imports.
2992 welcome_message : deprecated
2998 welcome_message : deprecated
2993 This argument is ignored, no welcome message will be displayed.
2999 This argument is ignored, no welcome message will be displayed.
2994 """
3000 """
2995 from IPython.core.pylabtools import import_pylab
3001 from IPython.core.pylabtools import import_pylab
2996
3002
2997 gui, backend = self.enable_matplotlib(gui)
3003 gui, backend = self.enable_matplotlib(gui)
2998
3004
2999 # We want to prevent the loading of pylab to pollute the user's
3005 # We want to prevent the loading of pylab to pollute the user's
3000 # namespace as shown by the %who* magics, so we execute the activation
3006 # namespace as shown by the %who* magics, so we execute the activation
3001 # code in an empty namespace, and we update *both* user_ns and
3007 # code in an empty namespace, and we update *both* user_ns and
3002 # user_ns_hidden with this information.
3008 # user_ns_hidden with this information.
3003 ns = {}
3009 ns = {}
3004 import_pylab(ns, import_all)
3010 import_pylab(ns, import_all)
3005 # warn about clobbered names
3011 # warn about clobbered names
3006 ignored = {"__builtins__"}
3012 ignored = {"__builtins__"}
3007 both = set(ns).intersection(self.user_ns).difference(ignored)
3013 both = set(ns).intersection(self.user_ns).difference(ignored)
3008 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3014 clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ]
3009 self.user_ns.update(ns)
3015 self.user_ns.update(ns)
3010 self.user_ns_hidden.update(ns)
3016 self.user_ns_hidden.update(ns)
3011 return gui, backend, clobbered
3017 return gui, backend, clobbered
3012
3018
3013 #-------------------------------------------------------------------------
3019 #-------------------------------------------------------------------------
3014 # Utilities
3020 # Utilities
3015 #-------------------------------------------------------------------------
3021 #-------------------------------------------------------------------------
3016
3022
3017 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3023 def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
3018 """Expand python variables in a string.
3024 """Expand python variables in a string.
3019
3025
3020 The depth argument indicates how many frames above the caller should
3026 The depth argument indicates how many frames above the caller should
3021 be walked to look for the local namespace where to expand variables.
3027 be walked to look for the local namespace where to expand variables.
3022
3028
3023 The global namespace for expansion is always the user's interactive
3029 The global namespace for expansion is always the user's interactive
3024 namespace.
3030 namespace.
3025 """
3031 """
3026 ns = self.user_ns.copy()
3032 ns = self.user_ns.copy()
3027 try:
3033 try:
3028 frame = sys._getframe(depth+1)
3034 frame = sys._getframe(depth+1)
3029 except ValueError:
3035 except ValueError:
3030 # This is thrown if there aren't that many frames on the stack,
3036 # This is thrown if there aren't that many frames on the stack,
3031 # e.g. if a script called run_line_magic() directly.
3037 # e.g. if a script called run_line_magic() directly.
3032 pass
3038 pass
3033 else:
3039 else:
3034 ns.update(frame.f_locals)
3040 ns.update(frame.f_locals)
3035
3041
3036 try:
3042 try:
3037 # We have to use .vformat() here, because 'self' is a valid and common
3043 # We have to use .vformat() here, because 'self' is a valid and common
3038 # name, and expanding **ns for .format() would make it collide with
3044 # name, and expanding **ns for .format() would make it collide with
3039 # the 'self' argument of the method.
3045 # the 'self' argument of the method.
3040 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3046 cmd = formatter.vformat(cmd, args=[], kwargs=ns)
3041 except Exception:
3047 except Exception:
3042 # if formatter couldn't format, just let it go untransformed
3048 # if formatter couldn't format, just let it go untransformed
3043 pass
3049 pass
3044 return cmd
3050 return cmd
3045
3051
3046 def mktempfile(self, data=None, prefix='ipython_edit_'):
3052 def mktempfile(self, data=None, prefix='ipython_edit_'):
3047 """Make a new tempfile and return its filename.
3053 """Make a new tempfile and return its filename.
3048
3054
3049 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3055 This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
3050 but it registers the created filename internally so ipython cleans it up
3056 but it registers the created filename internally so ipython cleans it up
3051 at exit time.
3057 at exit time.
3052
3058
3053 Optional inputs:
3059 Optional inputs:
3054
3060
3055 - data(None): if data is given, it gets written out to the temp file
3061 - data(None): if data is given, it gets written out to the temp file
3056 immediately, and the file is closed again."""
3062 immediately, and the file is closed again."""
3057
3063
3058 dirname = tempfile.mkdtemp(prefix=prefix)
3064 dirname = tempfile.mkdtemp(prefix=prefix)
3059 self.tempdirs.append(dirname)
3065 self.tempdirs.append(dirname)
3060
3066
3061 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3067 handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname)
3062 os.close(handle) # On Windows, there can only be one open handle on a file
3068 os.close(handle) # On Windows, there can only be one open handle on a file
3063 self.tempfiles.append(filename)
3069 self.tempfiles.append(filename)
3064
3070
3065 if data:
3071 if data:
3066 tmp_file = open(filename,'w')
3072 tmp_file = open(filename,'w')
3067 tmp_file.write(data)
3073 tmp_file.write(data)
3068 tmp_file.close()
3074 tmp_file.close()
3069 return filename
3075 return filename
3070
3076
3071 @undoc
3077 @undoc
3072 def write(self,data):
3078 def write(self,data):
3073 """DEPRECATED: Write a string to the default output"""
3079 """DEPRECATED: Write a string to the default output"""
3074 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3080 warn('InteractiveShell.write() is deprecated, use sys.stdout instead',
3075 DeprecationWarning, stacklevel=2)
3081 DeprecationWarning, stacklevel=2)
3076 sys.stdout.write(data)
3082 sys.stdout.write(data)
3077
3083
3078 @undoc
3084 @undoc
3079 def write_err(self,data):
3085 def write_err(self,data):
3080 """DEPRECATED: Write a string to the default error output"""
3086 """DEPRECATED: Write a string to the default error output"""
3081 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3087 warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead',
3082 DeprecationWarning, stacklevel=2)
3088 DeprecationWarning, stacklevel=2)
3083 sys.stderr.write(data)
3089 sys.stderr.write(data)
3084
3090
3085 def ask_yes_no(self, prompt, default=None, interrupt=None):
3091 def ask_yes_no(self, prompt, default=None, interrupt=None):
3086 if self.quiet:
3092 if self.quiet:
3087 return True
3093 return True
3088 return ask_yes_no(prompt,default,interrupt)
3094 return ask_yes_no(prompt,default,interrupt)
3089
3095
3090 def show_usage(self):
3096 def show_usage(self):
3091 """Show a usage message"""
3097 """Show a usage message"""
3092 page.page(IPython.core.usage.interactive_usage)
3098 page.page(IPython.core.usage.interactive_usage)
3093
3099
3094 def extract_input_lines(self, range_str, raw=False):
3100 def extract_input_lines(self, range_str, raw=False):
3095 """Return as a string a set of input history slices.
3101 """Return as a string a set of input history slices.
3096
3102
3097 Parameters
3103 Parameters
3098 ----------
3104 ----------
3099 range_str : string
3105 range_str : string
3100 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3106 The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
3101 since this function is for use by magic functions which get their
3107 since this function is for use by magic functions which get their
3102 arguments as strings. The number before the / is the session
3108 arguments as strings. The number before the / is the session
3103 number: ~n goes n back from the current session.
3109 number: ~n goes n back from the current session.
3104
3110
3105 raw : bool, optional
3111 raw : bool, optional
3106 By default, the processed input is used. If this is true, the raw
3112 By default, the processed input is used. If this is true, the raw
3107 input history is used instead.
3113 input history is used instead.
3108
3114
3109 Notes
3115 Notes
3110 -----
3116 -----
3111
3117
3112 Slices can be described with two notations:
3118 Slices can be described with two notations:
3113
3119
3114 * ``N:M`` -> standard python form, means including items N...(M-1).
3120 * ``N:M`` -> standard python form, means including items N...(M-1).
3115 * ``N-M`` -> include items N..M (closed endpoint).
3121 * ``N-M`` -> include items N..M (closed endpoint).
3116 """
3122 """
3117 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3123 lines = self.history_manager.get_range_by_str(range_str, raw=raw)
3118 return "\n".join(x for _, _, x in lines)
3124 return "\n".join(x for _, _, x in lines)
3119
3125
3120 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3126 def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
3121 """Get a code string from history, file, url, or a string or macro.
3127 """Get a code string from history, file, url, or a string or macro.
3122
3128
3123 This is mainly used by magic functions.
3129 This is mainly used by magic functions.
3124
3130
3125 Parameters
3131 Parameters
3126 ----------
3132 ----------
3127
3133
3128 target : str
3134 target : str
3129
3135
3130 A string specifying code to retrieve. This will be tried respectively
3136 A string specifying code to retrieve. This will be tried respectively
3131 as: ranges of input history (see %history for syntax), url,
3137 as: ranges of input history (see %history for syntax), url,
3132 corresponding .py file, filename, or an expression evaluating to a
3138 corresponding .py file, filename, or an expression evaluating to a
3133 string or Macro in the user namespace.
3139 string or Macro in the user namespace.
3134
3140
3135 raw : bool
3141 raw : bool
3136 If true (default), retrieve raw history. Has no effect on the other
3142 If true (default), retrieve raw history. Has no effect on the other
3137 retrieval mechanisms.
3143 retrieval mechanisms.
3138
3144
3139 py_only : bool (default False)
3145 py_only : bool (default False)
3140 Only try to fetch python code, do not try alternative methods to decode file
3146 Only try to fetch python code, do not try alternative methods to decode file
3141 if unicode fails.
3147 if unicode fails.
3142
3148
3143 Returns
3149 Returns
3144 -------
3150 -------
3145 A string of code.
3151 A string of code.
3146
3152
3147 ValueError is raised if nothing is found, and TypeError if it evaluates
3153 ValueError is raised if nothing is found, and TypeError if it evaluates
3148 to an object of another type. In each case, .args[0] is a printable
3154 to an object of another type. In each case, .args[0] is a printable
3149 message.
3155 message.
3150 """
3156 """
3151 code = self.extract_input_lines(target, raw=raw) # Grab history
3157 code = self.extract_input_lines(target, raw=raw) # Grab history
3152 if code:
3158 if code:
3153 return code
3159 return code
3154 try:
3160 try:
3155 if target.startswith(('http://', 'https://')):
3161 if target.startswith(('http://', 'https://')):
3156 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3162 return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
3157 except UnicodeDecodeError:
3163 except UnicodeDecodeError:
3158 if not py_only :
3164 if not py_only :
3159 # Deferred import
3165 # Deferred import
3160 from urllib.request import urlopen
3166 from urllib.request import urlopen
3161 response = urlopen(target)
3167 response = urlopen(target)
3162 return response.read().decode('latin1')
3168 return response.read().decode('latin1')
3163 raise ValueError(("'%s' seem to be unreadable.") % target)
3169 raise ValueError(("'%s' seem to be unreadable.") % target)
3164
3170
3165 potential_target = [target]
3171 potential_target = [target]
3166 try :
3172 try :
3167 potential_target.insert(0,get_py_filename(target))
3173 potential_target.insert(0,get_py_filename(target))
3168 except IOError:
3174 except IOError:
3169 pass
3175 pass
3170
3176
3171 for tgt in potential_target :
3177 for tgt in potential_target :
3172 if os.path.isfile(tgt): # Read file
3178 if os.path.isfile(tgt): # Read file
3173 try :
3179 try :
3174 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3180 return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
3175 except UnicodeDecodeError :
3181 except UnicodeDecodeError :
3176 if not py_only :
3182 if not py_only :
3177 with io_open(tgt,'r', encoding='latin1') as f :
3183 with io_open(tgt,'r', encoding='latin1') as f :
3178 return f.read()
3184 return f.read()
3179 raise ValueError(("'%s' seem to be unreadable.") % target)
3185 raise ValueError(("'%s' seem to be unreadable.") % target)
3180 elif os.path.isdir(os.path.expanduser(tgt)):
3186 elif os.path.isdir(os.path.expanduser(tgt)):
3181 raise ValueError("'%s' is a directory, not a regular file." % target)
3187 raise ValueError("'%s' is a directory, not a regular file." % target)
3182
3188
3183 if search_ns:
3189 if search_ns:
3184 # Inspect namespace to load object source
3190 # Inspect namespace to load object source
3185 object_info = self.object_inspect(target, detail_level=1)
3191 object_info = self.object_inspect(target, detail_level=1)
3186 if object_info['found'] and object_info['source']:
3192 if object_info['found'] and object_info['source']:
3187 return object_info['source']
3193 return object_info['source']
3188
3194
3189 try: # User namespace
3195 try: # User namespace
3190 codeobj = eval(target, self.user_ns)
3196 codeobj = eval(target, self.user_ns)
3191 except Exception:
3197 except Exception:
3192 raise ValueError(("'%s' was not found in history, as a file, url, "
3198 raise ValueError(("'%s' was not found in history, as a file, url, "
3193 "nor in the user namespace.") % target)
3199 "nor in the user namespace.") % target)
3194
3200
3195 if isinstance(codeobj, str):
3201 if isinstance(codeobj, str):
3196 return codeobj
3202 return codeobj
3197 elif isinstance(codeobj, Macro):
3203 elif isinstance(codeobj, Macro):
3198 return codeobj.value
3204 return codeobj.value
3199
3205
3200 raise TypeError("%s is neither a string nor a macro." % target,
3206 raise TypeError("%s is neither a string nor a macro." % target,
3201 codeobj)
3207 codeobj)
3202
3208
3203 #-------------------------------------------------------------------------
3209 #-------------------------------------------------------------------------
3204 # Things related to IPython exiting
3210 # Things related to IPython exiting
3205 #-------------------------------------------------------------------------
3211 #-------------------------------------------------------------------------
3206 def atexit_operations(self):
3212 def atexit_operations(self):
3207 """This will be executed at the time of exit.
3213 """This will be executed at the time of exit.
3208
3214
3209 Cleanup operations and saving of persistent data that is done
3215 Cleanup operations and saving of persistent data that is done
3210 unconditionally by IPython should be performed here.
3216 unconditionally by IPython should be performed here.
3211
3217
3212 For things that may depend on startup flags or platform specifics (such
3218 For things that may depend on startup flags or platform specifics (such
3213 as having readline or not), register a separate atexit function in the
3219 as having readline or not), register a separate atexit function in the
3214 code that has the appropriate information, rather than trying to
3220 code that has the appropriate information, rather than trying to
3215 clutter
3221 clutter
3216 """
3222 """
3217 # Close the history session (this stores the end time and line count)
3223 # Close the history session (this stores the end time and line count)
3218 # this must be *before* the tempfile cleanup, in case of temporary
3224 # this must be *before* the tempfile cleanup, in case of temporary
3219 # history db
3225 # history db
3220 self.history_manager.end_session()
3226 self.history_manager.end_session()
3221
3227
3222 # Cleanup all tempfiles and folders left around
3228 # Cleanup all tempfiles and folders left around
3223 for tfile in self.tempfiles:
3229 for tfile in self.tempfiles:
3224 try:
3230 try:
3225 os.unlink(tfile)
3231 os.unlink(tfile)
3226 except OSError:
3232 except OSError:
3227 pass
3233 pass
3228
3234
3229 for tdir in self.tempdirs:
3235 for tdir in self.tempdirs:
3230 try:
3236 try:
3231 os.rmdir(tdir)
3237 os.rmdir(tdir)
3232 except OSError:
3238 except OSError:
3233 pass
3239 pass
3234
3240
3235 # Clear all user namespaces to release all references cleanly.
3241 # Clear all user namespaces to release all references cleanly.
3236 self.reset(new_session=False)
3242 self.reset(new_session=False)
3237
3243
3238 # Run user hooks
3244 # Run user hooks
3239 self.hooks.shutdown_hook()
3245 self.hooks.shutdown_hook()
3240
3246
3241 def cleanup(self):
3247 def cleanup(self):
3242 self.restore_sys_module_state()
3248 self.restore_sys_module_state()
3243
3249
3244
3250
3245 # Overridden in terminal subclass to change prompts
3251 # Overridden in terminal subclass to change prompts
3246 def switch_doctest_mode(self, mode):
3252 def switch_doctest_mode(self, mode):
3247 pass
3253 pass
3248
3254
3249
3255
3250 class InteractiveShellABC(metaclass=abc.ABCMeta):
3256 class InteractiveShellABC(metaclass=abc.ABCMeta):
3251 """An abstract base class for InteractiveShell."""
3257 """An abstract base class for InteractiveShell."""
3252
3258
3253 InteractiveShellABC.register(InteractiveShell)
3259 InteractiveShellABC.register(InteractiveShell)
@@ -1,318 +1,318 b''
1 """Implementation of magic functions related to History.
1 """Implementation of magic functions related to History.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Copyright (c) 2012, IPython Development Team.
4 # Copyright (c) 2012, IPython Development Team.
5 #
5 #
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7 #
7 #
8 # The full license is in the file COPYING.txt, distributed with this software.
8 # The full license is in the file COPYING.txt, distributed with this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14
14
15 # Stdlib
15 # Stdlib
16 import os
16 import os
17 import sys
17 import sys
18 from io import open as io_open
18 from io import open as io_open
19
19
20 # Our own packages
20 # Our own packages
21 from IPython.core.error import StdinNotImplementedError
21 from IPython.core.error import StdinNotImplementedError
22 from IPython.core.magic import Magics, magics_class, line_magic
22 from IPython.core.magic import Magics, magics_class, line_magic
23 from IPython.core.magic_arguments import (argument, magic_arguments,
23 from IPython.core.magic_arguments import (argument, magic_arguments,
24 parse_argstring)
24 parse_argstring)
25 from IPython.testing.skipdoctest import skip_doctest
25 from IPython.testing.skipdoctest import skip_doctest
26 from IPython.utils import io
26 from IPython.utils import io
27
27
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29 # Magics class implementation
29 # Magics class implementation
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31
31
32
32
33 _unspecified = object()
33 _unspecified = object()
34
34
35
35
36 @magics_class
36 @magics_class
37 class HistoryMagics(Magics):
37 class HistoryMagics(Magics):
38
38
39 @magic_arguments()
39 @magic_arguments()
40 @argument(
40 @argument(
41 '-n', dest='print_nums', action='store_true', default=False,
41 '-n', dest='print_nums', action='store_true', default=False,
42 help="""
42 help="""
43 print line numbers for each input.
43 print line numbers for each input.
44 This feature is only available if numbered prompts are in use.
44 This feature is only available if numbered prompts are in use.
45 """)
45 """)
46 @argument(
46 @argument(
47 '-o', dest='get_output', action='store_true', default=False,
47 '-o', dest='get_output', action='store_true', default=False,
48 help="also print outputs for each input.")
48 help="also print outputs for each input.")
49 @argument(
49 @argument(
50 '-p', dest='pyprompts', action='store_true', default=False,
50 '-p', dest='pyprompts', action='store_true', default=False,
51 help="""
51 help="""
52 print classic '>>>' python prompts before each input.
52 print classic '>>>' python prompts before each input.
53 This is useful for making documentation, and in conjunction
53 This is useful for making documentation, and in conjunction
54 with -o, for producing doctest-ready output.
54 with -o, for producing doctest-ready output.
55 """)
55 """)
56 @argument(
56 @argument(
57 '-t', dest='raw', action='store_false', default=True,
57 '-t', dest='raw', action='store_false', default=True,
58 help="""
58 help="""
59 print the 'translated' history, as IPython understands it.
59 print the 'translated' history, as IPython understands it.
60 IPython filters your input and converts it all into valid Python
60 IPython filters your input and converts it all into valid Python
61 source before executing it (things like magics or aliases are turned
61 source before executing it (things like magics or aliases are turned
62 into function calls, for example). With this option, you'll see the
62 into function calls, for example). With this option, you'll see the
63 native history instead of the user-entered version: '%%cd /' will be
63 native history instead of the user-entered version: '%%cd /' will be
64 seen as 'get_ipython().magic("%%cd /")' instead of '%%cd /'.
64 seen as 'get_ipython().run_line_magic("cd", "/")' instead of '%%cd /'.
65 """)
65 """)
66 @argument(
66 @argument(
67 '-f', dest='filename',
67 '-f', dest='filename',
68 help="""
68 help="""
69 FILENAME: instead of printing the output to the screen, redirect
69 FILENAME: instead of printing the output to the screen, redirect
70 it to the given file. The file is always overwritten, though *when
70 it to the given file. The file is always overwritten, though *when
71 it can*, IPython asks for confirmation first. In particular, running
71 it can*, IPython asks for confirmation first. In particular, running
72 the command 'history -f FILENAME' from the IPython Notebook
72 the command 'history -f FILENAME' from the IPython Notebook
73 interface will replace FILENAME even if it already exists *without*
73 interface will replace FILENAME even if it already exists *without*
74 confirmation.
74 confirmation.
75 """)
75 """)
76 @argument(
76 @argument(
77 '-g', dest='pattern', nargs='*', default=None,
77 '-g', dest='pattern', nargs='*', default=None,
78 help="""
78 help="""
79 treat the arg as a glob pattern to search for in (full) history.
79 treat the arg as a glob pattern to search for in (full) history.
80 This includes the saved history (almost all commands ever written).
80 This includes the saved history (almost all commands ever written).
81 The pattern may contain '?' to match one unknown character and '*'
81 The pattern may contain '?' to match one unknown character and '*'
82 to match any number of unknown characters. Use '%%hist -g' to show
82 to match any number of unknown characters. Use '%%hist -g' to show
83 full saved history (may be very long).
83 full saved history (may be very long).
84 """)
84 """)
85 @argument(
85 @argument(
86 '-l', dest='limit', type=int, nargs='?', default=_unspecified,
86 '-l', dest='limit', type=int, nargs='?', default=_unspecified,
87 help="""
87 help="""
88 get the last n lines from all sessions. Specify n as a single
88 get the last n lines from all sessions. Specify n as a single
89 arg, or the default is the last 10 lines.
89 arg, or the default is the last 10 lines.
90 """)
90 """)
91 @argument(
91 @argument(
92 '-u', dest='unique', action='store_true',
92 '-u', dest='unique', action='store_true',
93 help="""
93 help="""
94 when searching history using `-g`, show only unique history.
94 when searching history using `-g`, show only unique history.
95 """)
95 """)
96 @argument('range', nargs='*')
96 @argument('range', nargs='*')
97 @skip_doctest
97 @skip_doctest
98 @line_magic
98 @line_magic
99 def history(self, parameter_s = ''):
99 def history(self, parameter_s = ''):
100 """Print input history (_i<n> variables), with most recent last.
100 """Print input history (_i<n> variables), with most recent last.
101
101
102 By default, input history is printed without line numbers so it can be
102 By default, input history is printed without line numbers so it can be
103 directly pasted into an editor. Use -n to show them.
103 directly pasted into an editor. Use -n to show them.
104
104
105 By default, all input history from the current session is displayed.
105 By default, all input history from the current session is displayed.
106 Ranges of history can be indicated using the syntax:
106 Ranges of history can be indicated using the syntax:
107
107
108 ``4``
108 ``4``
109 Line 4, current session
109 Line 4, current session
110 ``4-6``
110 ``4-6``
111 Lines 4-6, current session
111 Lines 4-6, current session
112 ``243/1-5``
112 ``243/1-5``
113 Lines 1-5, session 243
113 Lines 1-5, session 243
114 ``~2/7``
114 ``~2/7``
115 Line 7, session 2 before current
115 Line 7, session 2 before current
116 ``~8/1-~6/5``
116 ``~8/1-~6/5``
117 From the first line of 8 sessions ago, to the fifth line of 6
117 From the first line of 8 sessions ago, to the fifth line of 6
118 sessions ago.
118 sessions ago.
119
119
120 Multiple ranges can be entered, separated by spaces
120 Multiple ranges can be entered, separated by spaces
121
121
122 The same syntax is used by %macro, %save, %edit, %rerun
122 The same syntax is used by %macro, %save, %edit, %rerun
123
123
124 Examples
124 Examples
125 --------
125 --------
126 ::
126 ::
127
127
128 In [6]: %history -n 4-6
128 In [6]: %history -n 4-6
129 4:a = 12
129 4:a = 12
130 5:print a**2
130 5:print a**2
131 6:%history -n 4-6
131 6:%history -n 4-6
132
132
133 """
133 """
134
134
135 args = parse_argstring(self.history, parameter_s)
135 args = parse_argstring(self.history, parameter_s)
136
136
137 # For brevity
137 # For brevity
138 history_manager = self.shell.history_manager
138 history_manager = self.shell.history_manager
139
139
140 def _format_lineno(session, line):
140 def _format_lineno(session, line):
141 """Helper function to format line numbers properly."""
141 """Helper function to format line numbers properly."""
142 if session in (0, history_manager.session_number):
142 if session in (0, history_manager.session_number):
143 return str(line)
143 return str(line)
144 return "%s/%s" % (session, line)
144 return "%s/%s" % (session, line)
145
145
146 # Check if output to specific file was requested.
146 # Check if output to specific file was requested.
147 outfname = args.filename
147 outfname = args.filename
148 if not outfname:
148 if not outfname:
149 outfile = sys.stdout # default
149 outfile = sys.stdout # default
150 # We don't want to close stdout at the end!
150 # We don't want to close stdout at the end!
151 close_at_end = False
151 close_at_end = False
152 else:
152 else:
153 if os.path.exists(outfname):
153 if os.path.exists(outfname):
154 try:
154 try:
155 ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
155 ans = io.ask_yes_no("File %r exists. Overwrite?" % outfname)
156 except StdinNotImplementedError:
156 except StdinNotImplementedError:
157 ans = True
157 ans = True
158 if not ans:
158 if not ans:
159 print('Aborting.')
159 print('Aborting.')
160 return
160 return
161 print("Overwriting file.")
161 print("Overwriting file.")
162 outfile = io_open(outfname, 'w', encoding='utf-8')
162 outfile = io_open(outfname, 'w', encoding='utf-8')
163 close_at_end = True
163 close_at_end = True
164
164
165 print_nums = args.print_nums
165 print_nums = args.print_nums
166 get_output = args.get_output
166 get_output = args.get_output
167 pyprompts = args.pyprompts
167 pyprompts = args.pyprompts
168 raw = args.raw
168 raw = args.raw
169
169
170 pattern = None
170 pattern = None
171 limit = None if args.limit is _unspecified else args.limit
171 limit = None if args.limit is _unspecified else args.limit
172
172
173 if args.pattern is not None:
173 if args.pattern is not None:
174 if args.pattern:
174 if args.pattern:
175 pattern = "*" + " ".join(args.pattern) + "*"
175 pattern = "*" + " ".join(args.pattern) + "*"
176 else:
176 else:
177 pattern = "*"
177 pattern = "*"
178 hist = history_manager.search(pattern, raw=raw, output=get_output,
178 hist = history_manager.search(pattern, raw=raw, output=get_output,
179 n=limit, unique=args.unique)
179 n=limit, unique=args.unique)
180 print_nums = True
180 print_nums = True
181 elif args.limit is not _unspecified:
181 elif args.limit is not _unspecified:
182 n = 10 if limit is None else limit
182 n = 10 if limit is None else limit
183 hist = history_manager.get_tail(n, raw=raw, output=get_output)
183 hist = history_manager.get_tail(n, raw=raw, output=get_output)
184 else:
184 else:
185 if args.range: # Get history by ranges
185 if args.range: # Get history by ranges
186 hist = history_manager.get_range_by_str(" ".join(args.range),
186 hist = history_manager.get_range_by_str(" ".join(args.range),
187 raw, get_output)
187 raw, get_output)
188 else: # Just get history for the current session
188 else: # Just get history for the current session
189 hist = history_manager.get_range(raw=raw, output=get_output)
189 hist = history_manager.get_range(raw=raw, output=get_output)
190
190
191 # We could be displaying the entire history, so let's not try to pull
191 # We could be displaying the entire history, so let's not try to pull
192 # it into a list in memory. Anything that needs more space will just
192 # it into a list in memory. Anything that needs more space will just
193 # misalign.
193 # misalign.
194 width = 4
194 width = 4
195
195
196 for session, lineno, inline in hist:
196 for session, lineno, inline in hist:
197 # Print user history with tabs expanded to 4 spaces. The GUI
197 # Print user history with tabs expanded to 4 spaces. The GUI
198 # clients use hard tabs for easier usability in auto-indented code,
198 # clients use hard tabs for easier usability in auto-indented code,
199 # but we want to produce PEP-8 compliant history for safe pasting
199 # but we want to produce PEP-8 compliant history for safe pasting
200 # into an editor.
200 # into an editor.
201 if get_output:
201 if get_output:
202 inline, output = inline
202 inline, output = inline
203 inline = inline.expandtabs(4).rstrip()
203 inline = inline.expandtabs(4).rstrip()
204
204
205 multiline = "\n" in inline
205 multiline = "\n" in inline
206 line_sep = '\n' if multiline else ' '
206 line_sep = '\n' if multiline else ' '
207 if print_nums:
207 if print_nums:
208 print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
208 print(u'%s:%s' % (_format_lineno(session, lineno).rjust(width),
209 line_sep), file=outfile, end=u'')
209 line_sep), file=outfile, end=u'')
210 if pyprompts:
210 if pyprompts:
211 print(u">>> ", end=u"", file=outfile)
211 print(u">>> ", end=u"", file=outfile)
212 if multiline:
212 if multiline:
213 inline = "\n... ".join(inline.splitlines()) + "\n..."
213 inline = "\n... ".join(inline.splitlines()) + "\n..."
214 print(inline, file=outfile)
214 print(inline, file=outfile)
215 if get_output and output:
215 if get_output and output:
216 print(output, file=outfile)
216 print(output, file=outfile)
217
217
218 if close_at_end:
218 if close_at_end:
219 outfile.close()
219 outfile.close()
220
220
221 @line_magic
221 @line_magic
222 def recall(self, arg):
222 def recall(self, arg):
223 r"""Repeat a command, or get command to input line for editing.
223 r"""Repeat a command, or get command to input line for editing.
224
224
225 %recall and %rep are equivalent.
225 %recall and %rep are equivalent.
226
226
227 - %recall (no arguments):
227 - %recall (no arguments):
228
228
229 Place a string version of last computation result (stored in the
229 Place a string version of last computation result (stored in the
230 special '_' variable) to the next input prompt. Allows you to create
230 special '_' variable) to the next input prompt. Allows you to create
231 elaborate command lines without using copy-paste::
231 elaborate command lines without using copy-paste::
232
232
233 In[1]: l = ["hei", "vaan"]
233 In[1]: l = ["hei", "vaan"]
234 In[2]: "".join(l)
234 In[2]: "".join(l)
235 Out[2]: heivaan
235 Out[2]: heivaan
236 In[3]: %recall
236 In[3]: %recall
237 In[4]: heivaan_ <== cursor blinking
237 In[4]: heivaan_ <== cursor blinking
238
238
239 %recall 45
239 %recall 45
240
240
241 Place history line 45 on the next input prompt. Use %hist to find
241 Place history line 45 on the next input prompt. Use %hist to find
242 out the number.
242 out the number.
243
243
244 %recall 1-4
244 %recall 1-4
245
245
246 Combine the specified lines into one cell, and place it on the next
246 Combine the specified lines into one cell, and place it on the next
247 input prompt. See %history for the slice syntax.
247 input prompt. See %history for the slice syntax.
248
248
249 %recall foo+bar
249 %recall foo+bar
250
250
251 If foo+bar can be evaluated in the user namespace, the result is
251 If foo+bar can be evaluated in the user namespace, the result is
252 placed at the next input prompt. Otherwise, the history is searched
252 placed at the next input prompt. Otherwise, the history is searched
253 for lines which contain that substring, and the most recent one is
253 for lines which contain that substring, and the most recent one is
254 placed at the next input prompt.
254 placed at the next input prompt.
255 """
255 """
256 if not arg: # Last output
256 if not arg: # Last output
257 self.shell.set_next_input(str(self.shell.user_ns["_"]))
257 self.shell.set_next_input(str(self.shell.user_ns["_"]))
258 return
258 return
259 # Get history range
259 # Get history range
260 histlines = self.shell.history_manager.get_range_by_str(arg)
260 histlines = self.shell.history_manager.get_range_by_str(arg)
261 cmd = "\n".join(x[2] for x in histlines)
261 cmd = "\n".join(x[2] for x in histlines)
262 if cmd:
262 if cmd:
263 self.shell.set_next_input(cmd.rstrip())
263 self.shell.set_next_input(cmd.rstrip())
264 return
264 return
265
265
266 try: # Variable in user namespace
266 try: # Variable in user namespace
267 cmd = str(eval(arg, self.shell.user_ns))
267 cmd = str(eval(arg, self.shell.user_ns))
268 except Exception: # Search for term in history
268 except Exception: # Search for term in history
269 histlines = self.shell.history_manager.search("*"+arg+"*")
269 histlines = self.shell.history_manager.search("*"+arg+"*")
270 for h in reversed([x[2] for x in histlines]):
270 for h in reversed([x[2] for x in histlines]):
271 if 'recall' in h or 'rep' in h:
271 if 'recall' in h or 'rep' in h:
272 continue
272 continue
273 self.shell.set_next_input(h.rstrip())
273 self.shell.set_next_input(h.rstrip())
274 return
274 return
275 else:
275 else:
276 self.shell.set_next_input(cmd.rstrip())
276 self.shell.set_next_input(cmd.rstrip())
277 print("Couldn't evaluate or find in history:", arg)
277 print("Couldn't evaluate or find in history:", arg)
278
278
279 @line_magic
279 @line_magic
280 def rerun(self, parameter_s=''):
280 def rerun(self, parameter_s=''):
281 """Re-run previous input
281 """Re-run previous input
282
282
283 By default, you can specify ranges of input history to be repeated
283 By default, you can specify ranges of input history to be repeated
284 (as with %history). With no arguments, it will repeat the last line.
284 (as with %history). With no arguments, it will repeat the last line.
285
285
286 Options:
286 Options:
287
287
288 -l <n> : Repeat the last n lines of input, not including the
288 -l <n> : Repeat the last n lines of input, not including the
289 current command.
289 current command.
290
290
291 -g foo : Repeat the most recent line which contains foo
291 -g foo : Repeat the most recent line which contains foo
292 """
292 """
293 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
293 opts, args = self.parse_options(parameter_s, 'l:g:', mode='string')
294 if "l" in opts: # Last n lines
294 if "l" in opts: # Last n lines
295 n = int(opts['l'])
295 n = int(opts['l'])
296 hist = self.shell.history_manager.get_tail(n)
296 hist = self.shell.history_manager.get_tail(n)
297 elif "g" in opts: # Search
297 elif "g" in opts: # Search
298 p = "*"+opts['g']+"*"
298 p = "*"+opts['g']+"*"
299 hist = list(self.shell.history_manager.search(p))
299 hist = list(self.shell.history_manager.search(p))
300 for l in reversed(hist):
300 for l in reversed(hist):
301 if "rerun" not in l[2]:
301 if "rerun" not in l[2]:
302 hist = [l] # The last match which isn't a %rerun
302 hist = [l] # The last match which isn't a %rerun
303 break
303 break
304 else:
304 else:
305 hist = [] # No matches except %rerun
305 hist = [] # No matches except %rerun
306 elif args: # Specify history ranges
306 elif args: # Specify history ranges
307 hist = self.shell.history_manager.get_range_by_str(args)
307 hist = self.shell.history_manager.get_range_by_str(args)
308 else: # Last line
308 else: # Last line
309 hist = self.shell.history_manager.get_tail(1)
309 hist = self.shell.history_manager.get_tail(1)
310 hist = [x[2] for x in hist]
310 hist = [x[2] for x in hist]
311 if not hist:
311 if not hist:
312 print("No lines in history match specification")
312 print("No lines in history match specification")
313 return
313 return
314 histlines = "\n".join(hist)
314 histlines = "\n".join(hist)
315 print("=== Executing: ===")
315 print("=== Executing: ===")
316 print(histlines)
316 print(histlines)
317 print("=== Output: ===")
317 print("=== Output: ===")
318 self.shell.run_cell("\n".join(hist), store_history=False)
318 self.shell.run_cell("\n".join(hist), store_history=False)
@@ -1,706 +1,709 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """
2 """
3 Prefiltering components.
3 Prefiltering components.
4
4
5 Prefilters transform user input before it is exec'd by Python. These
5 Prefilters transform user input before it is exec'd by Python. These
6 transforms are used to implement additional syntax such as !ls and %magic.
6 transforms are used to implement additional syntax such as !ls and %magic.
7 """
7 """
8
8
9 # Copyright (c) IPython Development Team.
9 # Copyright (c) IPython Development Team.
10 # Distributed under the terms of the Modified BSD License.
10 # Distributed under the terms of the Modified BSD License.
11
11
12 from keyword import iskeyword
12 from keyword import iskeyword
13 import re
13 import re
14
14
15 from IPython.core.autocall import IPyAutocall
15 from IPython.core.autocall import IPyAutocall
16 from traitlets.config.configurable import Configurable
16 from traitlets.config.configurable import Configurable
17 from IPython.core.inputsplitter import (
17 from IPython.core.inputsplitter import (
18 ESC_MAGIC,
18 ESC_MAGIC,
19 ESC_QUOTE,
19 ESC_QUOTE,
20 ESC_QUOTE2,
20 ESC_QUOTE2,
21 ESC_PAREN,
21 ESC_PAREN,
22 )
22 )
23 from IPython.core.macro import Macro
23 from IPython.core.macro import Macro
24 from IPython.core.splitinput import LineInfo
24 from IPython.core.splitinput import LineInfo
25
25
26 from traitlets import (
26 from traitlets import (
27 List, Integer, Unicode, Bool, Instance, CRegExp
27 List, Integer, Unicode, Bool, Instance, CRegExp
28 )
28 )
29
29
30 #-----------------------------------------------------------------------------
30 #-----------------------------------------------------------------------------
31 # Global utilities, errors and constants
31 # Global utilities, errors and constants
32 #-----------------------------------------------------------------------------
32 #-----------------------------------------------------------------------------
33
33
34
34
35 class PrefilterError(Exception):
35 class PrefilterError(Exception):
36 pass
36 pass
37
37
38
38
39 # RegExp to identify potential function names
39 # RegExp to identify potential function names
40 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
40 re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$')
41
41
42 # RegExp to exclude strings with this start from autocalling. In
42 # RegExp to exclude strings with this start from autocalling. In
43 # particular, all binary operators should be excluded, so that if foo is
43 # particular, all binary operators should be excluded, so that if foo is
44 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
44 # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The
45 # characters '!=()' don't need to be checked for, as the checkPythonChars
45 # characters '!=()' don't need to be checked for, as the checkPythonChars
46 # routine explicitely does so, to catch direct calls and rebindings of
46 # routine explicitely does so, to catch direct calls and rebindings of
47 # existing names.
47 # existing names.
48
48
49 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
49 # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise
50 # it affects the rest of the group in square brackets.
50 # it affects the rest of the group in square brackets.
51 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
51 re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]'
52 r'|^is |^not |^in |^and |^or ')
52 r'|^is |^not |^in |^and |^or ')
53
53
54 # try to catch also methods for stuff in lists/tuples/dicts: off
54 # try to catch also methods for stuff in lists/tuples/dicts: off
55 # (experimental). For this to work, the line_split regexp would need
55 # (experimental). For this to work, the line_split regexp would need
56 # to be modified so it wouldn't break things at '['. That line is
56 # to be modified so it wouldn't break things at '['. That line is
57 # nasty enough that I shouldn't change it until I can test it _well_.
57 # nasty enough that I shouldn't change it until I can test it _well_.
58 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
58 #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$')
59
59
60
60
61 # Handler Check Utilities
61 # Handler Check Utilities
62 def is_shadowed(identifier, ip):
62 def is_shadowed(identifier, ip):
63 """Is the given identifier defined in one of the namespaces which shadow
63 """Is the given identifier defined in one of the namespaces which shadow
64 the alias and magic namespaces? Note that an identifier is different
64 the alias and magic namespaces? Note that an identifier is different
65 than ifun, because it can not contain a '.' character."""
65 than ifun, because it can not contain a '.' character."""
66 # This is much safer than calling ofind, which can change state
66 # This is much safer than calling ofind, which can change state
67 return (identifier in ip.user_ns \
67 return (identifier in ip.user_ns \
68 or identifier in ip.user_global_ns \
68 or identifier in ip.user_global_ns \
69 or identifier in ip.ns_table['builtin']\
69 or identifier in ip.ns_table['builtin']\
70 or iskeyword(identifier))
70 or iskeyword(identifier))
71
71
72
72
73 #-----------------------------------------------------------------------------
73 #-----------------------------------------------------------------------------
74 # Main Prefilter manager
74 # Main Prefilter manager
75 #-----------------------------------------------------------------------------
75 #-----------------------------------------------------------------------------
76
76
77
77
78 class PrefilterManager(Configurable):
78 class PrefilterManager(Configurable):
79 """Main prefilter component.
79 """Main prefilter component.
80
80
81 The IPython prefilter is run on all user input before it is run. The
81 The IPython prefilter is run on all user input before it is run. The
82 prefilter consumes lines of input and produces transformed lines of
82 prefilter consumes lines of input and produces transformed lines of
83 input.
83 input.
84
84
85 The iplementation consists of two phases:
85 The iplementation consists of two phases:
86
86
87 1. Transformers
87 1. Transformers
88 2. Checkers and handlers
88 2. Checkers and handlers
89
89
90 Over time, we plan on deprecating the checkers and handlers and doing
90 Over time, we plan on deprecating the checkers and handlers and doing
91 everything in the transformers.
91 everything in the transformers.
92
92
93 The transformers are instances of :class:`PrefilterTransformer` and have
93 The transformers are instances of :class:`PrefilterTransformer` and have
94 a single method :meth:`transform` that takes a line and returns a
94 a single method :meth:`transform` that takes a line and returns a
95 transformed line. The transformation can be accomplished using any
95 transformed line. The transformation can be accomplished using any
96 tool, but our current ones use regular expressions for speed.
96 tool, but our current ones use regular expressions for speed.
97
97
98 After all the transformers have been run, the line is fed to the checkers,
98 After all the transformers have been run, the line is fed to the checkers,
99 which are instances of :class:`PrefilterChecker`. The line is passed to
99 which are instances of :class:`PrefilterChecker`. The line is passed to
100 the :meth:`check` method, which either returns `None` or a
100 the :meth:`check` method, which either returns `None` or a
101 :class:`PrefilterHandler` instance. If `None` is returned, the other
101 :class:`PrefilterHandler` instance. If `None` is returned, the other
102 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
102 checkers are tried. If an :class:`PrefilterHandler` instance is returned,
103 the line is passed to the :meth:`handle` method of the returned
103 the line is passed to the :meth:`handle` method of the returned
104 handler and no further checkers are tried.
104 handler and no further checkers are tried.
105
105
106 Both transformers and checkers have a `priority` attribute, that determines
106 Both transformers and checkers have a `priority` attribute, that determines
107 the order in which they are called. Smaller priorities are tried first.
107 the order in which they are called. Smaller priorities are tried first.
108
108
109 Both transformers and checkers also have `enabled` attribute, which is
109 Both transformers and checkers also have `enabled` attribute, which is
110 a boolean that determines if the instance is used.
110 a boolean that determines if the instance is used.
111
111
112 Users or developers can change the priority or enabled attribute of
112 Users or developers can change the priority or enabled attribute of
113 transformers or checkers, but they must call the :meth:`sort_checkers`
113 transformers or checkers, but they must call the :meth:`sort_checkers`
114 or :meth:`sort_transformers` method after changing the priority.
114 or :meth:`sort_transformers` method after changing the priority.
115 """
115 """
116
116
117 multi_line_specials = Bool(True).tag(config=True)
117 multi_line_specials = Bool(True).tag(config=True)
118 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
118 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
119
119
120 def __init__(self, shell=None, **kwargs):
120 def __init__(self, shell=None, **kwargs):
121 super(PrefilterManager, self).__init__(shell=shell, **kwargs)
121 super(PrefilterManager, self).__init__(shell=shell, **kwargs)
122 self.shell = shell
122 self.shell = shell
123 self.init_transformers()
123 self.init_transformers()
124 self.init_handlers()
124 self.init_handlers()
125 self.init_checkers()
125 self.init_checkers()
126
126
127 #-------------------------------------------------------------------------
127 #-------------------------------------------------------------------------
128 # API for managing transformers
128 # API for managing transformers
129 #-------------------------------------------------------------------------
129 #-------------------------------------------------------------------------
130
130
131 def init_transformers(self):
131 def init_transformers(self):
132 """Create the default transformers."""
132 """Create the default transformers."""
133 self._transformers = []
133 self._transformers = []
134 for transformer_cls in _default_transformers:
134 for transformer_cls in _default_transformers:
135 transformer_cls(
135 transformer_cls(
136 shell=self.shell, prefilter_manager=self, parent=self
136 shell=self.shell, prefilter_manager=self, parent=self
137 )
137 )
138
138
139 def sort_transformers(self):
139 def sort_transformers(self):
140 """Sort the transformers by priority.
140 """Sort the transformers by priority.
141
141
142 This must be called after the priority of a transformer is changed.
142 This must be called after the priority of a transformer is changed.
143 The :meth:`register_transformer` method calls this automatically.
143 The :meth:`register_transformer` method calls this automatically.
144 """
144 """
145 self._transformers.sort(key=lambda x: x.priority)
145 self._transformers.sort(key=lambda x: x.priority)
146
146
147 @property
147 @property
148 def transformers(self):
148 def transformers(self):
149 """Return a list of checkers, sorted by priority."""
149 """Return a list of checkers, sorted by priority."""
150 return self._transformers
150 return self._transformers
151
151
152 def register_transformer(self, transformer):
152 def register_transformer(self, transformer):
153 """Register a transformer instance."""
153 """Register a transformer instance."""
154 if transformer not in self._transformers:
154 if transformer not in self._transformers:
155 self._transformers.append(transformer)
155 self._transformers.append(transformer)
156 self.sort_transformers()
156 self.sort_transformers()
157
157
158 def unregister_transformer(self, transformer):
158 def unregister_transformer(self, transformer):
159 """Unregister a transformer instance."""
159 """Unregister a transformer instance."""
160 if transformer in self._transformers:
160 if transformer in self._transformers:
161 self._transformers.remove(transformer)
161 self._transformers.remove(transformer)
162
162
163 #-------------------------------------------------------------------------
163 #-------------------------------------------------------------------------
164 # API for managing checkers
164 # API for managing checkers
165 #-------------------------------------------------------------------------
165 #-------------------------------------------------------------------------
166
166
167 def init_checkers(self):
167 def init_checkers(self):
168 """Create the default checkers."""
168 """Create the default checkers."""
169 self._checkers = []
169 self._checkers = []
170 for checker in _default_checkers:
170 for checker in _default_checkers:
171 checker(
171 checker(
172 shell=self.shell, prefilter_manager=self, parent=self
172 shell=self.shell, prefilter_manager=self, parent=self
173 )
173 )
174
174
175 def sort_checkers(self):
175 def sort_checkers(self):
176 """Sort the checkers by priority.
176 """Sort the checkers by priority.
177
177
178 This must be called after the priority of a checker is changed.
178 This must be called after the priority of a checker is changed.
179 The :meth:`register_checker` method calls this automatically.
179 The :meth:`register_checker` method calls this automatically.
180 """
180 """
181 self._checkers.sort(key=lambda x: x.priority)
181 self._checkers.sort(key=lambda x: x.priority)
182
182
183 @property
183 @property
184 def checkers(self):
184 def checkers(self):
185 """Return a list of checkers, sorted by priority."""
185 """Return a list of checkers, sorted by priority."""
186 return self._checkers
186 return self._checkers
187
187
188 def register_checker(self, checker):
188 def register_checker(self, checker):
189 """Register a checker instance."""
189 """Register a checker instance."""
190 if checker not in self._checkers:
190 if checker not in self._checkers:
191 self._checkers.append(checker)
191 self._checkers.append(checker)
192 self.sort_checkers()
192 self.sort_checkers()
193
193
194 def unregister_checker(self, checker):
194 def unregister_checker(self, checker):
195 """Unregister a checker instance."""
195 """Unregister a checker instance."""
196 if checker in self._checkers:
196 if checker in self._checkers:
197 self._checkers.remove(checker)
197 self._checkers.remove(checker)
198
198
199 #-------------------------------------------------------------------------
199 #-------------------------------------------------------------------------
200 # API for managing handlers
200 # API for managing handlers
201 #-------------------------------------------------------------------------
201 #-------------------------------------------------------------------------
202
202
203 def init_handlers(self):
203 def init_handlers(self):
204 """Create the default handlers."""
204 """Create the default handlers."""
205 self._handlers = {}
205 self._handlers = {}
206 self._esc_handlers = {}
206 self._esc_handlers = {}
207 for handler in _default_handlers:
207 for handler in _default_handlers:
208 handler(
208 handler(
209 shell=self.shell, prefilter_manager=self, parent=self
209 shell=self.shell, prefilter_manager=self, parent=self
210 )
210 )
211
211
212 @property
212 @property
213 def handlers(self):
213 def handlers(self):
214 """Return a dict of all the handlers."""
214 """Return a dict of all the handlers."""
215 return self._handlers
215 return self._handlers
216
216
217 def register_handler(self, name, handler, esc_strings):
217 def register_handler(self, name, handler, esc_strings):
218 """Register a handler instance by name with esc_strings."""
218 """Register a handler instance by name with esc_strings."""
219 self._handlers[name] = handler
219 self._handlers[name] = handler
220 for esc_str in esc_strings:
220 for esc_str in esc_strings:
221 self._esc_handlers[esc_str] = handler
221 self._esc_handlers[esc_str] = handler
222
222
223 def unregister_handler(self, name, handler, esc_strings):
223 def unregister_handler(self, name, handler, esc_strings):
224 """Unregister a handler instance by name with esc_strings."""
224 """Unregister a handler instance by name with esc_strings."""
225 try:
225 try:
226 del self._handlers[name]
226 del self._handlers[name]
227 except KeyError:
227 except KeyError:
228 pass
228 pass
229 for esc_str in esc_strings:
229 for esc_str in esc_strings:
230 h = self._esc_handlers.get(esc_str)
230 h = self._esc_handlers.get(esc_str)
231 if h is handler:
231 if h is handler:
232 del self._esc_handlers[esc_str]
232 del self._esc_handlers[esc_str]
233
233
234 def get_handler_by_name(self, name):
234 def get_handler_by_name(self, name):
235 """Get a handler by its name."""
235 """Get a handler by its name."""
236 return self._handlers.get(name)
236 return self._handlers.get(name)
237
237
238 def get_handler_by_esc(self, esc_str):
238 def get_handler_by_esc(self, esc_str):
239 """Get a handler by its escape string."""
239 """Get a handler by its escape string."""
240 return self._esc_handlers.get(esc_str)
240 return self._esc_handlers.get(esc_str)
241
241
242 #-------------------------------------------------------------------------
242 #-------------------------------------------------------------------------
243 # Main prefiltering API
243 # Main prefiltering API
244 #-------------------------------------------------------------------------
244 #-------------------------------------------------------------------------
245
245
246 def prefilter_line_info(self, line_info):
246 def prefilter_line_info(self, line_info):
247 """Prefilter a line that has been converted to a LineInfo object.
247 """Prefilter a line that has been converted to a LineInfo object.
248
248
249 This implements the checker/handler part of the prefilter pipe.
249 This implements the checker/handler part of the prefilter pipe.
250 """
250 """
251 # print "prefilter_line_info: ", line_info
251 # print "prefilter_line_info: ", line_info
252 handler = self.find_handler(line_info)
252 handler = self.find_handler(line_info)
253 return handler.handle(line_info)
253 return handler.handle(line_info)
254
254
255 def find_handler(self, line_info):
255 def find_handler(self, line_info):
256 """Find a handler for the line_info by trying checkers."""
256 """Find a handler for the line_info by trying checkers."""
257 for checker in self.checkers:
257 for checker in self.checkers:
258 if checker.enabled:
258 if checker.enabled:
259 handler = checker.check(line_info)
259 handler = checker.check(line_info)
260 if handler:
260 if handler:
261 return handler
261 return handler
262 return self.get_handler_by_name('normal')
262 return self.get_handler_by_name('normal')
263
263
264 def transform_line(self, line, continue_prompt):
264 def transform_line(self, line, continue_prompt):
265 """Calls the enabled transformers in order of increasing priority."""
265 """Calls the enabled transformers in order of increasing priority."""
266 for transformer in self.transformers:
266 for transformer in self.transformers:
267 if transformer.enabled:
267 if transformer.enabled:
268 line = transformer.transform(line, continue_prompt)
268 line = transformer.transform(line, continue_prompt)
269 return line
269 return line
270
270
271 def prefilter_line(self, line, continue_prompt=False):
271 def prefilter_line(self, line, continue_prompt=False):
272 """Prefilter a single input line as text.
272 """Prefilter a single input line as text.
273
273
274 This method prefilters a single line of text by calling the
274 This method prefilters a single line of text by calling the
275 transformers and then the checkers/handlers.
275 transformers and then the checkers/handlers.
276 """
276 """
277
277
278 # print "prefilter_line: ", line, continue_prompt
278 # print "prefilter_line: ", line, continue_prompt
279 # All handlers *must* return a value, even if it's blank ('').
279 # All handlers *must* return a value, even if it's blank ('').
280
280
281 # save the line away in case we crash, so the post-mortem handler can
281 # save the line away in case we crash, so the post-mortem handler can
282 # record it
282 # record it
283 self.shell._last_input_line = line
283 self.shell._last_input_line = line
284
284
285 if not line:
285 if not line:
286 # Return immediately on purely empty lines, so that if the user
286 # Return immediately on purely empty lines, so that if the user
287 # previously typed some whitespace that started a continuation
287 # previously typed some whitespace that started a continuation
288 # prompt, he can break out of that loop with just an empty line.
288 # prompt, he can break out of that loop with just an empty line.
289 # This is how the default python prompt works.
289 # This is how the default python prompt works.
290 return ''
290 return ''
291
291
292 # At this point, we invoke our transformers.
292 # At this point, we invoke our transformers.
293 if not continue_prompt or (continue_prompt and self.multi_line_specials):
293 if not continue_prompt or (continue_prompt and self.multi_line_specials):
294 line = self.transform_line(line, continue_prompt)
294 line = self.transform_line(line, continue_prompt)
295
295
296 # Now we compute line_info for the checkers and handlers
296 # Now we compute line_info for the checkers and handlers
297 line_info = LineInfo(line, continue_prompt)
297 line_info = LineInfo(line, continue_prompt)
298
298
299 # the input history needs to track even empty lines
299 # the input history needs to track even empty lines
300 stripped = line.strip()
300 stripped = line.strip()
301
301
302 normal_handler = self.get_handler_by_name('normal')
302 normal_handler = self.get_handler_by_name('normal')
303 if not stripped:
303 if not stripped:
304 return normal_handler.handle(line_info)
304 return normal_handler.handle(line_info)
305
305
306 # special handlers are only allowed for single line statements
306 # special handlers are only allowed for single line statements
307 if continue_prompt and not self.multi_line_specials:
307 if continue_prompt and not self.multi_line_specials:
308 return normal_handler.handle(line_info)
308 return normal_handler.handle(line_info)
309
309
310 prefiltered = self.prefilter_line_info(line_info)
310 prefiltered = self.prefilter_line_info(line_info)
311 # print "prefiltered line: %r" % prefiltered
311 # print "prefiltered line: %r" % prefiltered
312 return prefiltered
312 return prefiltered
313
313
314 def prefilter_lines(self, lines, continue_prompt=False):
314 def prefilter_lines(self, lines, continue_prompt=False):
315 """Prefilter multiple input lines of text.
315 """Prefilter multiple input lines of text.
316
316
317 This is the main entry point for prefiltering multiple lines of
317 This is the main entry point for prefiltering multiple lines of
318 input. This simply calls :meth:`prefilter_line` for each line of
318 input. This simply calls :meth:`prefilter_line` for each line of
319 input.
319 input.
320
320
321 This covers cases where there are multiple lines in the user entry,
321 This covers cases where there are multiple lines in the user entry,
322 which is the case when the user goes back to a multiline history
322 which is the case when the user goes back to a multiline history
323 entry and presses enter.
323 entry and presses enter.
324 """
324 """
325 llines = lines.rstrip('\n').split('\n')
325 llines = lines.rstrip('\n').split('\n')
326 # We can get multiple lines in one shot, where multiline input 'blends'
326 # We can get multiple lines in one shot, where multiline input 'blends'
327 # into one line, in cases like recalling from the readline history
327 # into one line, in cases like recalling from the readline history
328 # buffer. We need to make sure that in such cases, we correctly
328 # buffer. We need to make sure that in such cases, we correctly
329 # communicate downstream which line is first and which are continuation
329 # communicate downstream which line is first and which are continuation
330 # ones.
330 # ones.
331 if len(llines) > 1:
331 if len(llines) > 1:
332 out = '\n'.join([self.prefilter_line(line, lnum>0)
332 out = '\n'.join([self.prefilter_line(line, lnum>0)
333 for lnum, line in enumerate(llines) ])
333 for lnum, line in enumerate(llines) ])
334 else:
334 else:
335 out = self.prefilter_line(llines[0], continue_prompt)
335 out = self.prefilter_line(llines[0], continue_prompt)
336
336
337 return out
337 return out
338
338
339 #-----------------------------------------------------------------------------
339 #-----------------------------------------------------------------------------
340 # Prefilter transformers
340 # Prefilter transformers
341 #-----------------------------------------------------------------------------
341 #-----------------------------------------------------------------------------
342
342
343
343
344 class PrefilterTransformer(Configurable):
344 class PrefilterTransformer(Configurable):
345 """Transform a line of user input."""
345 """Transform a line of user input."""
346
346
347 priority = Integer(100).tag(config=True)
347 priority = Integer(100).tag(config=True)
348 # Transformers don't currently use shell or prefilter_manager, but as we
348 # Transformers don't currently use shell or prefilter_manager, but as we
349 # move away from checkers and handlers, they will need them.
349 # move away from checkers and handlers, they will need them.
350 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
350 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
351 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
351 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
352 enabled = Bool(True).tag(config=True)
352 enabled = Bool(True).tag(config=True)
353
353
354 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
354 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
355 super(PrefilterTransformer, self).__init__(
355 super(PrefilterTransformer, self).__init__(
356 shell=shell, prefilter_manager=prefilter_manager, **kwargs
356 shell=shell, prefilter_manager=prefilter_manager, **kwargs
357 )
357 )
358 self.prefilter_manager.register_transformer(self)
358 self.prefilter_manager.register_transformer(self)
359
359
360 def transform(self, line, continue_prompt):
360 def transform(self, line, continue_prompt):
361 """Transform a line, returning the new one."""
361 """Transform a line, returning the new one."""
362 return None
362 return None
363
363
364 def __repr__(self):
364 def __repr__(self):
365 return "<%s(priority=%r, enabled=%r)>" % (
365 return "<%s(priority=%r, enabled=%r)>" % (
366 self.__class__.__name__, self.priority, self.enabled)
366 self.__class__.__name__, self.priority, self.enabled)
367
367
368
368
369 #-----------------------------------------------------------------------------
369 #-----------------------------------------------------------------------------
370 # Prefilter checkers
370 # Prefilter checkers
371 #-----------------------------------------------------------------------------
371 #-----------------------------------------------------------------------------
372
372
373
373
374 class PrefilterChecker(Configurable):
374 class PrefilterChecker(Configurable):
375 """Inspect an input line and return a handler for that line."""
375 """Inspect an input line and return a handler for that line."""
376
376
377 priority = Integer(100).tag(config=True)
377 priority = Integer(100).tag(config=True)
378 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
378 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
379 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
379 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
380 enabled = Bool(True).tag(config=True)
380 enabled = Bool(True).tag(config=True)
381
381
382 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
382 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
383 super(PrefilterChecker, self).__init__(
383 super(PrefilterChecker, self).__init__(
384 shell=shell, prefilter_manager=prefilter_manager, **kwargs
384 shell=shell, prefilter_manager=prefilter_manager, **kwargs
385 )
385 )
386 self.prefilter_manager.register_checker(self)
386 self.prefilter_manager.register_checker(self)
387
387
388 def check(self, line_info):
388 def check(self, line_info):
389 """Inspect line_info and return a handler instance or None."""
389 """Inspect line_info and return a handler instance or None."""
390 return None
390 return None
391
391
392 def __repr__(self):
392 def __repr__(self):
393 return "<%s(priority=%r, enabled=%r)>" % (
393 return "<%s(priority=%r, enabled=%r)>" % (
394 self.__class__.__name__, self.priority, self.enabled)
394 self.__class__.__name__, self.priority, self.enabled)
395
395
396
396
397 class EmacsChecker(PrefilterChecker):
397 class EmacsChecker(PrefilterChecker):
398
398
399 priority = Integer(100).tag(config=True)
399 priority = Integer(100).tag(config=True)
400 enabled = Bool(False).tag(config=True)
400 enabled = Bool(False).tag(config=True)
401
401
402 def check(self, line_info):
402 def check(self, line_info):
403 "Emacs ipython-mode tags certain input lines."
403 "Emacs ipython-mode tags certain input lines."
404 if line_info.line.endswith('# PYTHON-MODE'):
404 if line_info.line.endswith('# PYTHON-MODE'):
405 return self.prefilter_manager.get_handler_by_name('emacs')
405 return self.prefilter_manager.get_handler_by_name('emacs')
406 else:
406 else:
407 return None
407 return None
408
408
409
409
410 class MacroChecker(PrefilterChecker):
410 class MacroChecker(PrefilterChecker):
411
411
412 priority = Integer(250).tag(config=True)
412 priority = Integer(250).tag(config=True)
413
413
414 def check(self, line_info):
414 def check(self, line_info):
415 obj = self.shell.user_ns.get(line_info.ifun)
415 obj = self.shell.user_ns.get(line_info.ifun)
416 if isinstance(obj, Macro):
416 if isinstance(obj, Macro):
417 return self.prefilter_manager.get_handler_by_name('macro')
417 return self.prefilter_manager.get_handler_by_name('macro')
418 else:
418 else:
419 return None
419 return None
420
420
421
421
422 class IPyAutocallChecker(PrefilterChecker):
422 class IPyAutocallChecker(PrefilterChecker):
423
423
424 priority = Integer(300).tag(config=True)
424 priority = Integer(300).tag(config=True)
425
425
426 def check(self, line_info):
426 def check(self, line_info):
427 "Instances of IPyAutocall in user_ns get autocalled immediately"
427 "Instances of IPyAutocall in user_ns get autocalled immediately"
428 obj = self.shell.user_ns.get(line_info.ifun, None)
428 obj = self.shell.user_ns.get(line_info.ifun, None)
429 if isinstance(obj, IPyAutocall):
429 if isinstance(obj, IPyAutocall):
430 obj.set_ip(self.shell)
430 obj.set_ip(self.shell)
431 return self.prefilter_manager.get_handler_by_name('auto')
431 return self.prefilter_manager.get_handler_by_name('auto')
432 else:
432 else:
433 return None
433 return None
434
434
435
435
436 class AssignmentChecker(PrefilterChecker):
436 class AssignmentChecker(PrefilterChecker):
437
437
438 priority = Integer(600).tag(config=True)
438 priority = Integer(600).tag(config=True)
439
439
440 def check(self, line_info):
440 def check(self, line_info):
441 """Check to see if user is assigning to a var for the first time, in
441 """Check to see if user is assigning to a var for the first time, in
442 which case we want to avoid any sort of automagic / autocall games.
442 which case we want to avoid any sort of automagic / autocall games.
443
443
444 This allows users to assign to either alias or magic names true python
444 This allows users to assign to either alias or magic names true python
445 variables (the magic/alias systems always take second seat to true
445 variables (the magic/alias systems always take second seat to true
446 python code). E.g. ls='hi', or ls,that=1,2"""
446 python code). E.g. ls='hi', or ls,that=1,2"""
447 if line_info.the_rest:
447 if line_info.the_rest:
448 if line_info.the_rest[0] in '=,':
448 if line_info.the_rest[0] in '=,':
449 return self.prefilter_manager.get_handler_by_name('normal')
449 return self.prefilter_manager.get_handler_by_name('normal')
450 else:
450 else:
451 return None
451 return None
452
452
453
453
454 class AutoMagicChecker(PrefilterChecker):
454 class AutoMagicChecker(PrefilterChecker):
455
455
456 priority = Integer(700).tag(config=True)
456 priority = Integer(700).tag(config=True)
457
457
458 def check(self, line_info):
458 def check(self, line_info):
459 """If the ifun is magic, and automagic is on, run it. Note: normal,
459 """If the ifun is magic, and automagic is on, run it. Note: normal,
460 non-auto magic would already have been triggered via '%' in
460 non-auto magic would already have been triggered via '%' in
461 check_esc_chars. This just checks for automagic. Also, before
461 check_esc_chars. This just checks for automagic. Also, before
462 triggering the magic handler, make sure that there is nothing in the
462 triggering the magic handler, make sure that there is nothing in the
463 user namespace which could shadow it."""
463 user namespace which could shadow it."""
464 if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
464 if not self.shell.automagic or not self.shell.find_magic(line_info.ifun):
465 return None
465 return None
466
466
467 # We have a likely magic method. Make sure we should actually call it.
467 # We have a likely magic method. Make sure we should actually call it.
468 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
468 if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials:
469 return None
469 return None
470
470
471 head = line_info.ifun.split('.',1)[0]
471 head = line_info.ifun.split('.',1)[0]
472 if is_shadowed(head, self.shell):
472 if is_shadowed(head, self.shell):
473 return None
473 return None
474
474
475 return self.prefilter_manager.get_handler_by_name('magic')
475 return self.prefilter_manager.get_handler_by_name('magic')
476
476
477
477
478 class PythonOpsChecker(PrefilterChecker):
478 class PythonOpsChecker(PrefilterChecker):
479
479
480 priority = Integer(900).tag(config=True)
480 priority = Integer(900).tag(config=True)
481
481
482 def check(self, line_info):
482 def check(self, line_info):
483 """If the 'rest' of the line begins with a function call or pretty much
483 """If the 'rest' of the line begins with a function call or pretty much
484 any python operator, we should simply execute the line (regardless of
484 any python operator, we should simply execute the line (regardless of
485 whether or not there's a possible autocall expansion). This avoids
485 whether or not there's a possible autocall expansion). This avoids
486 spurious (and very confusing) geattr() accesses."""
486 spurious (and very confusing) geattr() accesses."""
487 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
487 if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|':
488 return self.prefilter_manager.get_handler_by_name('normal')
488 return self.prefilter_manager.get_handler_by_name('normal')
489 else:
489 else:
490 return None
490 return None
491
491
492
492
493 class AutocallChecker(PrefilterChecker):
493 class AutocallChecker(PrefilterChecker):
494
494
495 priority = Integer(1000).tag(config=True)
495 priority = Integer(1000).tag(config=True)
496
496
497 function_name_regexp = CRegExp(re_fun_name,
497 function_name_regexp = CRegExp(re_fun_name,
498 help="RegExp to identify potential function names."
498 help="RegExp to identify potential function names."
499 ).tag(config=True)
499 ).tag(config=True)
500 exclude_regexp = CRegExp(re_exclude_auto,
500 exclude_regexp = CRegExp(re_exclude_auto,
501 help="RegExp to exclude strings with this start from autocalling."
501 help="RegExp to exclude strings with this start from autocalling."
502 ).tag(config=True)
502 ).tag(config=True)
503
503
504 def check(self, line_info):
504 def check(self, line_info):
505 "Check if the initial word/function is callable and autocall is on."
505 "Check if the initial word/function is callable and autocall is on."
506 if not self.shell.autocall:
506 if not self.shell.autocall:
507 return None
507 return None
508
508
509 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
509 oinfo = line_info.ofind(self.shell) # This can mutate state via getattr
510 if not oinfo['found']:
510 if not oinfo['found']:
511 return None
511 return None
512
512
513 ignored_funs = ['b', 'f', 'r', 'u', 'br', 'rb', 'fr', 'rf']
513 ignored_funs = ['b', 'f', 'r', 'u', 'br', 'rb', 'fr', 'rf']
514 ifun = line_info.ifun
514 ifun = line_info.ifun
515 line = line_info.line
515 line = line_info.line
516 if ifun.lower() in ignored_funs and (line.startswith(ifun + "'") or line.startswith(ifun + '"')):
516 if ifun.lower() in ignored_funs and (line.startswith(ifun + "'") or line.startswith(ifun + '"')):
517 return None
517 return None
518
518
519 if callable(oinfo['obj']) \
519 if callable(oinfo['obj']) \
520 and (not self.exclude_regexp.match(line_info.the_rest)) \
520 and (not self.exclude_regexp.match(line_info.the_rest)) \
521 and self.function_name_regexp.match(line_info.ifun):
521 and self.function_name_regexp.match(line_info.ifun):
522 return self.prefilter_manager.get_handler_by_name('auto')
522 return self.prefilter_manager.get_handler_by_name('auto')
523 else:
523 else:
524 return None
524 return None
525
525
526
526
527 #-----------------------------------------------------------------------------
527 #-----------------------------------------------------------------------------
528 # Prefilter handlers
528 # Prefilter handlers
529 #-----------------------------------------------------------------------------
529 #-----------------------------------------------------------------------------
530
530
531
531
532 class PrefilterHandler(Configurable):
532 class PrefilterHandler(Configurable):
533
533
534 handler_name = Unicode('normal')
534 handler_name = Unicode('normal')
535 esc_strings = List([])
535 esc_strings = List([])
536 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
536 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC', allow_none=True)
537 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
537 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True)
538
538
539 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
539 def __init__(self, shell=None, prefilter_manager=None, **kwargs):
540 super(PrefilterHandler, self).__init__(
540 super(PrefilterHandler, self).__init__(
541 shell=shell, prefilter_manager=prefilter_manager, **kwargs
541 shell=shell, prefilter_manager=prefilter_manager, **kwargs
542 )
542 )
543 self.prefilter_manager.register_handler(
543 self.prefilter_manager.register_handler(
544 self.handler_name,
544 self.handler_name,
545 self,
545 self,
546 self.esc_strings
546 self.esc_strings
547 )
547 )
548
548
549 def handle(self, line_info):
549 def handle(self, line_info):
550 # print "normal: ", line_info
550 # print "normal: ", line_info
551 """Handle normal input lines. Use as a template for handlers."""
551 """Handle normal input lines. Use as a template for handlers."""
552
552
553 # With autoindent on, we need some way to exit the input loop, and I
553 # With autoindent on, we need some way to exit the input loop, and I
554 # don't want to force the user to have to backspace all the way to
554 # don't want to force the user to have to backspace all the way to
555 # clear the line. The rule will be in this case, that either two
555 # clear the line. The rule will be in this case, that either two
556 # lines of pure whitespace in a row, or a line of pure whitespace but
556 # lines of pure whitespace in a row, or a line of pure whitespace but
557 # of a size different to the indent level, will exit the input loop.
557 # of a size different to the indent level, will exit the input loop.
558 line = line_info.line
558 line = line_info.line
559 continue_prompt = line_info.continue_prompt
559 continue_prompt = line_info.continue_prompt
560
560
561 if (continue_prompt and
561 if (continue_prompt and
562 self.shell.autoindent and
562 self.shell.autoindent and
563 line.isspace() and
563 line.isspace() and
564 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
564 0 < abs(len(line) - self.shell.indent_current_nsp) <= 2):
565 line = ''
565 line = ''
566
566
567 return line
567 return line
568
568
569 def __str__(self):
569 def __str__(self):
570 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
570 return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name)
571
571
572
572
573 class MacroHandler(PrefilterHandler):
573 class MacroHandler(PrefilterHandler):
574 handler_name = Unicode("macro")
574 handler_name = Unicode("macro")
575
575
576 def handle(self, line_info):
576 def handle(self, line_info):
577 obj = self.shell.user_ns.get(line_info.ifun)
577 obj = self.shell.user_ns.get(line_info.ifun)
578 pre_space = line_info.pre_whitespace
578 pre_space = line_info.pre_whitespace
579 line_sep = "\n" + pre_space
579 line_sep = "\n" + pre_space
580 return pre_space + line_sep.join(obj.value.splitlines())
580 return pre_space + line_sep.join(obj.value.splitlines())
581
581
582
582
583 class MagicHandler(PrefilterHandler):
583 class MagicHandler(PrefilterHandler):
584
584
585 handler_name = Unicode('magic')
585 handler_name = Unicode('magic')
586 esc_strings = List([ESC_MAGIC])
586 esc_strings = List([ESC_MAGIC])
587
587
588 def handle(self, line_info):
588 def handle(self, line_info):
589 """Execute magic functions."""
589 """Execute magic functions."""
590 ifun = line_info.ifun
590 ifun = line_info.ifun
591 the_rest = line_info.the_rest
591 the_rest = line_info.the_rest
592 cmd = '%sget_ipython().magic(%r)' % (line_info.pre_whitespace,
592 #Prepare arguments for get_ipython().run_line_magic(magic_name, magic_args)
593 (ifun + " " + the_rest))
593 t_arg_s = ifun + " " + the_rest
594 t_magic_name, _, t_magic_arg_s = t_arg_s.partition(' ')
595 t_magic_name = t_magic_name.lstrip(ESC_MAGIC)
596 cmd = '%sget_ipython().run_line_magic(%r, %r)' % (line_info.pre_whitespace, t_magic_name, t_magic_arg_s)
594 return cmd
597 return cmd
595
598
596
599
597 class AutoHandler(PrefilterHandler):
600 class AutoHandler(PrefilterHandler):
598
601
599 handler_name = Unicode('auto')
602 handler_name = Unicode('auto')
600 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
603 esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2])
601
604
602 def handle(self, line_info):
605 def handle(self, line_info):
603 """Handle lines which can be auto-executed, quoting if requested."""
606 """Handle lines which can be auto-executed, quoting if requested."""
604 line = line_info.line
607 line = line_info.line
605 ifun = line_info.ifun
608 ifun = line_info.ifun
606 the_rest = line_info.the_rest
609 the_rest = line_info.the_rest
607 esc = line_info.esc
610 esc = line_info.esc
608 continue_prompt = line_info.continue_prompt
611 continue_prompt = line_info.continue_prompt
609 obj = line_info.ofind(self.shell)['obj']
612 obj = line_info.ofind(self.shell)['obj']
610
613
611 # This should only be active for single-line input!
614 # This should only be active for single-line input!
612 if continue_prompt:
615 if continue_prompt:
613 return line
616 return line
614
617
615 force_auto = isinstance(obj, IPyAutocall)
618 force_auto = isinstance(obj, IPyAutocall)
616
619
617 # User objects sometimes raise exceptions on attribute access other
620 # User objects sometimes raise exceptions on attribute access other
618 # than AttributeError (we've seen it in the past), so it's safest to be
621 # than AttributeError (we've seen it in the past), so it's safest to be
619 # ultra-conservative here and catch all.
622 # ultra-conservative here and catch all.
620 try:
623 try:
621 auto_rewrite = obj.rewrite
624 auto_rewrite = obj.rewrite
622 except Exception:
625 except Exception:
623 auto_rewrite = True
626 auto_rewrite = True
624
627
625 if esc == ESC_QUOTE:
628 if esc == ESC_QUOTE:
626 # Auto-quote splitting on whitespace
629 # Auto-quote splitting on whitespace
627 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
630 newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) )
628 elif esc == ESC_QUOTE2:
631 elif esc == ESC_QUOTE2:
629 # Auto-quote whole string
632 # Auto-quote whole string
630 newcmd = '%s("%s")' % (ifun,the_rest)
633 newcmd = '%s("%s")' % (ifun,the_rest)
631 elif esc == ESC_PAREN:
634 elif esc == ESC_PAREN:
632 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
635 newcmd = '%s(%s)' % (ifun,",".join(the_rest.split()))
633 else:
636 else:
634 # Auto-paren.
637 # Auto-paren.
635 if force_auto:
638 if force_auto:
636 # Don't rewrite if it is already a call.
639 # Don't rewrite if it is already a call.
637 do_rewrite = not the_rest.startswith('(')
640 do_rewrite = not the_rest.startswith('(')
638 else:
641 else:
639 if not the_rest:
642 if not the_rest:
640 # We only apply it to argument-less calls if the autocall
643 # We only apply it to argument-less calls if the autocall
641 # parameter is set to 2.
644 # parameter is set to 2.
642 do_rewrite = (self.shell.autocall >= 2)
645 do_rewrite = (self.shell.autocall >= 2)
643 elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
646 elif the_rest.startswith('[') and hasattr(obj, '__getitem__'):
644 # Don't autocall in this case: item access for an object
647 # Don't autocall in this case: item access for an object
645 # which is BOTH callable and implements __getitem__.
648 # which is BOTH callable and implements __getitem__.
646 do_rewrite = False
649 do_rewrite = False
647 else:
650 else:
648 do_rewrite = True
651 do_rewrite = True
649
652
650 # Figure out the rewritten command
653 # Figure out the rewritten command
651 if do_rewrite:
654 if do_rewrite:
652 if the_rest.endswith(';'):
655 if the_rest.endswith(';'):
653 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
656 newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1])
654 else:
657 else:
655 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
658 newcmd = '%s(%s)' % (ifun.rstrip(), the_rest)
656 else:
659 else:
657 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
660 normal_handler = self.prefilter_manager.get_handler_by_name('normal')
658 return normal_handler.handle(line_info)
661 return normal_handler.handle(line_info)
659
662
660 # Display the rewritten call
663 # Display the rewritten call
661 if auto_rewrite:
664 if auto_rewrite:
662 self.shell.auto_rewrite_input(newcmd)
665 self.shell.auto_rewrite_input(newcmd)
663
666
664 return newcmd
667 return newcmd
665
668
666
669
667 class EmacsHandler(PrefilterHandler):
670 class EmacsHandler(PrefilterHandler):
668
671
669 handler_name = Unicode('emacs')
672 handler_name = Unicode('emacs')
670 esc_strings = List([])
673 esc_strings = List([])
671
674
672 def handle(self, line_info):
675 def handle(self, line_info):
673 """Handle input lines marked by python-mode."""
676 """Handle input lines marked by python-mode."""
674
677
675 # Currently, nothing is done. Later more functionality can be added
678 # Currently, nothing is done. Later more functionality can be added
676 # here if needed.
679 # here if needed.
677
680
678 # The input cache shouldn't be updated
681 # The input cache shouldn't be updated
679 return line_info.line
682 return line_info.line
680
683
681
684
682 #-----------------------------------------------------------------------------
685 #-----------------------------------------------------------------------------
683 # Defaults
686 # Defaults
684 #-----------------------------------------------------------------------------
687 #-----------------------------------------------------------------------------
685
688
686
689
687 _default_transformers = [
690 _default_transformers = [
688 ]
691 ]
689
692
690 _default_checkers = [
693 _default_checkers = [
691 EmacsChecker,
694 EmacsChecker,
692 MacroChecker,
695 MacroChecker,
693 IPyAutocallChecker,
696 IPyAutocallChecker,
694 AssignmentChecker,
697 AssignmentChecker,
695 AutoMagicChecker,
698 AutoMagicChecker,
696 PythonOpsChecker,
699 PythonOpsChecker,
697 AutocallChecker
700 AutocallChecker
698 ]
701 ]
699
702
700 _default_handlers = [
703 _default_handlers = [
701 PrefilterHandler,
704 PrefilterHandler,
702 MacroHandler,
705 MacroHandler,
703 MagicHandler,
706 MagicHandler,
704 AutoHandler,
707 AutoHandler,
705 EmacsHandler
708 EmacsHandler
706 ]
709 ]
@@ -1,97 +1,97 b''
1 """Tests for input handlers.
1 """Tests for input handlers.
2 """
2 """
3 #-----------------------------------------------------------------------------
3 #-----------------------------------------------------------------------------
4 # Module imports
4 # Module imports
5 #-----------------------------------------------------------------------------
5 #-----------------------------------------------------------------------------
6
6
7 # third party
7 # third party
8 import nose.tools as nt
8 import nose.tools as nt
9
9
10 # our own packages
10 # our own packages
11 from IPython.core import autocall
11 from IPython.core import autocall
12 from IPython.testing import tools as tt
12 from IPython.testing import tools as tt
13 from IPython.testing.globalipapp import get_ipython
13 from IPython.testing.globalipapp import get_ipython
14 from IPython.utils import py3compat
14 from IPython.utils import py3compat
15
15
16 #-----------------------------------------------------------------------------
16 #-----------------------------------------------------------------------------
17 # Globals
17 # Globals
18 #-----------------------------------------------------------------------------
18 #-----------------------------------------------------------------------------
19
19
20 # Get the public instance of IPython
20 # Get the public instance of IPython
21 ip = get_ipython()
21 ip = get_ipython()
22
22
23 failures = []
23 failures = []
24 num_tests = 0
24 num_tests = 0
25
25
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27 # Test functions
27 # Test functions
28 #-----------------------------------------------------------------------------
28 #-----------------------------------------------------------------------------
29
29
30 class CallableIndexable(object):
30 class CallableIndexable(object):
31 def __getitem__(self, idx): return True
31 def __getitem__(self, idx): return True
32 def __call__(self, *args, **kws): return True
32 def __call__(self, *args, **kws): return True
33
33
34
34
35 class Autocallable(autocall.IPyAutocall):
35 class Autocallable(autocall.IPyAutocall):
36 def __call__(self):
36 def __call__(self):
37 return "called"
37 return "called"
38
38
39
39
40 def run(tests):
40 def run(tests):
41 """Loop through a list of (pre, post) inputs, where pre is the string
41 """Loop through a list of (pre, post) inputs, where pre is the string
42 handed to ipython, and post is how that string looks after it's been
42 handed to ipython, and post is how that string looks after it's been
43 transformed (i.e. ipython's notion of _i)"""
43 transformed (i.e. ipython's notion of _i)"""
44 tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests)
44 tt.check_pairs(ip.prefilter_manager.prefilter_lines, tests)
45
45
46
46
47 def test_handlers():
47 def test_handlers():
48 call_idx = CallableIndexable()
48 call_idx = CallableIndexable()
49 ip.user_ns['call_idx'] = call_idx
49 ip.user_ns['call_idx'] = call_idx
50
50
51 # For many of the below, we're also checking that leading whitespace
51 # For many of the below, we're also checking that leading whitespace
52 # turns off the esc char, which it should unless there is a continuation
52 # turns off the esc char, which it should unless there is a continuation
53 # line.
53 # line.
54 run([(i,py3compat.u_format(o)) for i,o in \
54 run([(i,py3compat.u_format(o)) for i,o in \
55 [('"no change"', '"no change"'), # normal
55 [('"no change"', '"no change"'), # normal
56 (u"lsmagic", "get_ipython().magic({u}'lsmagic ')"), # magic
56 (u"lsmagic", "get_ipython().run_line_magic('lsmagic', '')"), # magic
57 #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
57 #("a = b # PYTHON-MODE", '_i'), # emacs -- avoids _in cache
58 ]])
58 ]])
59
59
60 # Objects which are instances of IPyAutocall are *always* autocalled
60 # Objects which are instances of IPyAutocall are *always* autocalled
61 autocallable = Autocallable()
61 autocallable = Autocallable()
62 ip.user_ns['autocallable'] = autocallable
62 ip.user_ns['autocallable'] = autocallable
63
63
64 # auto
64 # auto
65 ip.magic('autocall 0')
65 ip.magic('autocall 0')
66 # Only explicit escapes or instances of IPyAutocallable should get
66 # Only explicit escapes or instances of IPyAutocallable should get
67 # expanded
67 # expanded
68 run([
68 run([
69 ('len "abc"', 'len "abc"'),
69 ('len "abc"', 'len "abc"'),
70 ('autocallable', 'autocallable()'),
70 ('autocallable', 'autocallable()'),
71 # Don't add extra brackets (gh-1117)
71 # Don't add extra brackets (gh-1117)
72 ('autocallable()', 'autocallable()'),
72 ('autocallable()', 'autocallable()'),
73 ])
73 ])
74 ip.magic('autocall 1')
74 ip.magic('autocall 1')
75 run([
75 run([
76 ('len "abc"', 'len("abc")'),
76 ('len "abc"', 'len("abc")'),
77 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
77 ('len "abc";', 'len("abc");'), # ; is special -- moves out of parens
78 # Autocall is turned off if first arg is [] and the object
78 # Autocall is turned off if first arg is [] and the object
79 # is both callable and indexable. Like so:
79 # is both callable and indexable. Like so:
80 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
80 ('len [1,2]', 'len([1,2])'), # len doesn't support __getitem__...
81 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
81 ('call_idx [1]', 'call_idx [1]'), # call_idx *does*..
82 ('call_idx 1', 'call_idx(1)'),
82 ('call_idx 1', 'call_idx(1)'),
83 ('len', 'len'), # only at 2 does it auto-call on single args
83 ('len', 'len'), # only at 2 does it auto-call on single args
84 ])
84 ])
85 ip.magic('autocall 2')
85 ip.magic('autocall 2')
86 run([
86 run([
87 ('len "abc"', 'len("abc")'),
87 ('len "abc"', 'len("abc")'),
88 ('len "abc";', 'len("abc");'),
88 ('len "abc";', 'len("abc");'),
89 ('len [1,2]', 'len([1,2])'),
89 ('len [1,2]', 'len([1,2])'),
90 ('call_idx [1]', 'call_idx [1]'),
90 ('call_idx [1]', 'call_idx [1]'),
91 ('call_idx 1', 'call_idx(1)'),
91 ('call_idx 1', 'call_idx(1)'),
92 # This is what's different:
92 # This is what's different:
93 ('len', 'len()'), # only at 2 does it auto-call on single args
93 ('len', 'len()'), # only at 2 does it auto-call on single args
94 ])
94 ])
95 ip.magic('autocall 1')
95 ip.magic('autocall 1')
96
96
97 nt.assert_equal(failures, [])
97 nt.assert_equal(failures, [])
@@ -1,641 +1,641 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for the inputsplitter module."""
2 """Tests for the inputsplitter module."""
3
3
4
4
5 # Copyright (c) IPython Development Team.
5 # Copyright (c) IPython Development Team.
6 # Distributed under the terms of the Modified BSD License.
6 # Distributed under the terms of the Modified BSD License.
7
7
8 import unittest
8 import unittest
9 import sys
9 import sys
10
10
11 import nose.tools as nt
11 import nose.tools as nt
12
12
13 from IPython.core import inputsplitter as isp
13 from IPython.core import inputsplitter as isp
14 from IPython.core.inputtransformer import InputTransformer
14 from IPython.core.inputtransformer import InputTransformer
15 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
15 from IPython.core.tests.test_inputtransformer import syntax, syntax_ml
16 from IPython.testing import tools as tt
16 from IPython.testing import tools as tt
17 from IPython.utils import py3compat
17 from IPython.utils import py3compat
18 from IPython.utils.py3compat import input
18 from IPython.utils.py3compat import input
19
19
20 #-----------------------------------------------------------------------------
20 #-----------------------------------------------------------------------------
21 # Semi-complete examples (also used as tests)
21 # Semi-complete examples (also used as tests)
22 #-----------------------------------------------------------------------------
22 #-----------------------------------------------------------------------------
23
23
24 # Note: at the bottom, there's a slightly more complete version of this that
24 # Note: at the bottom, there's a slightly more complete version of this that
25 # can be useful during development of code here.
25 # can be useful during development of code here.
26
26
27 def mini_interactive_loop(input_func):
27 def mini_interactive_loop(input_func):
28 """Minimal example of the logic of an interactive interpreter loop.
28 """Minimal example of the logic of an interactive interpreter loop.
29
29
30 This serves as an example, and it is used by the test system with a fake
30 This serves as an example, and it is used by the test system with a fake
31 raw_input that simulates interactive input."""
31 raw_input that simulates interactive input."""
32
32
33 from IPython.core.inputsplitter import InputSplitter
33 from IPython.core.inputsplitter import InputSplitter
34
34
35 isp = InputSplitter()
35 isp = InputSplitter()
36 # In practice, this input loop would be wrapped in an outside loop to read
36 # In practice, this input loop would be wrapped in an outside loop to read
37 # input indefinitely, until some exit/quit command was issued. Here we
37 # input indefinitely, until some exit/quit command was issued. Here we
38 # only illustrate the basic inner loop.
38 # only illustrate the basic inner loop.
39 while isp.push_accepts_more():
39 while isp.push_accepts_more():
40 indent = ' '*isp.indent_spaces
40 indent = ' '*isp.indent_spaces
41 prompt = '>>> ' + indent
41 prompt = '>>> ' + indent
42 line = indent + input_func(prompt)
42 line = indent + input_func(prompt)
43 isp.push(line)
43 isp.push(line)
44
44
45 # Here we just return input so we can use it in a test suite, but a real
45 # Here we just return input so we can use it in a test suite, but a real
46 # interpreter would instead send it for execution somewhere.
46 # interpreter would instead send it for execution somewhere.
47 src = isp.source_reset()
47 src = isp.source_reset()
48 #print 'Input source was:\n', src # dbg
48 #print 'Input source was:\n', src # dbg
49 return src
49 return src
50
50
51 #-----------------------------------------------------------------------------
51 #-----------------------------------------------------------------------------
52 # Test utilities, just for local use
52 # Test utilities, just for local use
53 #-----------------------------------------------------------------------------
53 #-----------------------------------------------------------------------------
54
54
55 def assemble(block):
55 def assemble(block):
56 """Assemble a block into multi-line sub-blocks."""
56 """Assemble a block into multi-line sub-blocks."""
57 return ['\n'.join(sub_block)+'\n' for sub_block in block]
57 return ['\n'.join(sub_block)+'\n' for sub_block in block]
58
58
59
59
60 def pseudo_input(lines):
60 def pseudo_input(lines):
61 """Return a function that acts like raw_input but feeds the input list."""
61 """Return a function that acts like raw_input but feeds the input list."""
62 ilines = iter(lines)
62 ilines = iter(lines)
63 def raw_in(prompt):
63 def raw_in(prompt):
64 try:
64 try:
65 return next(ilines)
65 return next(ilines)
66 except StopIteration:
66 except StopIteration:
67 return ''
67 return ''
68 return raw_in
68 return raw_in
69
69
70 #-----------------------------------------------------------------------------
70 #-----------------------------------------------------------------------------
71 # Tests
71 # Tests
72 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
73 def test_spaces():
73 def test_spaces():
74 tests = [('', 0),
74 tests = [('', 0),
75 (' ', 1),
75 (' ', 1),
76 ('\n', 0),
76 ('\n', 0),
77 (' \n', 1),
77 (' \n', 1),
78 ('x', 0),
78 ('x', 0),
79 (' x', 1),
79 (' x', 1),
80 (' x',2),
80 (' x',2),
81 (' x',4),
81 (' x',4),
82 # Note: tabs are counted as a single whitespace!
82 # Note: tabs are counted as a single whitespace!
83 ('\tx', 1),
83 ('\tx', 1),
84 ('\t x', 2),
84 ('\t x', 2),
85 ]
85 ]
86 tt.check_pairs(isp.num_ini_spaces, tests)
86 tt.check_pairs(isp.num_ini_spaces, tests)
87
87
88
88
89 def test_remove_comments():
89 def test_remove_comments():
90 tests = [('text', 'text'),
90 tests = [('text', 'text'),
91 ('text # comment', 'text '),
91 ('text # comment', 'text '),
92 ('text # comment\n', 'text \n'),
92 ('text # comment\n', 'text \n'),
93 ('text # comment \n', 'text \n'),
93 ('text # comment \n', 'text \n'),
94 ('line # c \nline\n','line \nline\n'),
94 ('line # c \nline\n','line \nline\n'),
95 ('line # c \nline#c2 \nline\nline #c\n\n',
95 ('line # c \nline#c2 \nline\nline #c\n\n',
96 'line \nline\nline\nline \n\n'),
96 'line \nline\nline\nline \n\n'),
97 ]
97 ]
98 tt.check_pairs(isp.remove_comments, tests)
98 tt.check_pairs(isp.remove_comments, tests)
99
99
100
100
101 def test_get_input_encoding():
101 def test_get_input_encoding():
102 encoding = isp.get_input_encoding()
102 encoding = isp.get_input_encoding()
103 nt.assert_true(isinstance(encoding, str))
103 nt.assert_true(isinstance(encoding, str))
104 # simple-minded check that at least encoding a simple string works with the
104 # simple-minded check that at least encoding a simple string works with the
105 # encoding we got.
105 # encoding we got.
106 nt.assert_equal(u'test'.encode(encoding), b'test')
106 nt.assert_equal(u'test'.encode(encoding), b'test')
107
107
108
108
109 class NoInputEncodingTestCase(unittest.TestCase):
109 class NoInputEncodingTestCase(unittest.TestCase):
110 def setUp(self):
110 def setUp(self):
111 self.old_stdin = sys.stdin
111 self.old_stdin = sys.stdin
112 class X: pass
112 class X: pass
113 fake_stdin = X()
113 fake_stdin = X()
114 sys.stdin = fake_stdin
114 sys.stdin = fake_stdin
115
115
116 def test(self):
116 def test(self):
117 # Verify that if sys.stdin has no 'encoding' attribute we do the right
117 # Verify that if sys.stdin has no 'encoding' attribute we do the right
118 # thing
118 # thing
119 enc = isp.get_input_encoding()
119 enc = isp.get_input_encoding()
120 self.assertEqual(enc, 'ascii')
120 self.assertEqual(enc, 'ascii')
121
121
122 def tearDown(self):
122 def tearDown(self):
123 sys.stdin = self.old_stdin
123 sys.stdin = self.old_stdin
124
124
125
125
126 class InputSplitterTestCase(unittest.TestCase):
126 class InputSplitterTestCase(unittest.TestCase):
127 def setUp(self):
127 def setUp(self):
128 self.isp = isp.InputSplitter()
128 self.isp = isp.InputSplitter()
129
129
130 def test_reset(self):
130 def test_reset(self):
131 isp = self.isp
131 isp = self.isp
132 isp.push('x=1')
132 isp.push('x=1')
133 isp.reset()
133 isp.reset()
134 self.assertEqual(isp._buffer, [])
134 self.assertEqual(isp._buffer, [])
135 self.assertEqual(isp.indent_spaces, 0)
135 self.assertEqual(isp.indent_spaces, 0)
136 self.assertEqual(isp.source, '')
136 self.assertEqual(isp.source, '')
137 self.assertEqual(isp.code, None)
137 self.assertEqual(isp.code, None)
138 self.assertEqual(isp._is_complete, False)
138 self.assertEqual(isp._is_complete, False)
139
139
140 def test_source(self):
140 def test_source(self):
141 self.isp._store('1')
141 self.isp._store('1')
142 self.isp._store('2')
142 self.isp._store('2')
143 self.assertEqual(self.isp.source, '1\n2\n')
143 self.assertEqual(self.isp.source, '1\n2\n')
144 self.assertEqual(len(self.isp._buffer)>0, True)
144 self.assertEqual(len(self.isp._buffer)>0, True)
145 self.assertEqual(self.isp.source_reset(), '1\n2\n')
145 self.assertEqual(self.isp.source_reset(), '1\n2\n')
146 self.assertEqual(self.isp._buffer, [])
146 self.assertEqual(self.isp._buffer, [])
147 self.assertEqual(self.isp.source, '')
147 self.assertEqual(self.isp.source, '')
148
148
149 def test_indent(self):
149 def test_indent(self):
150 isp = self.isp # shorthand
150 isp = self.isp # shorthand
151 isp.push('x=1')
151 isp.push('x=1')
152 self.assertEqual(isp.indent_spaces, 0)
152 self.assertEqual(isp.indent_spaces, 0)
153 isp.push('if 1:\n x=1')
153 isp.push('if 1:\n x=1')
154 self.assertEqual(isp.indent_spaces, 4)
154 self.assertEqual(isp.indent_spaces, 4)
155 isp.push('y=2\n')
155 isp.push('y=2\n')
156 self.assertEqual(isp.indent_spaces, 0)
156 self.assertEqual(isp.indent_spaces, 0)
157
157
158 def test_indent2(self):
158 def test_indent2(self):
159 isp = self.isp
159 isp = self.isp
160 isp.push('if 1:')
160 isp.push('if 1:')
161 self.assertEqual(isp.indent_spaces, 4)
161 self.assertEqual(isp.indent_spaces, 4)
162 isp.push(' x=1')
162 isp.push(' x=1')
163 self.assertEqual(isp.indent_spaces, 4)
163 self.assertEqual(isp.indent_spaces, 4)
164 # Blank lines shouldn't change the indent level
164 # Blank lines shouldn't change the indent level
165 isp.push(' '*2)
165 isp.push(' '*2)
166 self.assertEqual(isp.indent_spaces, 4)
166 self.assertEqual(isp.indent_spaces, 4)
167
167
168 def test_indent3(self):
168 def test_indent3(self):
169 isp = self.isp
169 isp = self.isp
170 # When a multiline statement contains parens or multiline strings, we
170 # When a multiline statement contains parens or multiline strings, we
171 # shouldn't get confused.
171 # shouldn't get confused.
172 isp.push("if 1:")
172 isp.push("if 1:")
173 isp.push(" x = (1+\n 2)")
173 isp.push(" x = (1+\n 2)")
174 self.assertEqual(isp.indent_spaces, 4)
174 self.assertEqual(isp.indent_spaces, 4)
175
175
176 def test_indent4(self):
176 def test_indent4(self):
177 isp = self.isp
177 isp = self.isp
178 # whitespace after ':' should not screw up indent level
178 # whitespace after ':' should not screw up indent level
179 isp.push('if 1: \n x=1')
179 isp.push('if 1: \n x=1')
180 self.assertEqual(isp.indent_spaces, 4)
180 self.assertEqual(isp.indent_spaces, 4)
181 isp.push('y=2\n')
181 isp.push('y=2\n')
182 self.assertEqual(isp.indent_spaces, 0)
182 self.assertEqual(isp.indent_spaces, 0)
183 isp.push('if 1:\t\n x=1')
183 isp.push('if 1:\t\n x=1')
184 self.assertEqual(isp.indent_spaces, 4)
184 self.assertEqual(isp.indent_spaces, 4)
185 isp.push('y=2\n')
185 isp.push('y=2\n')
186 self.assertEqual(isp.indent_spaces, 0)
186 self.assertEqual(isp.indent_spaces, 0)
187
187
188 def test_dedent_pass(self):
188 def test_dedent_pass(self):
189 isp = self.isp # shorthand
189 isp = self.isp # shorthand
190 # should NOT cause dedent
190 # should NOT cause dedent
191 isp.push('if 1:\n passes = 5')
191 isp.push('if 1:\n passes = 5')
192 self.assertEqual(isp.indent_spaces, 4)
192 self.assertEqual(isp.indent_spaces, 4)
193 isp.push('if 1:\n pass')
193 isp.push('if 1:\n pass')
194 self.assertEqual(isp.indent_spaces, 0)
194 self.assertEqual(isp.indent_spaces, 0)
195 isp.push('if 1:\n pass ')
195 isp.push('if 1:\n pass ')
196 self.assertEqual(isp.indent_spaces, 0)
196 self.assertEqual(isp.indent_spaces, 0)
197
197
198 def test_dedent_break(self):
198 def test_dedent_break(self):
199 isp = self.isp # shorthand
199 isp = self.isp # shorthand
200 # should NOT cause dedent
200 # should NOT cause dedent
201 isp.push('while 1:\n breaks = 5')
201 isp.push('while 1:\n breaks = 5')
202 self.assertEqual(isp.indent_spaces, 4)
202 self.assertEqual(isp.indent_spaces, 4)
203 isp.push('while 1:\n break')
203 isp.push('while 1:\n break')
204 self.assertEqual(isp.indent_spaces, 0)
204 self.assertEqual(isp.indent_spaces, 0)
205 isp.push('while 1:\n break ')
205 isp.push('while 1:\n break ')
206 self.assertEqual(isp.indent_spaces, 0)
206 self.assertEqual(isp.indent_spaces, 0)
207
207
208 def test_dedent_continue(self):
208 def test_dedent_continue(self):
209 isp = self.isp # shorthand
209 isp = self.isp # shorthand
210 # should NOT cause dedent
210 # should NOT cause dedent
211 isp.push('while 1:\n continues = 5')
211 isp.push('while 1:\n continues = 5')
212 self.assertEqual(isp.indent_spaces, 4)
212 self.assertEqual(isp.indent_spaces, 4)
213 isp.push('while 1:\n continue')
213 isp.push('while 1:\n continue')
214 self.assertEqual(isp.indent_spaces, 0)
214 self.assertEqual(isp.indent_spaces, 0)
215 isp.push('while 1:\n continue ')
215 isp.push('while 1:\n continue ')
216 self.assertEqual(isp.indent_spaces, 0)
216 self.assertEqual(isp.indent_spaces, 0)
217
217
218 def test_dedent_raise(self):
218 def test_dedent_raise(self):
219 isp = self.isp # shorthand
219 isp = self.isp # shorthand
220 # should NOT cause dedent
220 # should NOT cause dedent
221 isp.push('if 1:\n raised = 4')
221 isp.push('if 1:\n raised = 4')
222 self.assertEqual(isp.indent_spaces, 4)
222 self.assertEqual(isp.indent_spaces, 4)
223 isp.push('if 1:\n raise TypeError()')
223 isp.push('if 1:\n raise TypeError()')
224 self.assertEqual(isp.indent_spaces, 0)
224 self.assertEqual(isp.indent_spaces, 0)
225 isp.push('if 1:\n raise')
225 isp.push('if 1:\n raise')
226 self.assertEqual(isp.indent_spaces, 0)
226 self.assertEqual(isp.indent_spaces, 0)
227 isp.push('if 1:\n raise ')
227 isp.push('if 1:\n raise ')
228 self.assertEqual(isp.indent_spaces, 0)
228 self.assertEqual(isp.indent_spaces, 0)
229
229
230 def test_dedent_return(self):
230 def test_dedent_return(self):
231 isp = self.isp # shorthand
231 isp = self.isp # shorthand
232 # should NOT cause dedent
232 # should NOT cause dedent
233 isp.push('if 1:\n returning = 4')
233 isp.push('if 1:\n returning = 4')
234 self.assertEqual(isp.indent_spaces, 4)
234 self.assertEqual(isp.indent_spaces, 4)
235 isp.push('if 1:\n return 5 + 493')
235 isp.push('if 1:\n return 5 + 493')
236 self.assertEqual(isp.indent_spaces, 0)
236 self.assertEqual(isp.indent_spaces, 0)
237 isp.push('if 1:\n return')
237 isp.push('if 1:\n return')
238 self.assertEqual(isp.indent_spaces, 0)
238 self.assertEqual(isp.indent_spaces, 0)
239 isp.push('if 1:\n return ')
239 isp.push('if 1:\n return ')
240 self.assertEqual(isp.indent_spaces, 0)
240 self.assertEqual(isp.indent_spaces, 0)
241 isp.push('if 1:\n return(0)')
241 isp.push('if 1:\n return(0)')
242 self.assertEqual(isp.indent_spaces, 0)
242 self.assertEqual(isp.indent_spaces, 0)
243
243
244 def test_push(self):
244 def test_push(self):
245 isp = self.isp
245 isp = self.isp
246 self.assertEqual(isp.push('x=1'), True)
246 self.assertEqual(isp.push('x=1'), True)
247
247
248 def test_push2(self):
248 def test_push2(self):
249 isp = self.isp
249 isp = self.isp
250 self.assertEqual(isp.push('if 1:'), False)
250 self.assertEqual(isp.push('if 1:'), False)
251 for line in [' x=1', '# a comment', ' y=2']:
251 for line in [' x=1', '# a comment', ' y=2']:
252 print(line)
252 print(line)
253 self.assertEqual(isp.push(line), True)
253 self.assertEqual(isp.push(line), True)
254
254
255 def test_push3(self):
255 def test_push3(self):
256 isp = self.isp
256 isp = self.isp
257 isp.push('if True:')
257 isp.push('if True:')
258 isp.push(' a = 1')
258 isp.push(' a = 1')
259 self.assertEqual(isp.push('b = [1,'), False)
259 self.assertEqual(isp.push('b = [1,'), False)
260
260
261 def test_push_accepts_more(self):
261 def test_push_accepts_more(self):
262 isp = self.isp
262 isp = self.isp
263 isp.push('x=1')
263 isp.push('x=1')
264 self.assertEqual(isp.push_accepts_more(), False)
264 self.assertEqual(isp.push_accepts_more(), False)
265
265
266 def test_push_accepts_more2(self):
266 def test_push_accepts_more2(self):
267 isp = self.isp
267 isp = self.isp
268 isp.push('if 1:')
268 isp.push('if 1:')
269 self.assertEqual(isp.push_accepts_more(), True)
269 self.assertEqual(isp.push_accepts_more(), True)
270 isp.push(' x=1')
270 isp.push(' x=1')
271 self.assertEqual(isp.push_accepts_more(), True)
271 self.assertEqual(isp.push_accepts_more(), True)
272 isp.push('')
272 isp.push('')
273 self.assertEqual(isp.push_accepts_more(), False)
273 self.assertEqual(isp.push_accepts_more(), False)
274
274
275 def test_push_accepts_more3(self):
275 def test_push_accepts_more3(self):
276 isp = self.isp
276 isp = self.isp
277 isp.push("x = (2+\n3)")
277 isp.push("x = (2+\n3)")
278 self.assertEqual(isp.push_accepts_more(), False)
278 self.assertEqual(isp.push_accepts_more(), False)
279
279
280 def test_push_accepts_more4(self):
280 def test_push_accepts_more4(self):
281 isp = self.isp
281 isp = self.isp
282 # When a multiline statement contains parens or multiline strings, we
282 # When a multiline statement contains parens or multiline strings, we
283 # shouldn't get confused.
283 # shouldn't get confused.
284 # FIXME: we should be able to better handle de-dents in statements like
284 # FIXME: we should be able to better handle de-dents in statements like
285 # multiline strings and multiline expressions (continued with \ or
285 # multiline strings and multiline expressions (continued with \ or
286 # parens). Right now we aren't handling the indentation tracking quite
286 # parens). Right now we aren't handling the indentation tracking quite
287 # correctly with this, though in practice it may not be too much of a
287 # correctly with this, though in practice it may not be too much of a
288 # problem. We'll need to see.
288 # problem. We'll need to see.
289 isp.push("if 1:")
289 isp.push("if 1:")
290 isp.push(" x = (2+")
290 isp.push(" x = (2+")
291 isp.push(" 3)")
291 isp.push(" 3)")
292 self.assertEqual(isp.push_accepts_more(), True)
292 self.assertEqual(isp.push_accepts_more(), True)
293 isp.push(" y = 3")
293 isp.push(" y = 3")
294 self.assertEqual(isp.push_accepts_more(), True)
294 self.assertEqual(isp.push_accepts_more(), True)
295 isp.push('')
295 isp.push('')
296 self.assertEqual(isp.push_accepts_more(), False)
296 self.assertEqual(isp.push_accepts_more(), False)
297
297
298 def test_push_accepts_more5(self):
298 def test_push_accepts_more5(self):
299 isp = self.isp
299 isp = self.isp
300 isp.push('try:')
300 isp.push('try:')
301 isp.push(' a = 5')
301 isp.push(' a = 5')
302 isp.push('except:')
302 isp.push('except:')
303 isp.push(' raise')
303 isp.push(' raise')
304 # We want to be able to add an else: block at this point, so it should
304 # We want to be able to add an else: block at this point, so it should
305 # wait for a blank line.
305 # wait for a blank line.
306 self.assertEqual(isp.push_accepts_more(), True)
306 self.assertEqual(isp.push_accepts_more(), True)
307
307
308 def test_continuation(self):
308 def test_continuation(self):
309 isp = self.isp
309 isp = self.isp
310 isp.push("import os, \\")
310 isp.push("import os, \\")
311 self.assertEqual(isp.push_accepts_more(), True)
311 self.assertEqual(isp.push_accepts_more(), True)
312 isp.push("sys")
312 isp.push("sys")
313 self.assertEqual(isp.push_accepts_more(), False)
313 self.assertEqual(isp.push_accepts_more(), False)
314
314
315 def test_syntax_error(self):
315 def test_syntax_error(self):
316 isp = self.isp
316 isp = self.isp
317 # Syntax errors immediately produce a 'ready' block, so the invalid
317 # Syntax errors immediately produce a 'ready' block, so the invalid
318 # Python can be sent to the kernel for evaluation with possible ipython
318 # Python can be sent to the kernel for evaluation with possible ipython
319 # special-syntax conversion.
319 # special-syntax conversion.
320 isp.push('run foo')
320 isp.push('run foo')
321 self.assertEqual(isp.push_accepts_more(), False)
321 self.assertEqual(isp.push_accepts_more(), False)
322
322
323 def test_unicode(self):
323 def test_unicode(self):
324 self.isp.push(u"Pérez")
324 self.isp.push(u"Pérez")
325 self.isp.push(u'\xc3\xa9')
325 self.isp.push(u'\xc3\xa9')
326 self.isp.push(u"u'\xc3\xa9'")
326 self.isp.push(u"u'\xc3\xa9'")
327
327
328 def test_line_continuation(self):
328 def test_line_continuation(self):
329 """ Test issue #2108."""
329 """ Test issue #2108."""
330 isp = self.isp
330 isp = self.isp
331 # A blank line after a line continuation should not accept more
331 # A blank line after a line continuation should not accept more
332 isp.push("1 \\\n\n")
332 isp.push("1 \\\n\n")
333 self.assertEqual(isp.push_accepts_more(), False)
333 self.assertEqual(isp.push_accepts_more(), False)
334 # Whitespace after a \ is a SyntaxError. The only way to test that
334 # Whitespace after a \ is a SyntaxError. The only way to test that
335 # here is to test that push doesn't accept more (as with
335 # here is to test that push doesn't accept more (as with
336 # test_syntax_error() above).
336 # test_syntax_error() above).
337 isp.push(r"1 \ ")
337 isp.push(r"1 \ ")
338 self.assertEqual(isp.push_accepts_more(), False)
338 self.assertEqual(isp.push_accepts_more(), False)
339 # Even if the line is continuable (c.f. the regular Python
339 # Even if the line is continuable (c.f. the regular Python
340 # interpreter)
340 # interpreter)
341 isp.push(r"(1 \ ")
341 isp.push(r"(1 \ ")
342 self.assertEqual(isp.push_accepts_more(), False)
342 self.assertEqual(isp.push_accepts_more(), False)
343
343
344 def test_check_complete(self):
344 def test_check_complete(self):
345 isp = self.isp
345 isp = self.isp
346 self.assertEqual(isp.check_complete("a = 1"), ('complete', None))
346 self.assertEqual(isp.check_complete("a = 1"), ('complete', None))
347 self.assertEqual(isp.check_complete("for a in range(5):"), ('incomplete', 4))
347 self.assertEqual(isp.check_complete("for a in range(5):"), ('incomplete', 4))
348 self.assertEqual(isp.check_complete("raise = 2"), ('invalid', None))
348 self.assertEqual(isp.check_complete("raise = 2"), ('invalid', None))
349 self.assertEqual(isp.check_complete("a = [1,\n2,"), ('incomplete', 0))
349 self.assertEqual(isp.check_complete("a = [1,\n2,"), ('incomplete', 0))
350 self.assertEqual(isp.check_complete("def a():\n x=1\n global x"), ('invalid', None))
350 self.assertEqual(isp.check_complete("def a():\n x=1\n global x"), ('invalid', None))
351
351
352 class InteractiveLoopTestCase(unittest.TestCase):
352 class InteractiveLoopTestCase(unittest.TestCase):
353 """Tests for an interactive loop like a python shell.
353 """Tests for an interactive loop like a python shell.
354 """
354 """
355 def check_ns(self, lines, ns):
355 def check_ns(self, lines, ns):
356 """Validate that the given input lines produce the resulting namespace.
356 """Validate that the given input lines produce the resulting namespace.
357
357
358 Note: the input lines are given exactly as they would be typed in an
358 Note: the input lines are given exactly as they would be typed in an
359 auto-indenting environment, as mini_interactive_loop above already does
359 auto-indenting environment, as mini_interactive_loop above already does
360 auto-indenting and prepends spaces to the input.
360 auto-indenting and prepends spaces to the input.
361 """
361 """
362 src = mini_interactive_loop(pseudo_input(lines))
362 src = mini_interactive_loop(pseudo_input(lines))
363 test_ns = {}
363 test_ns = {}
364 exec(src, test_ns)
364 exec(src, test_ns)
365 # We can't check that the provided ns is identical to the test_ns,
365 # We can't check that the provided ns is identical to the test_ns,
366 # because Python fills test_ns with extra keys (copyright, etc). But
366 # because Python fills test_ns with extra keys (copyright, etc). But
367 # we can check that the given dict is *contained* in test_ns
367 # we can check that the given dict is *contained* in test_ns
368 for k,v in ns.items():
368 for k,v in ns.items():
369 self.assertEqual(test_ns[k], v)
369 self.assertEqual(test_ns[k], v)
370
370
371 def test_simple(self):
371 def test_simple(self):
372 self.check_ns(['x=1'], dict(x=1))
372 self.check_ns(['x=1'], dict(x=1))
373
373
374 def test_simple2(self):
374 def test_simple2(self):
375 self.check_ns(['if 1:', 'x=2'], dict(x=2))
375 self.check_ns(['if 1:', 'x=2'], dict(x=2))
376
376
377 def test_xy(self):
377 def test_xy(self):
378 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
378 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
379
379
380 def test_abc(self):
380 def test_abc(self):
381 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
381 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
382
382
383 def test_multi(self):
383 def test_multi(self):
384 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
384 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
385
385
386
386
387 class IPythonInputTestCase(InputSplitterTestCase):
387 class IPythonInputTestCase(InputSplitterTestCase):
388 """By just creating a new class whose .isp is a different instance, we
388 """By just creating a new class whose .isp is a different instance, we
389 re-run the same test battery on the new input splitter.
389 re-run the same test battery on the new input splitter.
390
390
391 In addition, this runs the tests over the syntax and syntax_ml dicts that
391 In addition, this runs the tests over the syntax and syntax_ml dicts that
392 were tested by individual functions, as part of the OO interface.
392 were tested by individual functions, as part of the OO interface.
393
393
394 It also makes some checks on the raw buffer storage.
394 It also makes some checks on the raw buffer storage.
395 """
395 """
396
396
397 def setUp(self):
397 def setUp(self):
398 self.isp = isp.IPythonInputSplitter()
398 self.isp = isp.IPythonInputSplitter()
399
399
400 def test_syntax(self):
400 def test_syntax(self):
401 """Call all single-line syntax tests from the main object"""
401 """Call all single-line syntax tests from the main object"""
402 isp = self.isp
402 isp = self.isp
403 for example in syntax.values():
403 for example in syntax.values():
404 for raw, out_t in example:
404 for raw, out_t in example:
405 if raw.startswith(' '):
405 if raw.startswith(' '):
406 continue
406 continue
407
407
408 isp.push(raw+'\n')
408 isp.push(raw+'\n')
409 out_raw = isp.source_raw
409 out_raw = isp.source_raw
410 out = isp.source_reset()
410 out = isp.source_reset()
411 self.assertEqual(out.rstrip(), out_t,
411 self.assertEqual(out.rstrip(), out_t,
412 tt.pair_fail_msg.format("inputsplitter",raw, out_t, out))
412 tt.pair_fail_msg.format("inputsplitter",raw, out_t, out))
413 self.assertEqual(out_raw.rstrip(), raw.rstrip())
413 self.assertEqual(out_raw.rstrip(), raw.rstrip())
414
414
415 def test_syntax_multiline(self):
415 def test_syntax_multiline(self):
416 isp = self.isp
416 isp = self.isp
417 for example in syntax_ml.values():
417 for example in syntax_ml.values():
418 for line_pairs in example:
418 for line_pairs in example:
419 out_t_parts = []
419 out_t_parts = []
420 raw_parts = []
420 raw_parts = []
421 for lraw, out_t_part in line_pairs:
421 for lraw, out_t_part in line_pairs:
422 if out_t_part is not None:
422 if out_t_part is not None:
423 out_t_parts.append(out_t_part)
423 out_t_parts.append(out_t_part)
424
424
425 if lraw is not None:
425 if lraw is not None:
426 isp.push(lraw)
426 isp.push(lraw)
427 raw_parts.append(lraw)
427 raw_parts.append(lraw)
428
428
429 out_raw = isp.source_raw
429 out_raw = isp.source_raw
430 out = isp.source_reset()
430 out = isp.source_reset()
431 out_t = '\n'.join(out_t_parts).rstrip()
431 out_t = '\n'.join(out_t_parts).rstrip()
432 raw = '\n'.join(raw_parts).rstrip()
432 raw = '\n'.join(raw_parts).rstrip()
433 self.assertEqual(out.rstrip(), out_t)
433 self.assertEqual(out.rstrip(), out_t)
434 self.assertEqual(out_raw.rstrip(), raw)
434 self.assertEqual(out_raw.rstrip(), raw)
435
435
436 def test_syntax_multiline_cell(self):
436 def test_syntax_multiline_cell(self):
437 isp = self.isp
437 isp = self.isp
438 for example in syntax_ml.values():
438 for example in syntax_ml.values():
439
439
440 out_t_parts = []
440 out_t_parts = []
441 for line_pairs in example:
441 for line_pairs in example:
442 raw = '\n'.join(r for r, _ in line_pairs if r is not None)
442 raw = '\n'.join(r for r, _ in line_pairs if r is not None)
443 out_t = '\n'.join(t for _,t in line_pairs if t is not None)
443 out_t = '\n'.join(t for _,t in line_pairs if t is not None)
444 out = isp.transform_cell(raw)
444 out = isp.transform_cell(raw)
445 # Match ignoring trailing whitespace
445 # Match ignoring trailing whitespace
446 self.assertEqual(out.rstrip(), out_t.rstrip())
446 self.assertEqual(out.rstrip(), out_t.rstrip())
447
447
448 def test_cellmagic_preempt(self):
448 def test_cellmagic_preempt(self):
449 isp = self.isp
449 isp = self.isp
450 for raw, name, line, cell in [
450 for raw, name, line, cell in [
451 ("%%cellm a\nIn[1]:", u'cellm', u'a', u'In[1]:'),
451 ("%%cellm a\nIn[1]:", u'cellm', u'a', u'In[1]:'),
452 ("%%cellm \nline\n>>> hi", u'cellm', u'', u'line\n>>> hi'),
452 ("%%cellm \nline\n>>> hi", u'cellm', u'', u'line\n>>> hi'),
453 (">>> %%cellm \nline\n>>> hi", u'cellm', u'', u'line\nhi'),
453 (">>> %%cellm \nline\n>>> hi", u'cellm', u'', u'line\nhi'),
454 ("%%cellm \n>>> hi", u'cellm', u'', u'>>> hi'),
454 ("%%cellm \n>>> hi", u'cellm', u'', u'>>> hi'),
455 ("%%cellm \nline1\nline2", u'cellm', u'', u'line1\nline2'),
455 ("%%cellm \nline1\nline2", u'cellm', u'', u'line1\nline2'),
456 ("%%cellm \nline1\\\\\nline2", u'cellm', u'', u'line1\\\\\nline2'),
456 ("%%cellm \nline1\\\\\nline2", u'cellm', u'', u'line1\\\\\nline2'),
457 ]:
457 ]:
458 expected = "get_ipython().run_cell_magic(%r, %r, %r)" % (
458 expected = "get_ipython().run_cell_magic(%r, %r, %r)" % (
459 name, line, cell
459 name, line, cell
460 )
460 )
461 out = isp.transform_cell(raw)
461 out = isp.transform_cell(raw)
462 self.assertEqual(out.rstrip(), expected.rstrip())
462 self.assertEqual(out.rstrip(), expected.rstrip())
463
463
464 def test_multiline_passthrough(self):
464 def test_multiline_passthrough(self):
465 isp = self.isp
465 isp = self.isp
466 class CommentTransformer(InputTransformer):
466 class CommentTransformer(InputTransformer):
467 def __init__(self):
467 def __init__(self):
468 self._lines = []
468 self._lines = []
469
469
470 def push(self, line):
470 def push(self, line):
471 self._lines.append(line + '#')
471 self._lines.append(line + '#')
472
472
473 def reset(self):
473 def reset(self):
474 text = '\n'.join(self._lines)
474 text = '\n'.join(self._lines)
475 self._lines = []
475 self._lines = []
476 return text
476 return text
477
477
478 isp.physical_line_transforms.insert(0, CommentTransformer())
478 isp.physical_line_transforms.insert(0, CommentTransformer())
479
479
480 for raw, expected in [
480 for raw, expected in [
481 ("a=5", "a=5#"),
481 ("a=5", "a=5#"),
482 ("%ls foo", "get_ipython().magic(%r)" % u'ls foo#'),
482 ("%ls foo", "get_ipython().run_line_magic(%r, %r)" % (u'ls', u'foo#')),
483 ("!ls foo\n%ls bar", "get_ipython().system(%r)\nget_ipython().magic(%r)" % (
483 ("!ls foo\n%ls bar", "get_ipython().system(%r)\nget_ipython().run_line_magic(%r, %r)" % (
484 u'ls foo#', u'ls bar#'
484 u'ls foo#', u'ls', u'bar#'
485 )),
485 )),
486 ("1\n2\n3\n%ls foo\n4\n5", "1#\n2#\n3#\nget_ipython().magic(%r)\n4#\n5#" % u'ls foo#'),
486 ("1\n2\n3\n%ls foo\n4\n5", "1#\n2#\n3#\nget_ipython().run_line_magic(%r, %r)\n4#\n5#" % (u'ls', u'foo#')),
487 ]:
487 ]:
488 out = isp.transform_cell(raw)
488 out = isp.transform_cell(raw)
489 self.assertEqual(out.rstrip(), expected.rstrip())
489 self.assertEqual(out.rstrip(), expected.rstrip())
490
490
491 #-----------------------------------------------------------------------------
491 #-----------------------------------------------------------------------------
492 # Main - use as a script, mostly for developer experiments
492 # Main - use as a script, mostly for developer experiments
493 #-----------------------------------------------------------------------------
493 #-----------------------------------------------------------------------------
494
494
495 if __name__ == '__main__':
495 if __name__ == '__main__':
496 # A simple demo for interactive experimentation. This code will not get
496 # A simple demo for interactive experimentation. This code will not get
497 # picked up by any test suite.
497 # picked up by any test suite.
498 from IPython.core.inputsplitter import IPythonInputSplitter
498 from IPython.core.inputsplitter import IPythonInputSplitter
499
499
500 # configure here the syntax to use, prompt and whether to autoindent
500 # configure here the syntax to use, prompt and whether to autoindent
501 #isp, start_prompt = InputSplitter(), '>>> '
501 #isp, start_prompt = InputSplitter(), '>>> '
502 isp, start_prompt = IPythonInputSplitter(), 'In> '
502 isp, start_prompt = IPythonInputSplitter(), 'In> '
503
503
504 autoindent = True
504 autoindent = True
505 #autoindent = False
505 #autoindent = False
506
506
507 try:
507 try:
508 while True:
508 while True:
509 prompt = start_prompt
509 prompt = start_prompt
510 while isp.push_accepts_more():
510 while isp.push_accepts_more():
511 indent = ' '*isp.indent_spaces
511 indent = ' '*isp.indent_spaces
512 if autoindent:
512 if autoindent:
513 line = indent + input(prompt+indent)
513 line = indent + input(prompt+indent)
514 else:
514 else:
515 line = input(prompt)
515 line = input(prompt)
516 isp.push(line)
516 isp.push(line)
517 prompt = '... '
517 prompt = '... '
518
518
519 # Here we just return input so we can use it in a test suite, but a
519 # Here we just return input so we can use it in a test suite, but a
520 # real interpreter would instead send it for execution somewhere.
520 # real interpreter would instead send it for execution somewhere.
521 #src = isp.source; raise EOFError # dbg
521 #src = isp.source; raise EOFError # dbg
522 raw = isp.source_raw
522 raw = isp.source_raw
523 src = isp.source_reset()
523 src = isp.source_reset()
524 print('Input source was:\n', src)
524 print('Input source was:\n', src)
525 print('Raw source was:\n', raw)
525 print('Raw source was:\n', raw)
526 except EOFError:
526 except EOFError:
527 print('Bye')
527 print('Bye')
528
528
529 # Tests for cell magics support
529 # Tests for cell magics support
530
530
531 def test_last_blank():
531 def test_last_blank():
532 nt.assert_false(isp.last_blank(''))
532 nt.assert_false(isp.last_blank(''))
533 nt.assert_false(isp.last_blank('abc'))
533 nt.assert_false(isp.last_blank('abc'))
534 nt.assert_false(isp.last_blank('abc\n'))
534 nt.assert_false(isp.last_blank('abc\n'))
535 nt.assert_false(isp.last_blank('abc\na'))
535 nt.assert_false(isp.last_blank('abc\na'))
536
536
537 nt.assert_true(isp.last_blank('\n'))
537 nt.assert_true(isp.last_blank('\n'))
538 nt.assert_true(isp.last_blank('\n '))
538 nt.assert_true(isp.last_blank('\n '))
539 nt.assert_true(isp.last_blank('abc\n '))
539 nt.assert_true(isp.last_blank('abc\n '))
540 nt.assert_true(isp.last_blank('abc\n\n'))
540 nt.assert_true(isp.last_blank('abc\n\n'))
541 nt.assert_true(isp.last_blank('abc\nd\n\n'))
541 nt.assert_true(isp.last_blank('abc\nd\n\n'))
542 nt.assert_true(isp.last_blank('abc\nd\ne\n\n'))
542 nt.assert_true(isp.last_blank('abc\nd\ne\n\n'))
543 nt.assert_true(isp.last_blank('abc \n \n \n\n'))
543 nt.assert_true(isp.last_blank('abc \n \n \n\n'))
544
544
545
545
546 def test_last_two_blanks():
546 def test_last_two_blanks():
547 nt.assert_false(isp.last_two_blanks(''))
547 nt.assert_false(isp.last_two_blanks(''))
548 nt.assert_false(isp.last_two_blanks('abc'))
548 nt.assert_false(isp.last_two_blanks('abc'))
549 nt.assert_false(isp.last_two_blanks('abc\n'))
549 nt.assert_false(isp.last_two_blanks('abc\n'))
550 nt.assert_false(isp.last_two_blanks('abc\n\na'))
550 nt.assert_false(isp.last_two_blanks('abc\n\na'))
551 nt.assert_false(isp.last_two_blanks('abc\n \n'))
551 nt.assert_false(isp.last_two_blanks('abc\n \n'))
552 nt.assert_false(isp.last_two_blanks('abc\n\n'))
552 nt.assert_false(isp.last_two_blanks('abc\n\n'))
553
553
554 nt.assert_true(isp.last_two_blanks('\n\n'))
554 nt.assert_true(isp.last_two_blanks('\n\n'))
555 nt.assert_true(isp.last_two_blanks('\n\n '))
555 nt.assert_true(isp.last_two_blanks('\n\n '))
556 nt.assert_true(isp.last_two_blanks('\n \n'))
556 nt.assert_true(isp.last_two_blanks('\n \n'))
557 nt.assert_true(isp.last_two_blanks('abc\n\n '))
557 nt.assert_true(isp.last_two_blanks('abc\n\n '))
558 nt.assert_true(isp.last_two_blanks('abc\n\n\n'))
558 nt.assert_true(isp.last_two_blanks('abc\n\n\n'))
559 nt.assert_true(isp.last_two_blanks('abc\n\n \n'))
559 nt.assert_true(isp.last_two_blanks('abc\n\n \n'))
560 nt.assert_true(isp.last_two_blanks('abc\n\n \n '))
560 nt.assert_true(isp.last_two_blanks('abc\n\n \n '))
561 nt.assert_true(isp.last_two_blanks('abc\n\n \n \n'))
561 nt.assert_true(isp.last_two_blanks('abc\n\n \n \n'))
562 nt.assert_true(isp.last_two_blanks('abc\nd\n\n\n'))
562 nt.assert_true(isp.last_two_blanks('abc\nd\n\n\n'))
563 nt.assert_true(isp.last_two_blanks('abc\nd\ne\nf\n\n\n'))
563 nt.assert_true(isp.last_two_blanks('abc\nd\ne\nf\n\n\n'))
564
564
565
565
566 class CellMagicsCommon(object):
566 class CellMagicsCommon(object):
567
567
568 def test_whole_cell(self):
568 def test_whole_cell(self):
569 src = "%%cellm line\nbody\n"
569 src = "%%cellm line\nbody\n"
570 out = self.sp.transform_cell(src)
570 out = self.sp.transform_cell(src)
571 ref = u"get_ipython().run_cell_magic({u}'cellm', {u}'line', {u}'body')\n"
571 ref = u"get_ipython().run_cell_magic('cellm', 'line', 'body')\n"
572 nt.assert_equal(out, py3compat.u_format(ref))
572 nt.assert_equal(out, py3compat.u_format(ref))
573
573
574 def test_cellmagic_help(self):
574 def test_cellmagic_help(self):
575 self.sp.push('%%cellm?')
575 self.sp.push('%%cellm?')
576 nt.assert_false(self.sp.push_accepts_more())
576 nt.assert_false(self.sp.push_accepts_more())
577
577
578 def tearDown(self):
578 def tearDown(self):
579 self.sp.reset()
579 self.sp.reset()
580
580
581
581
582 class CellModeCellMagics(CellMagicsCommon, unittest.TestCase):
582 class CellModeCellMagics(CellMagicsCommon, unittest.TestCase):
583 sp = isp.IPythonInputSplitter(line_input_checker=False)
583 sp = isp.IPythonInputSplitter(line_input_checker=False)
584
584
585 def test_incremental(self):
585 def test_incremental(self):
586 sp = self.sp
586 sp = self.sp
587 sp.push('%%cellm firstline\n')
587 sp.push('%%cellm firstline\n')
588 nt.assert_true(sp.push_accepts_more()) #1
588 nt.assert_true(sp.push_accepts_more()) #1
589 sp.push('line2\n')
589 sp.push('line2\n')
590 nt.assert_true(sp.push_accepts_more()) #2
590 nt.assert_true(sp.push_accepts_more()) #2
591 sp.push('\n')
591 sp.push('\n')
592 # This should accept a blank line and carry on until the cell is reset
592 # This should accept a blank line and carry on until the cell is reset
593 nt.assert_true(sp.push_accepts_more()) #3
593 nt.assert_true(sp.push_accepts_more()) #3
594
594
595 def test_no_strip_coding(self):
595 def test_no_strip_coding(self):
596 src = '\n'.join([
596 src = '\n'.join([
597 '%%writefile foo.py',
597 '%%writefile foo.py',
598 '# coding: utf-8',
598 '# coding: utf-8',
599 'print(u"üñîçø∂é")',
599 'print(u"üñîçø∂é")',
600 ])
600 ])
601 out = self.sp.transform_cell(src)
601 out = self.sp.transform_cell(src)
602 nt.assert_in('# coding: utf-8', out)
602 nt.assert_in('# coding: utf-8', out)
603
603
604
604
605 class LineModeCellMagics(CellMagicsCommon, unittest.TestCase):
605 class LineModeCellMagics(CellMagicsCommon, unittest.TestCase):
606 sp = isp.IPythonInputSplitter(line_input_checker=True)
606 sp = isp.IPythonInputSplitter(line_input_checker=True)
607
607
608 def test_incremental(self):
608 def test_incremental(self):
609 sp = self.sp
609 sp = self.sp
610 sp.push('%%cellm line2\n')
610 sp.push('%%cellm line2\n')
611 nt.assert_true(sp.push_accepts_more()) #1
611 nt.assert_true(sp.push_accepts_more()) #1
612 sp.push('\n')
612 sp.push('\n')
613 # In this case, a blank line should end the cell magic
613 # In this case, a blank line should end the cell magic
614 nt.assert_false(sp.push_accepts_more()) #2
614 nt.assert_false(sp.push_accepts_more()) #2
615
615
616 indentation_samples = [
616 indentation_samples = [
617 ('a = 1', 0),
617 ('a = 1', 0),
618 ('for a in b:', 4),
618 ('for a in b:', 4),
619 ('def f():', 4),
619 ('def f():', 4),
620 ('def f(): #comment', 4),
620 ('def f(): #comment', 4),
621 ('a = ":#not a comment"', 0),
621 ('a = ":#not a comment"', 0),
622 ('def f():\n a = 1', 4),
622 ('def f():\n a = 1', 4),
623 ('def f():\n return 1', 0),
623 ('def f():\n return 1', 0),
624 ('for a in b:\n'
624 ('for a in b:\n'
625 ' if a < 0:'
625 ' if a < 0:'
626 ' continue', 3),
626 ' continue', 3),
627 ('a = {', 4),
627 ('a = {', 4),
628 ('a = {\n'
628 ('a = {\n'
629 ' 1,', 5),
629 ' 1,', 5),
630 ('b = """123', 0),
630 ('b = """123', 0),
631 ('', 0),
631 ('', 0),
632 ('def f():\n pass', 0),
632 ('def f():\n pass', 0),
633 ('class Bar:\n def f():\n pass', 4),
633 ('class Bar:\n def f():\n pass', 4),
634 ('class Bar:\n def f():\n raise', 4),
634 ('class Bar:\n def f():\n raise', 4),
635 ]
635 ]
636
636
637 def test_find_next_indent():
637 def test_find_next_indent():
638 for code, exp in indentation_samples:
638 for code, exp in indentation_samples:
639 res = isp.find_next_indent(code)
639 res = isp.find_next_indent(code)
640 msg = "{!r} != {!r} (expected)\n Code: {!r}".format(res, exp, code)
640 msg = "{!r} != {!r} (expected)\n Code: {!r}".format(res, exp, code)
641 assert res == exp, msg
641 assert res == exp, msg
@@ -1,494 +1,494 b''
1 import tokenize
1 import tokenize
2 import nose.tools as nt
2 import nose.tools as nt
3
3
4 from IPython.testing import tools as tt
4 from IPython.testing import tools as tt
5 from IPython.utils import py3compat
5 from IPython.utils import py3compat
6 u_fmt = py3compat.u_format
6 u_fmt = py3compat.u_format
7
7
8 from IPython.core import inputtransformer as ipt
8 from IPython.core import inputtransformer as ipt
9
9
10 def transform_and_reset(transformer):
10 def transform_and_reset(transformer):
11 transformer = transformer()
11 transformer = transformer()
12 def transform(inp):
12 def transform(inp):
13 try:
13 try:
14 return transformer.push(inp)
14 return transformer.push(inp)
15 finally:
15 finally:
16 transformer.reset()
16 transformer.reset()
17
17
18 return transform
18 return transform
19
19
20 # Transformer tests
20 # Transformer tests
21 def transform_checker(tests, transformer, **kwargs):
21 def transform_checker(tests, transformer, **kwargs):
22 """Utility to loop over test inputs"""
22 """Utility to loop over test inputs"""
23 transformer = transformer(**kwargs)
23 transformer = transformer(**kwargs)
24 try:
24 try:
25 for inp, tr in tests:
25 for inp, tr in tests:
26 if inp is None:
26 if inp is None:
27 out = transformer.reset()
27 out = transformer.reset()
28 else:
28 else:
29 out = transformer.push(inp)
29 out = transformer.push(inp)
30 nt.assert_equal(out, tr)
30 nt.assert_equal(out, tr)
31 finally:
31 finally:
32 transformer.reset()
32 transformer.reset()
33
33
34 # Data for all the syntax tests in the form of lists of pairs of
34 # Data for all the syntax tests in the form of lists of pairs of
35 # raw/transformed input. We store it here as a global dict so that we can use
35 # raw/transformed input. We store it here as a global dict so that we can use
36 # it both within single-function tests and also to validate the behavior of the
36 # it both within single-function tests and also to validate the behavior of the
37 # larger objects
37 # larger objects
38
38
39 syntax = \
39 syntax = \
40 dict(assign_system =
40 dict(assign_system =
41 [(i,py3compat.u_format(o)) for i,o in \
41 [(i,py3compat.u_format(o)) for i,o in \
42 [(u'a =! ls', "a = get_ipython().getoutput({u}'ls')"),
42 [(u'a =! ls', "a = get_ipython().getoutput('ls')"),
43 (u'b = !ls', "b = get_ipython().getoutput({u}'ls')"),
43 (u'b = !ls', "b = get_ipython().getoutput('ls')"),
44 (u'c= !ls', "c = get_ipython().getoutput({u}'ls')"),
44 (u'c= !ls', "c = get_ipython().getoutput('ls')"),
45 (u'd == !ls', u'd == !ls'), # Invalid syntax, but we leave == alone.
45 (u'd == !ls', u'd == !ls'), # Invalid syntax, but we leave == alone.
46 ('x=1', 'x=1'), # normal input is unmodified
46 ('x=1', 'x=1'), # normal input is unmodified
47 (' ',' '), # blank lines are kept intact
47 (' ',' '), # blank lines are kept intact
48 # Tuple unpacking
48 # Tuple unpacking
49 (u"a, b = !echo 'a\\nb'", u"a, b = get_ipython().getoutput({u}\"echo 'a\\\\nb'\")"),
49 (u"a, b = !echo 'a\\nb'", u"a, b = get_ipython().getoutput(\"echo 'a\\\\nb'\")"),
50 (u"a,= !echo 'a'", u"a, = get_ipython().getoutput({u}\"echo 'a'\")"),
50 (u"a,= !echo 'a'", u"a, = get_ipython().getoutput(\"echo 'a'\")"),
51 (u"a, *bc = !echo 'a\\nb\\nc'", u"a, *bc = get_ipython().getoutput({u}\"echo 'a\\\\nb\\\\nc'\")"),
51 (u"a, *bc = !echo 'a\\nb\\nc'", u"a, *bc = get_ipython().getoutput(\"echo 'a\\\\nb\\\\nc'\")"),
52 # Tuple unpacking with regular Python expressions, not our syntax.
52 # Tuple unpacking with regular Python expressions, not our syntax.
53 (u"a, b = range(2)", u"a, b = range(2)"),
53 (u"a, b = range(2)", u"a, b = range(2)"),
54 (u"a, = range(1)", u"a, = range(1)"),
54 (u"a, = range(1)", u"a, = range(1)"),
55 (u"a, *bc = range(3)", u"a, *bc = range(3)"),
55 (u"a, *bc = range(3)", u"a, *bc = range(3)"),
56 ]],
56 ]],
57
57
58 assign_magic =
58 assign_magic =
59 [(i,py3compat.u_format(o)) for i,o in \
59 [(i,py3compat.u_format(o)) for i,o in \
60 [(u'a =% who', "a = get_ipython().magic({u}'who')"),
60 [(u'a =% who', "a = get_ipython().run_line_magic('who', '')"),
61 (u'b = %who', "b = get_ipython().magic({u}'who')"),
61 (u'b = %who', "b = get_ipython().run_line_magic('who', '')"),
62 (u'c= %ls', "c = get_ipython().magic({u}'ls')"),
62 (u'c= %ls', "c = get_ipython().run_line_magic('ls', '')"),
63 (u'd == %ls', u'd == %ls'), # Invalid syntax, but we leave == alone.
63 (u'd == %ls', u'd == %ls'), # Invalid syntax, but we leave == alone.
64 ('x=1', 'x=1'), # normal input is unmodified
64 ('x=1', 'x=1'), # normal input is unmodified
65 (' ',' '), # blank lines are kept intact
65 (' ',' '), # blank lines are kept intact
66 (u"a, b = %foo", u"a, b = get_ipython().magic({u}'foo')"),
66 (u"a, b = %foo", u"a, b = get_ipython().run_line_magic('foo', '')"),
67 ]],
67 ]],
68
68
69 classic_prompt =
69 classic_prompt =
70 [('>>> x=1', 'x=1'),
70 [('>>> x=1', 'x=1'),
71 ('x=1', 'x=1'), # normal input is unmodified
71 ('x=1', 'x=1'), # normal input is unmodified
72 (' ', ' '), # blank lines are kept intact
72 (' ', ' '), # blank lines are kept intact
73 ],
73 ],
74
74
75 ipy_prompt =
75 ipy_prompt =
76 [('In [1]: x=1', 'x=1'),
76 [('In [1]: x=1', 'x=1'),
77 ('x=1', 'x=1'), # normal input is unmodified
77 ('x=1', 'x=1'), # normal input is unmodified
78 (' ',' '), # blank lines are kept intact
78 (' ',' '), # blank lines are kept intact
79 ],
79 ],
80
80
81 # Tests for the escape transformer to leave normal code alone
81 # Tests for the escape transformer to leave normal code alone
82 escaped_noesc =
82 escaped_noesc =
83 [ (' ', ' '),
83 [ (' ', ' '),
84 ('x=1', 'x=1'),
84 ('x=1', 'x=1'),
85 ],
85 ],
86
86
87 # System calls
87 # System calls
88 escaped_shell =
88 escaped_shell =
89 [(i,py3compat.u_format(o)) for i,o in \
89 [(i,py3compat.u_format(o)) for i,o in \
90 [ (u'!ls', "get_ipython().system({u}'ls')"),
90 [ (u'!ls', "get_ipython().system('ls')"),
91 # Double-escape shell, this means to capture the output of the
91 # Double-escape shell, this means to capture the output of the
92 # subprocess and return it
92 # subprocess and return it
93 (u'!!ls', "get_ipython().getoutput({u}'ls')"),
93 (u'!!ls', "get_ipython().getoutput('ls')"),
94 ]],
94 ]],
95
95
96 # Help/object info
96 # Help/object info
97 escaped_help =
97 escaped_help =
98 [(i,py3compat.u_format(o)) for i,o in \
98 [(i,py3compat.u_format(o)) for i,o in \
99 [ (u'?', 'get_ipython().show_usage()'),
99 [ (u'?', 'get_ipython().show_usage()'),
100 (u'?x1', "get_ipython().magic({u}'pinfo x1')"),
100 (u'?x1', "get_ipython().run_line_magic('pinfo', 'x1')"),
101 (u'??x2', "get_ipython().magic({u}'pinfo2 x2')"),
101 (u'??x2', "get_ipython().run_line_magic('pinfo2', 'x2')"),
102 (u'?a.*s', "get_ipython().magic({u}'psearch a.*s')"),
102 (u'?a.*s', "get_ipython().run_line_magic('psearch', 'a.*s')"),
103 (u'?%hist1', "get_ipython().magic({u}'pinfo %hist1')"),
103 (u'?%hist1', "get_ipython().run_line_magic('pinfo', '%hist1')"),
104 (u'?%%hist2', "get_ipython().magic({u}'pinfo %%hist2')"),
104 (u'?%%hist2', "get_ipython().run_line_magic('pinfo', '%%hist2')"),
105 (u'?abc = qwe', "get_ipython().magic({u}'pinfo abc')"),
105 (u'?abc = qwe', "get_ipython().run_line_magic('pinfo', 'abc')"),
106 ]],
106 ]],
107
107
108 end_help =
108 end_help =
109 [(i,py3compat.u_format(o)) for i,o in \
109 [(i,py3compat.u_format(o)) for i,o in \
110 [ (u'x3?', "get_ipython().magic({u}'pinfo x3')"),
110 [ (u'x3?', "get_ipython().run_line_magic('pinfo', 'x3')"),
111 (u'x4??', "get_ipython().magic({u}'pinfo2 x4')"),
111 (u'x4??', "get_ipython().run_line_magic('pinfo2', 'x4')"),
112 (u'%hist1?', "get_ipython().magic({u}'pinfo %hist1')"),
112 (u'%hist1?', "get_ipython().run_line_magic('pinfo', '%hist1')"),
113 (u'%hist2??', "get_ipython().magic({u}'pinfo2 %hist2')"),
113 (u'%hist2??', "get_ipython().run_line_magic('pinfo2', '%hist2')"),
114 (u'%%hist3?', "get_ipython().magic({u}'pinfo %%hist3')"),
114 (u'%%hist3?', "get_ipython().run_line_magic('pinfo', '%%hist3')"),
115 (u'%%hist4??', "get_ipython().magic({u}'pinfo2 %%hist4')"),
115 (u'%%hist4??', "get_ipython().run_line_magic('pinfo2', '%%hist4')"),
116 (u'f*?', "get_ipython().magic({u}'psearch f*')"),
116 (u'f*?', "get_ipython().run_line_magic('psearch', 'f*')"),
117 (u'ax.*aspe*?', "get_ipython().magic({u}'psearch ax.*aspe*')"),
117 (u'ax.*aspe*?', "get_ipython().run_line_magic('psearch', 'ax.*aspe*')"),
118 (u'a = abc?', "get_ipython().set_next_input({u}'a = abc');"
118 (u'a = abc?', "get_ipython().set_next_input('a = abc');"
119 "get_ipython().magic({u}'pinfo abc')"),
119 "get_ipython().run_line_magic('pinfo', 'abc')"),
120 (u'a = abc.qe??', "get_ipython().set_next_input({u}'a = abc.qe');"
120 (u'a = abc.qe??', "get_ipython().set_next_input('a = abc.qe');"
121 "get_ipython().magic({u}'pinfo2 abc.qe')"),
121 "get_ipython().run_line_magic('pinfo2', 'abc.qe')"),
122 (u'a = *.items?', "get_ipython().set_next_input({u}'a = *.items');"
122 (u'a = *.items?', "get_ipython().set_next_input('a = *.items');"
123 "get_ipython().magic({u}'psearch *.items')"),
123 "get_ipython().run_line_magic('psearch', '*.items')"),
124 (u'plot(a?', "get_ipython().set_next_input({u}'plot(a');"
124 (u'plot(a?', "get_ipython().set_next_input('plot(a');"
125 "get_ipython().magic({u}'pinfo a')"),
125 "get_ipython().run_line_magic('pinfo', 'a')"),
126 (u'a*2 #comment?', 'a*2 #comment?'),
126 (u'a*2 #comment?', 'a*2 #comment?'),
127 ]],
127 ]],
128
128
129 # Explicit magic calls
129 # Explicit magic calls
130 escaped_magic =
130 escaped_magic =
131 [(i,py3compat.u_format(o)) for i,o in \
131 [(i,py3compat.u_format(o)) for i,o in \
132 [ (u'%cd', "get_ipython().magic({u}'cd')"),
132 [ (u'%cd', "get_ipython().run_line_magic('cd', '')"),
133 (u'%cd /home', "get_ipython().magic({u}'cd /home')"),
133 (u'%cd /home', "get_ipython().run_line_magic('cd', '/home')"),
134 # Backslashes need to be escaped.
134 # Backslashes need to be escaped.
135 (u'%cd C:\\User', "get_ipython().magic({u}'cd C:\\\\User')"),
135 (u'%cd C:\\User', "get_ipython().run_line_magic('cd', 'C:\\\\User')"),
136 (u' %magic', " get_ipython().magic({u}'magic')"),
136 (u' %magic', " get_ipython().run_line_magic('magic', '')"),
137 ]],
137 ]],
138
138
139 # Quoting with separate arguments
139 # Quoting with separate arguments
140 escaped_quote =
140 escaped_quote =
141 [ (',f', 'f("")'),
141 [ (',f', 'f("")'),
142 (',f x', 'f("x")'),
142 (',f x', 'f("x")'),
143 (' ,f y', ' f("y")'),
143 (' ,f y', ' f("y")'),
144 (',f a b', 'f("a", "b")'),
144 (',f a b', 'f("a", "b")'),
145 ],
145 ],
146
146
147 # Quoting with single argument
147 # Quoting with single argument
148 escaped_quote2 =
148 escaped_quote2 =
149 [ (';f', 'f("")'),
149 [ (';f', 'f("")'),
150 (';f x', 'f("x")'),
150 (';f x', 'f("x")'),
151 (' ;f y', ' f("y")'),
151 (' ;f y', ' f("y")'),
152 (';f a b', 'f("a b")'),
152 (';f a b', 'f("a b")'),
153 ],
153 ],
154
154
155 # Simply apply parens
155 # Simply apply parens
156 escaped_paren =
156 escaped_paren =
157 [ ('/f', 'f()'),
157 [ ('/f', 'f()'),
158 ('/f x', 'f(x)'),
158 ('/f x', 'f(x)'),
159 (' /f y', ' f(y)'),
159 (' /f y', ' f(y)'),
160 ('/f a b', 'f(a, b)'),
160 ('/f a b', 'f(a, b)'),
161 ],
161 ],
162
162
163 # Check that we transform prompts before other transforms
163 # Check that we transform prompts before other transforms
164 mixed =
164 mixed =
165 [(i,py3compat.u_format(o)) for i,o in \
165 [(i,py3compat.u_format(o)) for i,o in \
166 [ (u'In [1]: %lsmagic', "get_ipython().magic({u}'lsmagic')"),
166 [ (u'In [1]: %lsmagic', "get_ipython().run_line_magic('lsmagic', '')"),
167 (u'>>> %lsmagic', "get_ipython().magic({u}'lsmagic')"),
167 (u'>>> %lsmagic', "get_ipython().run_line_magic('lsmagic', '')"),
168 (u'In [2]: !ls', "get_ipython().system({u}'ls')"),
168 (u'In [2]: !ls', "get_ipython().system('ls')"),
169 (u'In [3]: abs?', "get_ipython().magic({u}'pinfo abs')"),
169 (u'In [3]: abs?', "get_ipython().run_line_magic('pinfo', 'abs')"),
170 (u'In [4]: b = %who', "b = get_ipython().magic({u}'who')"),
170 (u'In [4]: b = %who', "b = get_ipython().run_line_magic('who', '')"),
171 ]],
171 ]],
172 )
172 )
173
173
174 # multiline syntax examples. Each of these should be a list of lists, with
174 # multiline syntax examples. Each of these should be a list of lists, with
175 # each entry itself having pairs of raw/transformed input. The union (with
175 # each entry itself having pairs of raw/transformed input. The union (with
176 # '\n'.join() of the transformed inputs is what the splitter should produce
176 # '\n'.join() of the transformed inputs is what the splitter should produce
177 # when fed the raw lines one at a time via push.
177 # when fed the raw lines one at a time via push.
178 syntax_ml = \
178 syntax_ml = \
179 dict(classic_prompt =
179 dict(classic_prompt =
180 [ [('>>> for i in range(10):','for i in range(10):'),
180 [ [('>>> for i in range(10):','for i in range(10):'),
181 ('... print i',' print i'),
181 ('... print i',' print i'),
182 ('... ', ''),
182 ('... ', ''),
183 ],
183 ],
184 [('>>> a="""','a="""'),
184 [('>>> a="""','a="""'),
185 ('... 123"""','123"""'),
185 ('... 123"""','123"""'),
186 ],
186 ],
187 [('a="""','a="""'),
187 [('a="""','a="""'),
188 ('... 123','123'),
188 ('... 123','123'),
189 ('... 456"""','456"""'),
189 ('... 456"""','456"""'),
190 ],
190 ],
191 [('a="""','a="""'),
191 [('a="""','a="""'),
192 ('>>> 123','123'),
192 ('>>> 123','123'),
193 ('... 456"""','456"""'),
193 ('... 456"""','456"""'),
194 ],
194 ],
195 [('a="""','a="""'),
195 [('a="""','a="""'),
196 ('123','123'),
196 ('123','123'),
197 ('... 456"""','... 456"""'),
197 ('... 456"""','... 456"""'),
198 ],
198 ],
199 [('....__class__','....__class__'),
199 [('....__class__','....__class__'),
200 ],
200 ],
201 [('a=5', 'a=5'),
201 [('a=5', 'a=5'),
202 ('...', ''),
202 ('...', ''),
203 ],
203 ],
204 [('>>> def f(x):', 'def f(x):'),
204 [('>>> def f(x):', 'def f(x):'),
205 ('...', ''),
205 ('...', ''),
206 ('... return x', ' return x'),
206 ('... return x', ' return x'),
207 ],
207 ],
208 [('board = """....', 'board = """....'),
208 [('board = """....', 'board = """....'),
209 ('....', '....'),
209 ('....', '....'),
210 ('...."""', '...."""'),
210 ('...."""', '...."""'),
211 ],
211 ],
212 ],
212 ],
213
213
214 ipy_prompt =
214 ipy_prompt =
215 [ [('In [24]: for i in range(10):','for i in range(10):'),
215 [ [('In [24]: for i in range(10):','for i in range(10):'),
216 (' ....: print i',' print i'),
216 (' ....: print i',' print i'),
217 (' ....: ', ''),
217 (' ....: ', ''),
218 ],
218 ],
219 [('In [24]: for i in range(10):','for i in range(10):'),
219 [('In [24]: for i in range(10):','for i in range(10):'),
220 # Qt console prompts expand with spaces, not dots
220 # Qt console prompts expand with spaces, not dots
221 (' ...: print i',' print i'),
221 (' ...: print i',' print i'),
222 (' ...: ', ''),
222 (' ...: ', ''),
223 ],
223 ],
224 [('In [24]: for i in range(10):','for i in range(10):'),
224 [('In [24]: for i in range(10):','for i in range(10):'),
225 # Sometimes whitespace preceding '...' has been removed
225 # Sometimes whitespace preceding '...' has been removed
226 ('...: print i',' print i'),
226 ('...: print i',' print i'),
227 ('...: ', ''),
227 ('...: ', ''),
228 ],
228 ],
229 [('In [24]: for i in range(10):','for i in range(10):'),
229 [('In [24]: for i in range(10):','for i in range(10):'),
230 # Space after last continuation prompt has been removed (issue #6674)
230 # Space after last continuation prompt has been removed (issue #6674)
231 ('...: print i',' print i'),
231 ('...: print i',' print i'),
232 ('...:', ''),
232 ('...:', ''),
233 ],
233 ],
234 [('In [2]: a="""','a="""'),
234 [('In [2]: a="""','a="""'),
235 (' ...: 123"""','123"""'),
235 (' ...: 123"""','123"""'),
236 ],
236 ],
237 [('a="""','a="""'),
237 [('a="""','a="""'),
238 (' ...: 123','123'),
238 (' ...: 123','123'),
239 (' ...: 456"""','456"""'),
239 (' ...: 456"""','456"""'),
240 ],
240 ],
241 [('a="""','a="""'),
241 [('a="""','a="""'),
242 ('In [1]: 123','123'),
242 ('In [1]: 123','123'),
243 (' ...: 456"""','456"""'),
243 (' ...: 456"""','456"""'),
244 ],
244 ],
245 [('a="""','a="""'),
245 [('a="""','a="""'),
246 ('123','123'),
246 ('123','123'),
247 (' ...: 456"""',' ...: 456"""'),
247 (' ...: 456"""',' ...: 456"""'),
248 ],
248 ],
249 ],
249 ],
250
250
251 multiline_datastructure_prompt =
251 multiline_datastructure_prompt =
252 [ [('>>> a = [1,','a = [1,'),
252 [ [('>>> a = [1,','a = [1,'),
253 ('... 2]','2]'),
253 ('... 2]','2]'),
254 ],
254 ],
255 ],
255 ],
256
256
257 multiline_datastructure =
257 multiline_datastructure =
258 [ [('b = ("%s"', None),
258 [ [('b = ("%s"', None),
259 ('# comment', None),
259 ('# comment', None),
260 ('%foo )', 'b = ("%s"\n# comment\n%foo )'),
260 ('%foo )', 'b = ("%s"\n# comment\n%foo )'),
261 ],
261 ],
262 ],
262 ],
263
263
264 multiline_string =
264 multiline_string =
265 [ [("'''foo?", None),
265 [ [("'''foo?", None),
266 ("bar'''", "'''foo?\nbar'''"),
266 ("bar'''", "'''foo?\nbar'''"),
267 ],
267 ],
268 ],
268 ],
269
269
270 leading_indent =
270 leading_indent =
271 [ [(' print "hi"','print "hi"'),
271 [ [(' print "hi"','print "hi"'),
272 ],
272 ],
273 [(' for a in range(5):','for a in range(5):'),
273 [(' for a in range(5):','for a in range(5):'),
274 (' a*2',' a*2'),
274 (' a*2',' a*2'),
275 ],
275 ],
276 [(' a="""','a="""'),
276 [(' a="""','a="""'),
277 (' 123"""','123"""'),
277 (' 123"""','123"""'),
278 ],
278 ],
279 [('a="""','a="""'),
279 [('a="""','a="""'),
280 (' 123"""',' 123"""'),
280 (' 123"""',' 123"""'),
281 ],
281 ],
282 ],
282 ],
283
283
284 cellmagic =
284 cellmagic =
285 [ [(u'%%foo a', None),
285 [ [(u'%%foo a', None),
286 (None, u_fmt("get_ipython().run_cell_magic({u}'foo', {u}'a', {u}'')")),
286 (None, u_fmt("get_ipython().run_cell_magic('foo', 'a', '')")),
287 ],
287 ],
288 [(u'%%bar 123', None),
288 [(u'%%bar 123', None),
289 (u'hello', None),
289 (u'hello', None),
290 (None , u_fmt("get_ipython().run_cell_magic({u}'bar', {u}'123', {u}'hello')")),
290 (None , u_fmt("get_ipython().run_cell_magic('bar', '123', 'hello')")),
291 ],
291 ],
292 [(u'a=5', 'a=5'),
292 [(u'a=5', 'a=5'),
293 (u'%%cellmagic', '%%cellmagic'),
293 (u'%%cellmagic', '%%cellmagic'),
294 ],
294 ],
295 ],
295 ],
296
296
297 escaped =
297 escaped =
298 [ [('%abc def \\', None),
298 [ [('%abc def \\', None),
299 ('ghi', u_fmt("get_ipython().magic({u}'abc def ghi')")),
299 ('ghi', u_fmt("get_ipython().run_line_magic('abc', 'def ghi')")),
300 ],
300 ],
301 [('%abc def \\', None),
301 [('%abc def \\', None),
302 ('ghi\\', None),
302 ('ghi\\', None),
303 (None, u_fmt("get_ipython().magic({u}'abc def ghi')")),
303 (None, u_fmt("get_ipython().run_line_magic('abc', 'def ghi')")),
304 ],
304 ],
305 ],
305 ],
306
306
307 assign_magic =
307 assign_magic =
308 [ [(u'a = %bc de \\', None),
308 [ [(u'a = %bc de \\', None),
309 (u'fg', u_fmt("a = get_ipython().magic({u}'bc de fg')")),
309 (u'fg', u_fmt("a = get_ipython().run_line_magic('bc', 'de fg')")),
310 ],
310 ],
311 [(u'a = %bc de \\', None),
311 [(u'a = %bc de \\', None),
312 (u'fg\\', None),
312 (u'fg\\', None),
313 (None, u_fmt("a = get_ipython().magic({u}'bc de fg')")),
313 (None, u_fmt("a = get_ipython().run_line_magic('bc', 'de fg')")),
314 ],
314 ],
315 ],
315 ],
316
316
317 assign_system =
317 assign_system =
318 [ [(u'a = !bc de \\', None),
318 [ [(u'a = !bc de \\', None),
319 (u'fg', u_fmt("a = get_ipython().getoutput({u}'bc de fg')")),
319 (u'fg', u_fmt("a = get_ipython().getoutput('bc de fg')")),
320 ],
320 ],
321 [(u'a = !bc de \\', None),
321 [(u'a = !bc de \\', None),
322 (u'fg\\', None),
322 (u'fg\\', None),
323 (None, u_fmt("a = get_ipython().getoutput({u}'bc de fg')")),
323 (None, u_fmt("a = get_ipython().getoutput('bc de fg')")),
324 ],
324 ],
325 ],
325 ],
326 )
326 )
327
327
328
328
329 def test_assign_system():
329 def test_assign_system():
330 tt.check_pairs(transform_and_reset(ipt.assign_from_system), syntax['assign_system'])
330 tt.check_pairs(transform_and_reset(ipt.assign_from_system), syntax['assign_system'])
331
331
332 def test_assign_magic():
332 def test_assign_magic():
333 tt.check_pairs(transform_and_reset(ipt.assign_from_magic), syntax['assign_magic'])
333 tt.check_pairs(transform_and_reset(ipt.assign_from_magic), syntax['assign_magic'])
334
334
335 def test_classic_prompt():
335 def test_classic_prompt():
336 tt.check_pairs(transform_and_reset(ipt.classic_prompt), syntax['classic_prompt'])
336 tt.check_pairs(transform_and_reset(ipt.classic_prompt), syntax['classic_prompt'])
337 for example in syntax_ml['classic_prompt']:
337 for example in syntax_ml['classic_prompt']:
338 transform_checker(example, ipt.classic_prompt)
338 transform_checker(example, ipt.classic_prompt)
339 for example in syntax_ml['multiline_datastructure_prompt']:
339 for example in syntax_ml['multiline_datastructure_prompt']:
340 transform_checker(example, ipt.classic_prompt)
340 transform_checker(example, ipt.classic_prompt)
341
341
342 # Check that we don't transform the second line if the first is obviously
342 # Check that we don't transform the second line if the first is obviously
343 # IPython syntax
343 # IPython syntax
344 transform_checker([
344 transform_checker([
345 (u'%foo', '%foo'),
345 (u'%foo', '%foo'),
346 (u'>>> bar', '>>> bar'),
346 (u'>>> bar', '>>> bar'),
347 ], ipt.classic_prompt)
347 ], ipt.classic_prompt)
348
348
349
349
350 def test_ipy_prompt():
350 def test_ipy_prompt():
351 tt.check_pairs(transform_and_reset(ipt.ipy_prompt), syntax['ipy_prompt'])
351 tt.check_pairs(transform_and_reset(ipt.ipy_prompt), syntax['ipy_prompt'])
352 for example in syntax_ml['ipy_prompt']:
352 for example in syntax_ml['ipy_prompt']:
353 transform_checker(example, ipt.ipy_prompt)
353 transform_checker(example, ipt.ipy_prompt)
354
354
355 # Check that we don't transform the second line if we're inside a cell magic
355 # Check that we don't transform the second line if we're inside a cell magic
356 transform_checker([
356 transform_checker([
357 (u'%%foo', '%%foo'),
357 (u'%%foo', '%%foo'),
358 (u'In [1]: bar', 'In [1]: bar'),
358 (u'In [1]: bar', 'In [1]: bar'),
359 ], ipt.ipy_prompt)
359 ], ipt.ipy_prompt)
360
360
361 def test_assemble_logical_lines():
361 def test_assemble_logical_lines():
362 tests = \
362 tests = \
363 [ [(u"a = \\", None),
363 [ [(u"a = \\", None),
364 (u"123", u"a = 123"),
364 (u"123", u"a = 123"),
365 ],
365 ],
366 [(u"a = \\", None), # Test resetting when within a multi-line string
366 [(u"a = \\", None), # Test resetting when within a multi-line string
367 (u"12 *\\", None),
367 (u"12 *\\", None),
368 (None, u"a = 12 *"),
368 (None, u"a = 12 *"),
369 ],
369 ],
370 [(u"# foo\\", u"# foo\\"), # Comments can't be continued like this
370 [(u"# foo\\", u"# foo\\"), # Comments can't be continued like this
371 ],
371 ],
372 ]
372 ]
373 for example in tests:
373 for example in tests:
374 transform_checker(example, ipt.assemble_logical_lines)
374 transform_checker(example, ipt.assemble_logical_lines)
375
375
376 def test_assemble_python_lines():
376 def test_assemble_python_lines():
377 tests = \
377 tests = \
378 [ [(u"a = '''", None),
378 [ [(u"a = '''", None),
379 (u"abc'''", u"a = '''\nabc'''"),
379 (u"abc'''", u"a = '''\nabc'''"),
380 ],
380 ],
381 [(u"a = '''", None), # Test resetting when within a multi-line string
381 [(u"a = '''", None), # Test resetting when within a multi-line string
382 (u"def", None),
382 (u"def", None),
383 (None, u"a = '''\ndef"),
383 (None, u"a = '''\ndef"),
384 ],
384 ],
385 [(u"a = [1,", None),
385 [(u"a = [1,", None),
386 (u"2]", u"a = [1,\n2]"),
386 (u"2]", u"a = [1,\n2]"),
387 ],
387 ],
388 [(u"a = [1,", None), # Test resetting when within a multi-line string
388 [(u"a = [1,", None), # Test resetting when within a multi-line string
389 (u"2,", None),
389 (u"2,", None),
390 (None, u"a = [1,\n2,"),
390 (None, u"a = [1,\n2,"),
391 ],
391 ],
392 [(u"a = '''", None), # Test line continuation within a multi-line string
392 [(u"a = '''", None), # Test line continuation within a multi-line string
393 (u"abc\\", None),
393 (u"abc\\", None),
394 (u"def", None),
394 (u"def", None),
395 (u"'''", u"a = '''\nabc\\\ndef\n'''"),
395 (u"'''", u"a = '''\nabc\\\ndef\n'''"),
396 ],
396 ],
397 ] + syntax_ml['multiline_datastructure']
397 ] + syntax_ml['multiline_datastructure']
398 for example in tests:
398 for example in tests:
399 transform_checker(example, ipt.assemble_python_lines)
399 transform_checker(example, ipt.assemble_python_lines)
400
400
401
401
402 def test_help_end():
402 def test_help_end():
403 tt.check_pairs(transform_and_reset(ipt.help_end), syntax['end_help'])
403 tt.check_pairs(transform_and_reset(ipt.help_end), syntax['end_help'])
404
404
405 def test_escaped_noesc():
405 def test_escaped_noesc():
406 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_noesc'])
406 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_noesc'])
407
407
408
408
409 def test_escaped_shell():
409 def test_escaped_shell():
410 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_shell'])
410 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_shell'])
411
411
412
412
413 def test_escaped_help():
413 def test_escaped_help():
414 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_help'])
414 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_help'])
415
415
416
416
417 def test_escaped_magic():
417 def test_escaped_magic():
418 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_magic'])
418 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_magic'])
419
419
420
420
421 def test_escaped_quote():
421 def test_escaped_quote():
422 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote'])
422 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote'])
423
423
424
424
425 def test_escaped_quote2():
425 def test_escaped_quote2():
426 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote2'])
426 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote2'])
427
427
428
428
429 def test_escaped_paren():
429 def test_escaped_paren():
430 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_paren'])
430 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_paren'])
431
431
432
432
433 def test_cellmagic():
433 def test_cellmagic():
434 for example in syntax_ml['cellmagic']:
434 for example in syntax_ml['cellmagic']:
435 transform_checker(example, ipt.cellmagic)
435 transform_checker(example, ipt.cellmagic)
436
436
437 line_example = [(u'%%bar 123', None),
437 line_example = [(u'%%bar 123', None),
438 (u'hello', None),
438 (u'hello', None),
439 (u'' , u_fmt("get_ipython().run_cell_magic({u}'bar', {u}'123', {u}'hello')")),
439 (u'' , u_fmt("get_ipython().run_cell_magic('bar', '123', 'hello')")),
440 ]
440 ]
441 transform_checker(line_example, ipt.cellmagic, end_on_blank_line=True)
441 transform_checker(line_example, ipt.cellmagic, end_on_blank_line=True)
442
442
443 def test_has_comment():
443 def test_has_comment():
444 tests = [('text', False),
444 tests = [('text', False),
445 ('text #comment', True),
445 ('text #comment', True),
446 ('text #comment\n', True),
446 ('text #comment\n', True),
447 ('#comment', True),
447 ('#comment', True),
448 ('#comment\n', True),
448 ('#comment\n', True),
449 ('a = "#string"', False),
449 ('a = "#string"', False),
450 ('a = "#string" # comment', True),
450 ('a = "#string" # comment', True),
451 ('a #comment not "string"', True),
451 ('a #comment not "string"', True),
452 ]
452 ]
453 tt.check_pairs(ipt.has_comment, tests)
453 tt.check_pairs(ipt.has_comment, tests)
454
454
455 @ipt.TokenInputTransformer.wrap
455 @ipt.TokenInputTransformer.wrap
456 def decistmt(tokens):
456 def decistmt(tokens):
457 """Substitute Decimals for floats in a string of statements.
457 """Substitute Decimals for floats in a string of statements.
458
458
459 Based on an example from the tokenize module docs.
459 Based on an example from the tokenize module docs.
460 """
460 """
461 result = []
461 result = []
462 for toknum, tokval, _, _, _ in tokens:
462 for toknum, tokval, _, _, _ in tokens:
463 if toknum == tokenize.NUMBER and '.' in tokval: # replace NUMBER tokens
463 if toknum == tokenize.NUMBER and '.' in tokval: # replace NUMBER tokens
464 for newtok in [
464 for newtok in [
465 (tokenize.NAME, 'Decimal'),
465 (tokenize.NAME, 'Decimal'),
466 (tokenize.OP, '('),
466 (tokenize.OP, '('),
467 (tokenize.STRING, repr(tokval)),
467 (tokenize.STRING, repr(tokval)),
468 (tokenize.OP, ')')
468 (tokenize.OP, ')')
469 ]:
469 ]:
470 yield newtok
470 yield newtok
471 else:
471 else:
472 yield (toknum, tokval)
472 yield (toknum, tokval)
473
473
474
474
475
475
476 def test_token_input_transformer():
476 def test_token_input_transformer():
477 tests = [(u'1.2', u_fmt(u"Decimal ({u}'1.2')")),
477 tests = [(u'1.2', u_fmt(u"Decimal ('1.2')")),
478 (u'"1.2"', u'"1.2"'),
478 (u'"1.2"', u'"1.2"'),
479 ]
479 ]
480 tt.check_pairs(transform_and_reset(decistmt), tests)
480 tt.check_pairs(transform_and_reset(decistmt), tests)
481 ml_tests = \
481 ml_tests = \
482 [ [(u"a = 1.2; b = '''x", None),
482 [ [(u"a = 1.2; b = '''x", None),
483 (u"y'''", u_fmt(u"a =Decimal ({u}'1.2');b ='''x\ny'''")),
483 (u"y'''", u_fmt(u"a =Decimal ('1.2');b ='''x\ny'''")),
484 ],
484 ],
485 [(u"a = [1.2,", None),
485 [(u"a = [1.2,", None),
486 (u"3]", u_fmt(u"a =[Decimal ({u}'1.2'),\n3 ]")),
486 (u"3]", u_fmt(u"a =[Decimal ('1.2'),\n3 ]")),
487 ],
487 ],
488 [(u"a = '''foo", None), # Test resetting when within a multi-line string
488 [(u"a = '''foo", None), # Test resetting when within a multi-line string
489 (u"bar", None),
489 (u"bar", None),
490 (None, u"a = '''foo\nbar"),
490 (None, u"a = '''foo\nbar"),
491 ],
491 ],
492 ]
492 ]
493 for example in ml_tests:
493 for example in ml_tests:
494 transform_checker(example, decistmt)
494 transform_checker(example, decistmt)
@@ -1,1044 +1,1044 b''
1 # -*- coding: utf-8 -*-
1 # -*- coding: utf-8 -*-
2 """Tests for various magic functions.
2 """Tests for various magic functions.
3
3
4 Needs to be run by nose (to make ipython session available).
4 Needs to be run by nose (to make ipython session available).
5 """
5 """
6
6
7 import io
7 import io
8 import os
8 import os
9 import re
9 import re
10 import sys
10 import sys
11 import warnings
11 import warnings
12 from unittest import TestCase
12 from unittest import TestCase
13 from importlib import invalidate_caches
13 from importlib import invalidate_caches
14 from io import StringIO
14 from io import StringIO
15
15
16 import nose.tools as nt
16 import nose.tools as nt
17
17
18 import shlex
18 import shlex
19
19
20 from IPython import get_ipython
20 from IPython import get_ipython
21 from IPython.core import magic
21 from IPython.core import magic
22 from IPython.core.error import UsageError
22 from IPython.core.error import UsageError
23 from IPython.core.magic import (Magics, magics_class, line_magic,
23 from IPython.core.magic import (Magics, magics_class, line_magic,
24 cell_magic,
24 cell_magic,
25 register_line_magic, register_cell_magic)
25 register_line_magic, register_cell_magic)
26 from IPython.core.magics import execution, script, code, logging
26 from IPython.core.magics import execution, script, code, logging
27 from IPython.testing import decorators as dec
27 from IPython.testing import decorators as dec
28 from IPython.testing import tools as tt
28 from IPython.testing import tools as tt
29 from IPython.utils import py3compat
29 from IPython.utils import py3compat
30 from IPython.utils.io import capture_output
30 from IPython.utils.io import capture_output
31 from IPython.utils.tempdir import TemporaryDirectory
31 from IPython.utils.tempdir import TemporaryDirectory
32 from IPython.utils.process import find_cmd
32 from IPython.utils.process import find_cmd
33
33
34
34
35
35
36 _ip = get_ipython()
36 _ip = get_ipython()
37
37
38 @magic.magics_class
38 @magic.magics_class
39 class DummyMagics(magic.Magics): pass
39 class DummyMagics(magic.Magics): pass
40
40
41 def test_extract_code_ranges():
41 def test_extract_code_ranges():
42 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
42 instr = "1 3 5-6 7-9 10:15 17: :10 10- -13 :"
43 expected = [(0, 1),
43 expected = [(0, 1),
44 (2, 3),
44 (2, 3),
45 (4, 6),
45 (4, 6),
46 (6, 9),
46 (6, 9),
47 (9, 14),
47 (9, 14),
48 (16, None),
48 (16, None),
49 (None, 9),
49 (None, 9),
50 (9, None),
50 (9, None),
51 (None, 13),
51 (None, 13),
52 (None, None)]
52 (None, None)]
53 actual = list(code.extract_code_ranges(instr))
53 actual = list(code.extract_code_ranges(instr))
54 nt.assert_equal(actual, expected)
54 nt.assert_equal(actual, expected)
55
55
56 def test_extract_symbols():
56 def test_extract_symbols():
57 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
57 source = """import foo\na = 10\ndef b():\n return 42\n\n\nclass A: pass\n\n\n"""
58 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
58 symbols_args = ["a", "b", "A", "A,b", "A,a", "z"]
59 expected = [([], ['a']),
59 expected = [([], ['a']),
60 (["def b():\n return 42\n"], []),
60 (["def b():\n return 42\n"], []),
61 (["class A: pass\n"], []),
61 (["class A: pass\n"], []),
62 (["class A: pass\n", "def b():\n return 42\n"], []),
62 (["class A: pass\n", "def b():\n return 42\n"], []),
63 (["class A: pass\n"], ['a']),
63 (["class A: pass\n"], ['a']),
64 ([], ['z'])]
64 ([], ['z'])]
65 for symbols, exp in zip(symbols_args, expected):
65 for symbols, exp in zip(symbols_args, expected):
66 nt.assert_equal(code.extract_symbols(source, symbols), exp)
66 nt.assert_equal(code.extract_symbols(source, symbols), exp)
67
67
68
68
69 def test_extract_symbols_raises_exception_with_non_python_code():
69 def test_extract_symbols_raises_exception_with_non_python_code():
70 source = ("=begin A Ruby program :)=end\n"
70 source = ("=begin A Ruby program :)=end\n"
71 "def hello\n"
71 "def hello\n"
72 "puts 'Hello world'\n"
72 "puts 'Hello world'\n"
73 "end")
73 "end")
74 with nt.assert_raises(SyntaxError):
74 with nt.assert_raises(SyntaxError):
75 code.extract_symbols(source, "hello")
75 code.extract_symbols(source, "hello")
76
76
77 def test_config():
77 def test_config():
78 """ test that config magic does not raise
78 """ test that config magic does not raise
79 can happen if Configurable init is moved too early into
79 can happen if Configurable init is moved too early into
80 Magics.__init__ as then a Config object will be registerd as a
80 Magics.__init__ as then a Config object will be registerd as a
81 magic.
81 magic.
82 """
82 """
83 ## should not raise.
83 ## should not raise.
84 _ip.magic('config')
84 _ip.magic('config')
85
85
86 def test_config_available_configs():
86 def test_config_available_configs():
87 """ test that config magic prints available configs in unique and
87 """ test that config magic prints available configs in unique and
88 sorted order. """
88 sorted order. """
89 with capture_output() as captured:
89 with capture_output() as captured:
90 _ip.magic('config')
90 _ip.magic('config')
91
91
92 stdout = captured.stdout
92 stdout = captured.stdout
93 config_classes = stdout.strip().split('\n')[1:]
93 config_classes = stdout.strip().split('\n')[1:]
94 nt.assert_list_equal(config_classes, sorted(set(config_classes)))
94 nt.assert_list_equal(config_classes, sorted(set(config_classes)))
95
95
96 def test_config_print_class():
96 def test_config_print_class():
97 """ test that config with a classname prints the class's options. """
97 """ test that config with a classname prints the class's options. """
98 with capture_output() as captured:
98 with capture_output() as captured:
99 _ip.magic('config TerminalInteractiveShell')
99 _ip.magic('config TerminalInteractiveShell')
100
100
101 stdout = captured.stdout
101 stdout = captured.stdout
102 if not re.match("TerminalInteractiveShell.* options", stdout.splitlines()[0]):
102 if not re.match("TerminalInteractiveShell.* options", stdout.splitlines()[0]):
103 print(stdout)
103 print(stdout)
104 raise AssertionError("1st line of stdout not like "
104 raise AssertionError("1st line of stdout not like "
105 "'TerminalInteractiveShell.* options'")
105 "'TerminalInteractiveShell.* options'")
106
106
107 def test_rehashx():
107 def test_rehashx():
108 # clear up everything
108 # clear up everything
109 _ip.alias_manager.clear_aliases()
109 _ip.alias_manager.clear_aliases()
110 del _ip.db['syscmdlist']
110 del _ip.db['syscmdlist']
111
111
112 _ip.magic('rehashx')
112 _ip.magic('rehashx')
113 # Practically ALL ipython development systems will have more than 10 aliases
113 # Practically ALL ipython development systems will have more than 10 aliases
114
114
115 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
115 nt.assert_true(len(_ip.alias_manager.aliases) > 10)
116 for name, cmd in _ip.alias_manager.aliases:
116 for name, cmd in _ip.alias_manager.aliases:
117 # we must strip dots from alias names
117 # we must strip dots from alias names
118 nt.assert_not_in('.', name)
118 nt.assert_not_in('.', name)
119
119
120 # rehashx must fill up syscmdlist
120 # rehashx must fill up syscmdlist
121 scoms = _ip.db['syscmdlist']
121 scoms = _ip.db['syscmdlist']
122 nt.assert_true(len(scoms) > 10)
122 nt.assert_true(len(scoms) > 10)
123
123
124
124
125 def test_magic_parse_options():
125 def test_magic_parse_options():
126 """Test that we don't mangle paths when parsing magic options."""
126 """Test that we don't mangle paths when parsing magic options."""
127 ip = get_ipython()
127 ip = get_ipython()
128 path = 'c:\\x'
128 path = 'c:\\x'
129 m = DummyMagics(ip)
129 m = DummyMagics(ip)
130 opts = m.parse_options('-f %s' % path,'f:')[0]
130 opts = m.parse_options('-f %s' % path,'f:')[0]
131 # argv splitting is os-dependent
131 # argv splitting is os-dependent
132 if os.name == 'posix':
132 if os.name == 'posix':
133 expected = 'c:x'
133 expected = 'c:x'
134 else:
134 else:
135 expected = path
135 expected = path
136 nt.assert_equal(opts['f'], expected)
136 nt.assert_equal(opts['f'], expected)
137
137
138 def test_magic_parse_long_options():
138 def test_magic_parse_long_options():
139 """Magic.parse_options can handle --foo=bar long options"""
139 """Magic.parse_options can handle --foo=bar long options"""
140 ip = get_ipython()
140 ip = get_ipython()
141 m = DummyMagics(ip)
141 m = DummyMagics(ip)
142 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
142 opts, _ = m.parse_options('--foo --bar=bubble', 'a', 'foo', 'bar=')
143 nt.assert_in('foo', opts)
143 nt.assert_in('foo', opts)
144 nt.assert_in('bar', opts)
144 nt.assert_in('bar', opts)
145 nt.assert_equal(opts['bar'], "bubble")
145 nt.assert_equal(opts['bar'], "bubble")
146
146
147
147
148 @dec.skip_without('sqlite3')
148 @dec.skip_without('sqlite3')
149 def doctest_hist_f():
149 def doctest_hist_f():
150 """Test %hist -f with temporary filename.
150 """Test %hist -f with temporary filename.
151
151
152 In [9]: import tempfile
152 In [9]: import tempfile
153
153
154 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
154 In [10]: tfile = tempfile.mktemp('.py','tmp-ipython-')
155
155
156 In [11]: %hist -nl -f $tfile 3
156 In [11]: %hist -nl -f $tfile 3
157
157
158 In [13]: import os; os.unlink(tfile)
158 In [13]: import os; os.unlink(tfile)
159 """
159 """
160
160
161
161
162 @dec.skip_without('sqlite3')
162 @dec.skip_without('sqlite3')
163 def doctest_hist_r():
163 def doctest_hist_r():
164 """Test %hist -r
164 """Test %hist -r
165
165
166 XXX - This test is not recording the output correctly. For some reason, in
166 XXX - This test is not recording the output correctly. For some reason, in
167 testing mode the raw history isn't getting populated. No idea why.
167 testing mode the raw history isn't getting populated. No idea why.
168 Disabling the output checking for now, though at least we do run it.
168 Disabling the output checking for now, though at least we do run it.
169
169
170 In [1]: 'hist' in _ip.lsmagic()
170 In [1]: 'hist' in _ip.lsmagic()
171 Out[1]: True
171 Out[1]: True
172
172
173 In [2]: x=1
173 In [2]: x=1
174
174
175 In [3]: %hist -rl 2
175 In [3]: %hist -rl 2
176 x=1 # random
176 x=1 # random
177 %hist -r 2
177 %hist -r 2
178 """
178 """
179
179
180
180
181 @dec.skip_without('sqlite3')
181 @dec.skip_without('sqlite3')
182 def doctest_hist_op():
182 def doctest_hist_op():
183 """Test %hist -op
183 """Test %hist -op
184
184
185 In [1]: class b(float):
185 In [1]: class b(float):
186 ...: pass
186 ...: pass
187 ...:
187 ...:
188
188
189 In [2]: class s(object):
189 In [2]: class s(object):
190 ...: def __str__(self):
190 ...: def __str__(self):
191 ...: return 's'
191 ...: return 's'
192 ...:
192 ...:
193
193
194 In [3]:
194 In [3]:
195
195
196 In [4]: class r(b):
196 In [4]: class r(b):
197 ...: def __repr__(self):
197 ...: def __repr__(self):
198 ...: return 'r'
198 ...: return 'r'
199 ...:
199 ...:
200
200
201 In [5]: class sr(s,r): pass
201 In [5]: class sr(s,r): pass
202 ...:
202 ...:
203
203
204 In [6]:
204 In [6]:
205
205
206 In [7]: bb=b()
206 In [7]: bb=b()
207
207
208 In [8]: ss=s()
208 In [8]: ss=s()
209
209
210 In [9]: rr=r()
210 In [9]: rr=r()
211
211
212 In [10]: ssrr=sr()
212 In [10]: ssrr=sr()
213
213
214 In [11]: 4.5
214 In [11]: 4.5
215 Out[11]: 4.5
215 Out[11]: 4.5
216
216
217 In [12]: str(ss)
217 In [12]: str(ss)
218 Out[12]: 's'
218 Out[12]: 's'
219
219
220 In [13]:
220 In [13]:
221
221
222 In [14]: %hist -op
222 In [14]: %hist -op
223 >>> class b:
223 >>> class b:
224 ... pass
224 ... pass
225 ...
225 ...
226 >>> class s(b):
226 >>> class s(b):
227 ... def __str__(self):
227 ... def __str__(self):
228 ... return 's'
228 ... return 's'
229 ...
229 ...
230 >>>
230 >>>
231 >>> class r(b):
231 >>> class r(b):
232 ... def __repr__(self):
232 ... def __repr__(self):
233 ... return 'r'
233 ... return 'r'
234 ...
234 ...
235 >>> class sr(s,r): pass
235 >>> class sr(s,r): pass
236 >>>
236 >>>
237 >>> bb=b()
237 >>> bb=b()
238 >>> ss=s()
238 >>> ss=s()
239 >>> rr=r()
239 >>> rr=r()
240 >>> ssrr=sr()
240 >>> ssrr=sr()
241 >>> 4.5
241 >>> 4.5
242 4.5
242 4.5
243 >>> str(ss)
243 >>> str(ss)
244 's'
244 's'
245 >>>
245 >>>
246 """
246 """
247
247
248 def test_hist_pof():
248 def test_hist_pof():
249 ip = get_ipython()
249 ip = get_ipython()
250 ip.run_cell(u"1+2", store_history=True)
250 ip.run_cell(u"1+2", store_history=True)
251 #raise Exception(ip.history_manager.session_number)
251 #raise Exception(ip.history_manager.session_number)
252 #raise Exception(list(ip.history_manager._get_range_session()))
252 #raise Exception(list(ip.history_manager._get_range_session()))
253 with TemporaryDirectory() as td:
253 with TemporaryDirectory() as td:
254 tf = os.path.join(td, 'hist.py')
254 tf = os.path.join(td, 'hist.py')
255 ip.run_line_magic('history', '-pof %s' % tf)
255 ip.run_line_magic('history', '-pof %s' % tf)
256 assert os.path.isfile(tf)
256 assert os.path.isfile(tf)
257
257
258
258
259 @dec.skip_without('sqlite3')
259 @dec.skip_without('sqlite3')
260 def test_macro():
260 def test_macro():
261 ip = get_ipython()
261 ip = get_ipython()
262 ip.history_manager.reset() # Clear any existing history.
262 ip.history_manager.reset() # Clear any existing history.
263 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
263 cmds = ["a=1", "def b():\n return a**2", "print(a,b())"]
264 for i, cmd in enumerate(cmds, start=1):
264 for i, cmd in enumerate(cmds, start=1):
265 ip.history_manager.store_inputs(i, cmd)
265 ip.history_manager.store_inputs(i, cmd)
266 ip.magic("macro test 1-3")
266 ip.magic("macro test 1-3")
267 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
267 nt.assert_equal(ip.user_ns["test"].value, "\n".join(cmds)+"\n")
268
268
269 # List macros
269 # List macros
270 nt.assert_in("test", ip.magic("macro"))
270 nt.assert_in("test", ip.magic("macro"))
271
271
272
272
273 @dec.skip_without('sqlite3')
273 @dec.skip_without('sqlite3')
274 def test_macro_run():
274 def test_macro_run():
275 """Test that we can run a multi-line macro successfully."""
275 """Test that we can run a multi-line macro successfully."""
276 ip = get_ipython()
276 ip = get_ipython()
277 ip.history_manager.reset()
277 ip.history_manager.reset()
278 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
278 cmds = ["a=10", "a+=1", py3compat.doctest_refactor_print("print a"),
279 "%macro test 2-3"]
279 "%macro test 2-3"]
280 for cmd in cmds:
280 for cmd in cmds:
281 ip.run_cell(cmd, store_history=True)
281 ip.run_cell(cmd, store_history=True)
282 nt.assert_equal(ip.user_ns["test"].value,
282 nt.assert_equal(ip.user_ns["test"].value,
283 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
283 py3compat.doctest_refactor_print("a+=1\nprint a\n"))
284 with tt.AssertPrints("12"):
284 with tt.AssertPrints("12"):
285 ip.run_cell("test")
285 ip.run_cell("test")
286 with tt.AssertPrints("13"):
286 with tt.AssertPrints("13"):
287 ip.run_cell("test")
287 ip.run_cell("test")
288
288
289
289
290 def test_magic_magic():
290 def test_magic_magic():
291 """Test %magic"""
291 """Test %magic"""
292 ip = get_ipython()
292 ip = get_ipython()
293 with capture_output() as captured:
293 with capture_output() as captured:
294 ip.magic("magic")
294 ip.magic("magic")
295
295
296 stdout = captured.stdout
296 stdout = captured.stdout
297 nt.assert_in('%magic', stdout)
297 nt.assert_in('%magic', stdout)
298 nt.assert_in('IPython', stdout)
298 nt.assert_in('IPython', stdout)
299 nt.assert_in('Available', stdout)
299 nt.assert_in('Available', stdout)
300
300
301
301
302 @dec.skipif_not_numpy
302 @dec.skipif_not_numpy
303 def test_numpy_reset_array_undec():
303 def test_numpy_reset_array_undec():
304 "Test '%reset array' functionality"
304 "Test '%reset array' functionality"
305 _ip.ex('import numpy as np')
305 _ip.ex('import numpy as np')
306 _ip.ex('a = np.empty(2)')
306 _ip.ex('a = np.empty(2)')
307 nt.assert_in('a', _ip.user_ns)
307 nt.assert_in('a', _ip.user_ns)
308 _ip.magic('reset -f array')
308 _ip.magic('reset -f array')
309 nt.assert_not_in('a', _ip.user_ns)
309 nt.assert_not_in('a', _ip.user_ns)
310
310
311 def test_reset_out():
311 def test_reset_out():
312 "Test '%reset out' magic"
312 "Test '%reset out' magic"
313 _ip.run_cell("parrot = 'dead'", store_history=True)
313 _ip.run_cell("parrot = 'dead'", store_history=True)
314 # test '%reset -f out', make an Out prompt
314 # test '%reset -f out', make an Out prompt
315 _ip.run_cell("parrot", store_history=True)
315 _ip.run_cell("parrot", store_history=True)
316 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
316 nt.assert_true('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
317 _ip.magic('reset -f out')
317 _ip.magic('reset -f out')
318 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
318 nt.assert_false('dead' in [_ip.user_ns[x] for x in ('_','__','___')])
319 nt.assert_equal(len(_ip.user_ns['Out']), 0)
319 nt.assert_equal(len(_ip.user_ns['Out']), 0)
320
320
321 def test_reset_in():
321 def test_reset_in():
322 "Test '%reset in' magic"
322 "Test '%reset in' magic"
323 # test '%reset -f in'
323 # test '%reset -f in'
324 _ip.run_cell("parrot", store_history=True)
324 _ip.run_cell("parrot", store_history=True)
325 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
325 nt.assert_true('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
326 _ip.magic('%reset -f in')
326 _ip.magic('%reset -f in')
327 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
327 nt.assert_false('parrot' in [_ip.user_ns[x] for x in ('_i','_ii','_iii')])
328 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
328 nt.assert_equal(len(set(_ip.user_ns['In'])), 1)
329
329
330 def test_reset_dhist():
330 def test_reset_dhist():
331 "Test '%reset dhist' magic"
331 "Test '%reset dhist' magic"
332 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
332 _ip.run_cell("tmp = [d for d in _dh]") # copy before clearing
333 _ip.magic('cd ' + os.path.dirname(nt.__file__))
333 _ip.magic('cd ' + os.path.dirname(nt.__file__))
334 _ip.magic('cd -')
334 _ip.magic('cd -')
335 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
335 nt.assert_true(len(_ip.user_ns['_dh']) > 0)
336 _ip.magic('reset -f dhist')
336 _ip.magic('reset -f dhist')
337 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
337 nt.assert_equal(len(_ip.user_ns['_dh']), 0)
338 _ip.run_cell("_dh = [d for d in tmp]") #restore
338 _ip.run_cell("_dh = [d for d in tmp]") #restore
339
339
340 def test_reset_in_length():
340 def test_reset_in_length():
341 "Test that '%reset in' preserves In[] length"
341 "Test that '%reset in' preserves In[] length"
342 _ip.run_cell("print 'foo'")
342 _ip.run_cell("print 'foo'")
343 _ip.run_cell("reset -f in")
343 _ip.run_cell("reset -f in")
344 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
344 nt.assert_equal(len(_ip.user_ns['In']), _ip.displayhook.prompt_count+1)
345
345
346 def test_tb_syntaxerror():
346 def test_tb_syntaxerror():
347 """test %tb after a SyntaxError"""
347 """test %tb after a SyntaxError"""
348 ip = get_ipython()
348 ip = get_ipython()
349 ip.run_cell("for")
349 ip.run_cell("for")
350
350
351 # trap and validate stdout
351 # trap and validate stdout
352 save_stdout = sys.stdout
352 save_stdout = sys.stdout
353 try:
353 try:
354 sys.stdout = StringIO()
354 sys.stdout = StringIO()
355 ip.run_cell("%tb")
355 ip.run_cell("%tb")
356 out = sys.stdout.getvalue()
356 out = sys.stdout.getvalue()
357 finally:
357 finally:
358 sys.stdout = save_stdout
358 sys.stdout = save_stdout
359 # trim output, and only check the last line
359 # trim output, and only check the last line
360 last_line = out.rstrip().splitlines()[-1].strip()
360 last_line = out.rstrip().splitlines()[-1].strip()
361 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
361 nt.assert_equal(last_line, "SyntaxError: invalid syntax")
362
362
363
363
364 def test_time():
364 def test_time():
365 ip = get_ipython()
365 ip = get_ipython()
366
366
367 with tt.AssertPrints("Wall time: "):
367 with tt.AssertPrints("Wall time: "):
368 ip.run_cell("%time None")
368 ip.run_cell("%time None")
369
369
370 ip.run_cell("def f(kmjy):\n"
370 ip.run_cell("def f(kmjy):\n"
371 " %time print (2*kmjy)")
371 " %time print (2*kmjy)")
372
372
373 with tt.AssertPrints("Wall time: "):
373 with tt.AssertPrints("Wall time: "):
374 with tt.AssertPrints("hihi", suppress=False):
374 with tt.AssertPrints("hihi", suppress=False):
375 ip.run_cell("f('hi')")
375 ip.run_cell("f('hi')")
376
376
377
377
378 @dec.skip_win32
378 @dec.skip_win32
379 def test_time2():
379 def test_time2():
380 ip = get_ipython()
380 ip = get_ipython()
381
381
382 with tt.AssertPrints("CPU times: user "):
382 with tt.AssertPrints("CPU times: user "):
383 ip.run_cell("%time None")
383 ip.run_cell("%time None")
384
384
385 def test_time3():
385 def test_time3():
386 """Erroneous magic function calls, issue gh-3334"""
386 """Erroneous magic function calls, issue gh-3334"""
387 ip = get_ipython()
387 ip = get_ipython()
388 ip.user_ns.pop('run', None)
388 ip.user_ns.pop('run', None)
389
389
390 with tt.AssertNotPrints("not found", channel='stderr'):
390 with tt.AssertNotPrints("not found", channel='stderr'):
391 ip.run_cell("%%time\n"
391 ip.run_cell("%%time\n"
392 "run = 0\n"
392 "run = 0\n"
393 "run += 1")
393 "run += 1")
394
394
395 def test_doctest_mode():
395 def test_doctest_mode():
396 "Toggle doctest_mode twice, it should be a no-op and run without error"
396 "Toggle doctest_mode twice, it should be a no-op and run without error"
397 _ip.magic('doctest_mode')
397 _ip.magic('doctest_mode')
398 _ip.magic('doctest_mode')
398 _ip.magic('doctest_mode')
399
399
400
400
401 def test_parse_options():
401 def test_parse_options():
402 """Tests for basic options parsing in magics."""
402 """Tests for basic options parsing in magics."""
403 # These are only the most minimal of tests, more should be added later. At
403 # These are only the most minimal of tests, more should be added later. At
404 # the very least we check that basic text/unicode calls work OK.
404 # the very least we check that basic text/unicode calls work OK.
405 m = DummyMagics(_ip)
405 m = DummyMagics(_ip)
406 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
406 nt.assert_equal(m.parse_options('foo', '')[1], 'foo')
407 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
407 nt.assert_equal(m.parse_options(u'foo', '')[1], u'foo')
408
408
409
409
410 def test_dirops():
410 def test_dirops():
411 """Test various directory handling operations."""
411 """Test various directory handling operations."""
412 # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
412 # curpath = lambda :os.path.splitdrive(os.getcwd())[1].replace('\\','/')
413 curpath = os.getcwd
413 curpath = os.getcwd
414 startdir = os.getcwd()
414 startdir = os.getcwd()
415 ipdir = os.path.realpath(_ip.ipython_dir)
415 ipdir = os.path.realpath(_ip.ipython_dir)
416 try:
416 try:
417 _ip.magic('cd "%s"' % ipdir)
417 _ip.magic('cd "%s"' % ipdir)
418 nt.assert_equal(curpath(), ipdir)
418 nt.assert_equal(curpath(), ipdir)
419 _ip.magic('cd -')
419 _ip.magic('cd -')
420 nt.assert_equal(curpath(), startdir)
420 nt.assert_equal(curpath(), startdir)
421 _ip.magic('pushd "%s"' % ipdir)
421 _ip.magic('pushd "%s"' % ipdir)
422 nt.assert_equal(curpath(), ipdir)
422 nt.assert_equal(curpath(), ipdir)
423 _ip.magic('popd')
423 _ip.magic('popd')
424 nt.assert_equal(curpath(), startdir)
424 nt.assert_equal(curpath(), startdir)
425 finally:
425 finally:
426 os.chdir(startdir)
426 os.chdir(startdir)
427
427
428
428
429 def test_xmode():
429 def test_xmode():
430 # Calling xmode three times should be a no-op
430 # Calling xmode three times should be a no-op
431 xmode = _ip.InteractiveTB.mode
431 xmode = _ip.InteractiveTB.mode
432 for i in range(3):
432 for i in range(3):
433 _ip.magic("xmode")
433 _ip.magic("xmode")
434 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
434 nt.assert_equal(_ip.InteractiveTB.mode, xmode)
435
435
436 def test_reset_hard():
436 def test_reset_hard():
437 monitor = []
437 monitor = []
438 class A(object):
438 class A(object):
439 def __del__(self):
439 def __del__(self):
440 monitor.append(1)
440 monitor.append(1)
441 def __repr__(self):
441 def __repr__(self):
442 return "<A instance>"
442 return "<A instance>"
443
443
444 _ip.user_ns["a"] = A()
444 _ip.user_ns["a"] = A()
445 _ip.run_cell("a")
445 _ip.run_cell("a")
446
446
447 nt.assert_equal(monitor, [])
447 nt.assert_equal(monitor, [])
448 _ip.magic("reset -f")
448 _ip.magic("reset -f")
449 nt.assert_equal(monitor, [1])
449 nt.assert_equal(monitor, [1])
450
450
451 class TestXdel(tt.TempFileMixin):
451 class TestXdel(tt.TempFileMixin):
452 def test_xdel(self):
452 def test_xdel(self):
453 """Test that references from %run are cleared by xdel."""
453 """Test that references from %run are cleared by xdel."""
454 src = ("class A(object):\n"
454 src = ("class A(object):\n"
455 " monitor = []\n"
455 " monitor = []\n"
456 " def __del__(self):\n"
456 " def __del__(self):\n"
457 " self.monitor.append(1)\n"
457 " self.monitor.append(1)\n"
458 "a = A()\n")
458 "a = A()\n")
459 self.mktmp(src)
459 self.mktmp(src)
460 # %run creates some hidden references...
460 # %run creates some hidden references...
461 _ip.magic("run %s" % self.fname)
461 _ip.magic("run %s" % self.fname)
462 # ... as does the displayhook.
462 # ... as does the displayhook.
463 _ip.run_cell("a")
463 _ip.run_cell("a")
464
464
465 monitor = _ip.user_ns["A"].monitor
465 monitor = _ip.user_ns["A"].monitor
466 nt.assert_equal(monitor, [])
466 nt.assert_equal(monitor, [])
467
467
468 _ip.magic("xdel a")
468 _ip.magic("xdel a")
469
469
470 # Check that a's __del__ method has been called.
470 # Check that a's __del__ method has been called.
471 nt.assert_equal(monitor, [1])
471 nt.assert_equal(monitor, [1])
472
472
473 def doctest_who():
473 def doctest_who():
474 """doctest for %who
474 """doctest for %who
475
475
476 In [1]: %reset -f
476 In [1]: %reset -f
477
477
478 In [2]: alpha = 123
478 In [2]: alpha = 123
479
479
480 In [3]: beta = 'beta'
480 In [3]: beta = 'beta'
481
481
482 In [4]: %who int
482 In [4]: %who int
483 alpha
483 alpha
484
484
485 In [5]: %who str
485 In [5]: %who str
486 beta
486 beta
487
487
488 In [6]: %whos
488 In [6]: %whos
489 Variable Type Data/Info
489 Variable Type Data/Info
490 ----------------------------
490 ----------------------------
491 alpha int 123
491 alpha int 123
492 beta str beta
492 beta str beta
493
493
494 In [7]: %who_ls
494 In [7]: %who_ls
495 Out[7]: ['alpha', 'beta']
495 Out[7]: ['alpha', 'beta']
496 """
496 """
497
497
498 def test_whos():
498 def test_whos():
499 """Check that whos is protected against objects where repr() fails."""
499 """Check that whos is protected against objects where repr() fails."""
500 class A(object):
500 class A(object):
501 def __repr__(self):
501 def __repr__(self):
502 raise Exception()
502 raise Exception()
503 _ip.user_ns['a'] = A()
503 _ip.user_ns['a'] = A()
504 _ip.magic("whos")
504 _ip.magic("whos")
505
505
506 @py3compat.u_format
506 @py3compat.u_format
507 def doctest_precision():
507 def doctest_precision():
508 """doctest for %precision
508 """doctest for %precision
509
509
510 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
510 In [1]: f = get_ipython().display_formatter.formatters['text/plain']
511
511
512 In [2]: %precision 5
512 In [2]: %precision 5
513 Out[2]: {u}'%.5f'
513 Out[2]: '%.5f'
514
514
515 In [3]: f.float_format
515 In [3]: f.float_format
516 Out[3]: {u}'%.5f'
516 Out[3]: '%.5f'
517
517
518 In [4]: %precision %e
518 In [4]: %precision %e
519 Out[4]: {u}'%e'
519 Out[4]: '%e'
520
520
521 In [5]: f(3.1415927)
521 In [5]: f(3.1415927)
522 Out[5]: {u}'3.141593e+00'
522 Out[5]: '3.141593e+00'
523 """
523 """
524
524
525 def test_psearch():
525 def test_psearch():
526 with tt.AssertPrints("dict.fromkeys"):
526 with tt.AssertPrints("dict.fromkeys"):
527 _ip.run_cell("dict.fr*?")
527 _ip.run_cell("dict.fr*?")
528
528
529 def test_timeit_shlex():
529 def test_timeit_shlex():
530 """test shlex issues with timeit (#1109)"""
530 """test shlex issues with timeit (#1109)"""
531 _ip.ex("def f(*a,**kw): pass")
531 _ip.ex("def f(*a,**kw): pass")
532 _ip.magic('timeit -n1 "this is a bug".count(" ")')
532 _ip.magic('timeit -n1 "this is a bug".count(" ")')
533 _ip.magic('timeit -r1 -n1 f(" ", 1)')
533 _ip.magic('timeit -r1 -n1 f(" ", 1)')
534 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
534 _ip.magic('timeit -r1 -n1 f(" ", 1, " ", 2, " ")')
535 _ip.magic('timeit -r1 -n1 ("a " + "b")')
535 _ip.magic('timeit -r1 -n1 ("a " + "b")')
536 _ip.magic('timeit -r1 -n1 f("a " + "b")')
536 _ip.magic('timeit -r1 -n1 f("a " + "b")')
537 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
537 _ip.magic('timeit -r1 -n1 f("a " + "b ")')
538
538
539
539
540 def test_timeit_arguments():
540 def test_timeit_arguments():
541 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
541 "Test valid timeit arguments, should not cause SyntaxError (GH #1269)"
542 _ip.magic("timeit ('#')")
542 _ip.magic("timeit ('#')")
543
543
544
544
545 def test_timeit_special_syntax():
545 def test_timeit_special_syntax():
546 "Test %%timeit with IPython special syntax"
546 "Test %%timeit with IPython special syntax"
547 @register_line_magic
547 @register_line_magic
548 def lmagic(line):
548 def lmagic(line):
549 ip = get_ipython()
549 ip = get_ipython()
550 ip.user_ns['lmagic_out'] = line
550 ip.user_ns['lmagic_out'] = line
551
551
552 # line mode test
552 # line mode test
553 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
553 _ip.run_line_magic('timeit', '-n1 -r1 %lmagic my line')
554 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
554 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
555 # cell mode test
555 # cell mode test
556 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
556 _ip.run_cell_magic('timeit', '-n1 -r1', '%lmagic my line2')
557 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
557 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
558
558
559 def test_timeit_return():
559 def test_timeit_return():
560 """
560 """
561 test wether timeit -o return object
561 test wether timeit -o return object
562 """
562 """
563
563
564 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
564 res = _ip.run_line_magic('timeit','-n10 -r10 -o 1')
565 assert(res is not None)
565 assert(res is not None)
566
566
567 def test_timeit_quiet():
567 def test_timeit_quiet():
568 """
568 """
569 test quiet option of timeit magic
569 test quiet option of timeit magic
570 """
570 """
571 with tt.AssertNotPrints("loops"):
571 with tt.AssertNotPrints("loops"):
572 _ip.run_cell("%timeit -n1 -r1 -q 1")
572 _ip.run_cell("%timeit -n1 -r1 -q 1")
573
573
574 def test_timeit_return_quiet():
574 def test_timeit_return_quiet():
575 with tt.AssertNotPrints("loops"):
575 with tt.AssertNotPrints("loops"):
576 res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1')
576 res = _ip.run_line_magic('timeit', '-n1 -r1 -q -o 1')
577 assert (res is not None)
577 assert (res is not None)
578
578
579 def test_timeit_invalid_return():
579 def test_timeit_invalid_return():
580 with nt.assert_raises_regexp(SyntaxError, "outside function"):
580 with nt.assert_raises_regexp(SyntaxError, "outside function"):
581 _ip.run_line_magic('timeit', 'return')
581 _ip.run_line_magic('timeit', 'return')
582
582
583 @dec.skipif(execution.profile is None)
583 @dec.skipif(execution.profile is None)
584 def test_prun_special_syntax():
584 def test_prun_special_syntax():
585 "Test %%prun with IPython special syntax"
585 "Test %%prun with IPython special syntax"
586 @register_line_magic
586 @register_line_magic
587 def lmagic(line):
587 def lmagic(line):
588 ip = get_ipython()
588 ip = get_ipython()
589 ip.user_ns['lmagic_out'] = line
589 ip.user_ns['lmagic_out'] = line
590
590
591 # line mode test
591 # line mode test
592 _ip.run_line_magic('prun', '-q %lmagic my line')
592 _ip.run_line_magic('prun', '-q %lmagic my line')
593 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
593 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line')
594 # cell mode test
594 # cell mode test
595 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
595 _ip.run_cell_magic('prun', '-q', '%lmagic my line2')
596 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
596 nt.assert_equal(_ip.user_ns['lmagic_out'], 'my line2')
597
597
598 @dec.skipif(execution.profile is None)
598 @dec.skipif(execution.profile is None)
599 def test_prun_quotes():
599 def test_prun_quotes():
600 "Test that prun does not clobber string escapes (GH #1302)"
600 "Test that prun does not clobber string escapes (GH #1302)"
601 _ip.magic(r"prun -q x = '\t'")
601 _ip.magic(r"prun -q x = '\t'")
602 nt.assert_equal(_ip.user_ns['x'], '\t')
602 nt.assert_equal(_ip.user_ns['x'], '\t')
603
603
604 def test_extension():
604 def test_extension():
605 # Debugging information for failures of this test
605 # Debugging information for failures of this test
606 print('sys.path:')
606 print('sys.path:')
607 for p in sys.path:
607 for p in sys.path:
608 print(' ', p)
608 print(' ', p)
609 print('CWD', os.getcwd())
609 print('CWD', os.getcwd())
610
610
611 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
611 nt.assert_raises(ImportError, _ip.magic, "load_ext daft_extension")
612 daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
612 daft_path = os.path.join(os.path.dirname(__file__), "daft_extension")
613 sys.path.insert(0, daft_path)
613 sys.path.insert(0, daft_path)
614 try:
614 try:
615 _ip.user_ns.pop('arq', None)
615 _ip.user_ns.pop('arq', None)
616 invalidate_caches() # Clear import caches
616 invalidate_caches() # Clear import caches
617 _ip.magic("load_ext daft_extension")
617 _ip.magic("load_ext daft_extension")
618 nt.assert_equal(_ip.user_ns['arq'], 185)
618 nt.assert_equal(_ip.user_ns['arq'], 185)
619 _ip.magic("unload_ext daft_extension")
619 _ip.magic("unload_ext daft_extension")
620 assert 'arq' not in _ip.user_ns
620 assert 'arq' not in _ip.user_ns
621 finally:
621 finally:
622 sys.path.remove(daft_path)
622 sys.path.remove(daft_path)
623
623
624
624
625 def test_notebook_export_json():
625 def test_notebook_export_json():
626 _ip = get_ipython()
626 _ip = get_ipython()
627 _ip.history_manager.reset() # Clear any existing history.
627 _ip.history_manager.reset() # Clear any existing history.
628 cmds = [u"a=1", u"def b():\n return a**2", u"print('noël, été', b())"]
628 cmds = [u"a=1", u"def b():\n return a**2", u"print('noël, été', b())"]
629 for i, cmd in enumerate(cmds, start=1):
629 for i, cmd in enumerate(cmds, start=1):
630 _ip.history_manager.store_inputs(i, cmd)
630 _ip.history_manager.store_inputs(i, cmd)
631 with TemporaryDirectory() as td:
631 with TemporaryDirectory() as td:
632 outfile = os.path.join(td, "nb.ipynb")
632 outfile = os.path.join(td, "nb.ipynb")
633 _ip.magic("notebook -e %s" % outfile)
633 _ip.magic("notebook -e %s" % outfile)
634
634
635
635
636 class TestEnv(TestCase):
636 class TestEnv(TestCase):
637
637
638 def test_env(self):
638 def test_env(self):
639 env = _ip.magic("env")
639 env = _ip.magic("env")
640 self.assertTrue(isinstance(env, dict))
640 self.assertTrue(isinstance(env, dict))
641
641
642 def test_env_get_set_simple(self):
642 def test_env_get_set_simple(self):
643 env = _ip.magic("env var val1")
643 env = _ip.magic("env var val1")
644 self.assertEqual(env, None)
644 self.assertEqual(env, None)
645 self.assertEqual(os.environ['var'], 'val1')
645 self.assertEqual(os.environ['var'], 'val1')
646 self.assertEqual(_ip.magic("env var"), 'val1')
646 self.assertEqual(_ip.magic("env var"), 'val1')
647 env = _ip.magic("env var=val2")
647 env = _ip.magic("env var=val2")
648 self.assertEqual(env, None)
648 self.assertEqual(env, None)
649 self.assertEqual(os.environ['var'], 'val2')
649 self.assertEqual(os.environ['var'], 'val2')
650
650
651 def test_env_get_set_complex(self):
651 def test_env_get_set_complex(self):
652 env = _ip.magic("env var 'val1 '' 'val2")
652 env = _ip.magic("env var 'val1 '' 'val2")
653 self.assertEqual(env, None)
653 self.assertEqual(env, None)
654 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
654 self.assertEqual(os.environ['var'], "'val1 '' 'val2")
655 self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2")
655 self.assertEqual(_ip.magic("env var"), "'val1 '' 'val2")
656 env = _ip.magic('env var=val2 val3="val4')
656 env = _ip.magic('env var=val2 val3="val4')
657 self.assertEqual(env, None)
657 self.assertEqual(env, None)
658 self.assertEqual(os.environ['var'], 'val2 val3="val4')
658 self.assertEqual(os.environ['var'], 'val2 val3="val4')
659
659
660 def test_env_set_bad_input(self):
660 def test_env_set_bad_input(self):
661 self.assertRaises(UsageError, lambda: _ip.magic("set_env var"))
661 self.assertRaises(UsageError, lambda: _ip.magic("set_env var"))
662
662
663 def test_env_set_whitespace(self):
663 def test_env_set_whitespace(self):
664 self.assertRaises(UsageError, lambda: _ip.magic("env var A=B"))
664 self.assertRaises(UsageError, lambda: _ip.magic("env var A=B"))
665
665
666
666
667 class CellMagicTestCase(TestCase):
667 class CellMagicTestCase(TestCase):
668
668
669 def check_ident(self, magic):
669 def check_ident(self, magic):
670 # Manually called, we get the result
670 # Manually called, we get the result
671 out = _ip.run_cell_magic(magic, 'a', 'b')
671 out = _ip.run_cell_magic(magic, 'a', 'b')
672 nt.assert_equal(out, ('a','b'))
672 nt.assert_equal(out, ('a','b'))
673 # Via run_cell, it goes into the user's namespace via displayhook
673 # Via run_cell, it goes into the user's namespace via displayhook
674 _ip.run_cell('%%' + magic +' c\nd')
674 _ip.run_cell('%%' + magic +' c\nd')
675 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
675 nt.assert_equal(_ip.user_ns['_'], ('c','d'))
676
676
677 def test_cell_magic_func_deco(self):
677 def test_cell_magic_func_deco(self):
678 "Cell magic using simple decorator"
678 "Cell magic using simple decorator"
679 @register_cell_magic
679 @register_cell_magic
680 def cellm(line, cell):
680 def cellm(line, cell):
681 return line, cell
681 return line, cell
682
682
683 self.check_ident('cellm')
683 self.check_ident('cellm')
684
684
685 def test_cell_magic_reg(self):
685 def test_cell_magic_reg(self):
686 "Cell magic manually registered"
686 "Cell magic manually registered"
687 def cellm(line, cell):
687 def cellm(line, cell):
688 return line, cell
688 return line, cell
689
689
690 _ip.register_magic_function(cellm, 'cell', 'cellm2')
690 _ip.register_magic_function(cellm, 'cell', 'cellm2')
691 self.check_ident('cellm2')
691 self.check_ident('cellm2')
692
692
693 def test_cell_magic_class(self):
693 def test_cell_magic_class(self):
694 "Cell magics declared via a class"
694 "Cell magics declared via a class"
695 @magics_class
695 @magics_class
696 class MyMagics(Magics):
696 class MyMagics(Magics):
697
697
698 @cell_magic
698 @cell_magic
699 def cellm3(self, line, cell):
699 def cellm3(self, line, cell):
700 return line, cell
700 return line, cell
701
701
702 _ip.register_magics(MyMagics)
702 _ip.register_magics(MyMagics)
703 self.check_ident('cellm3')
703 self.check_ident('cellm3')
704
704
705 def test_cell_magic_class2(self):
705 def test_cell_magic_class2(self):
706 "Cell magics declared via a class, #2"
706 "Cell magics declared via a class, #2"
707 @magics_class
707 @magics_class
708 class MyMagics2(Magics):
708 class MyMagics2(Magics):
709
709
710 @cell_magic('cellm4')
710 @cell_magic('cellm4')
711 def cellm33(self, line, cell):
711 def cellm33(self, line, cell):
712 return line, cell
712 return line, cell
713
713
714 _ip.register_magics(MyMagics2)
714 _ip.register_magics(MyMagics2)
715 self.check_ident('cellm4')
715 self.check_ident('cellm4')
716 # Check that nothing is registered as 'cellm33'
716 # Check that nothing is registered as 'cellm33'
717 c33 = _ip.find_cell_magic('cellm33')
717 c33 = _ip.find_cell_magic('cellm33')
718 nt.assert_equal(c33, None)
718 nt.assert_equal(c33, None)
719
719
720 def test_file():
720 def test_file():
721 """Basic %%file"""
721 """Basic %%file"""
722 ip = get_ipython()
722 ip = get_ipython()
723 with TemporaryDirectory() as td:
723 with TemporaryDirectory() as td:
724 fname = os.path.join(td, 'file1')
724 fname = os.path.join(td, 'file1')
725 ip.run_cell_magic("file", fname, u'\n'.join([
725 ip.run_cell_magic("file", fname, u'\n'.join([
726 'line1',
726 'line1',
727 'line2',
727 'line2',
728 ]))
728 ]))
729 with open(fname) as f:
729 with open(fname) as f:
730 s = f.read()
730 s = f.read()
731 nt.assert_in('line1\n', s)
731 nt.assert_in('line1\n', s)
732 nt.assert_in('line2', s)
732 nt.assert_in('line2', s)
733
733
734 def test_file_var_expand():
734 def test_file_var_expand():
735 """%%file $filename"""
735 """%%file $filename"""
736 ip = get_ipython()
736 ip = get_ipython()
737 with TemporaryDirectory() as td:
737 with TemporaryDirectory() as td:
738 fname = os.path.join(td, 'file1')
738 fname = os.path.join(td, 'file1')
739 ip.user_ns['filename'] = fname
739 ip.user_ns['filename'] = fname
740 ip.run_cell_magic("file", '$filename', u'\n'.join([
740 ip.run_cell_magic("file", '$filename', u'\n'.join([
741 'line1',
741 'line1',
742 'line2',
742 'line2',
743 ]))
743 ]))
744 with open(fname) as f:
744 with open(fname) as f:
745 s = f.read()
745 s = f.read()
746 nt.assert_in('line1\n', s)
746 nt.assert_in('line1\n', s)
747 nt.assert_in('line2', s)
747 nt.assert_in('line2', s)
748
748
749 def test_file_unicode():
749 def test_file_unicode():
750 """%%file with unicode cell"""
750 """%%file with unicode cell"""
751 ip = get_ipython()
751 ip = get_ipython()
752 with TemporaryDirectory() as td:
752 with TemporaryDirectory() as td:
753 fname = os.path.join(td, 'file1')
753 fname = os.path.join(td, 'file1')
754 ip.run_cell_magic("file", fname, u'\n'.join([
754 ip.run_cell_magic("file", fname, u'\n'.join([
755 u'liné1',
755 u'liné1',
756 u'liné2',
756 u'liné2',
757 ]))
757 ]))
758 with io.open(fname, encoding='utf-8') as f:
758 with io.open(fname, encoding='utf-8') as f:
759 s = f.read()
759 s = f.read()
760 nt.assert_in(u'liné1\n', s)
760 nt.assert_in(u'liné1\n', s)
761 nt.assert_in(u'liné2', s)
761 nt.assert_in(u'liné2', s)
762
762
763 def test_file_amend():
763 def test_file_amend():
764 """%%file -a amends files"""
764 """%%file -a amends files"""
765 ip = get_ipython()
765 ip = get_ipython()
766 with TemporaryDirectory() as td:
766 with TemporaryDirectory() as td:
767 fname = os.path.join(td, 'file2')
767 fname = os.path.join(td, 'file2')
768 ip.run_cell_magic("file", fname, u'\n'.join([
768 ip.run_cell_magic("file", fname, u'\n'.join([
769 'line1',
769 'line1',
770 'line2',
770 'line2',
771 ]))
771 ]))
772 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
772 ip.run_cell_magic("file", "-a %s" % fname, u'\n'.join([
773 'line3',
773 'line3',
774 'line4',
774 'line4',
775 ]))
775 ]))
776 with open(fname) as f:
776 with open(fname) as f:
777 s = f.read()
777 s = f.read()
778 nt.assert_in('line1\n', s)
778 nt.assert_in('line1\n', s)
779 nt.assert_in('line3\n', s)
779 nt.assert_in('line3\n', s)
780
780
781
781
782 def test_script_config():
782 def test_script_config():
783 ip = get_ipython()
783 ip = get_ipython()
784 ip.config.ScriptMagics.script_magics = ['whoda']
784 ip.config.ScriptMagics.script_magics = ['whoda']
785 sm = script.ScriptMagics(shell=ip)
785 sm = script.ScriptMagics(shell=ip)
786 nt.assert_in('whoda', sm.magics['cell'])
786 nt.assert_in('whoda', sm.magics['cell'])
787
787
788 @dec.skip_win32
788 @dec.skip_win32
789 def test_script_out():
789 def test_script_out():
790 ip = get_ipython()
790 ip = get_ipython()
791 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
791 ip.run_cell_magic("script", "--out output sh", "echo 'hi'")
792 nt.assert_equal(ip.user_ns['output'], 'hi\n')
792 nt.assert_equal(ip.user_ns['output'], 'hi\n')
793
793
794 @dec.skip_win32
794 @dec.skip_win32
795 def test_script_err():
795 def test_script_err():
796 ip = get_ipython()
796 ip = get_ipython()
797 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
797 ip.run_cell_magic("script", "--err error sh", "echo 'hello' >&2")
798 nt.assert_equal(ip.user_ns['error'], 'hello\n')
798 nt.assert_equal(ip.user_ns['error'], 'hello\n')
799
799
800 @dec.skip_win32
800 @dec.skip_win32
801 def test_script_out_err():
801 def test_script_out_err():
802 ip = get_ipython()
802 ip = get_ipython()
803 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
803 ip.run_cell_magic("script", "--out output --err error sh", "echo 'hi'\necho 'hello' >&2")
804 nt.assert_equal(ip.user_ns['output'], 'hi\n')
804 nt.assert_equal(ip.user_ns['output'], 'hi\n')
805 nt.assert_equal(ip.user_ns['error'], 'hello\n')
805 nt.assert_equal(ip.user_ns['error'], 'hello\n')
806
806
807 @dec.skip_win32
807 @dec.skip_win32
808 def test_script_bg_out():
808 def test_script_bg_out():
809 ip = get_ipython()
809 ip = get_ipython()
810 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
810 ip.run_cell_magic("script", "--bg --out output sh", "echo 'hi'")
811 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
811 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
812
812
813 @dec.skip_win32
813 @dec.skip_win32
814 def test_script_bg_err():
814 def test_script_bg_err():
815 ip = get_ipython()
815 ip = get_ipython()
816 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
816 ip.run_cell_magic("script", "--bg --err error sh", "echo 'hello' >&2")
817 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
817 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
818
818
819 @dec.skip_win32
819 @dec.skip_win32
820 def test_script_bg_out_err():
820 def test_script_bg_out_err():
821 ip = get_ipython()
821 ip = get_ipython()
822 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
822 ip.run_cell_magic("script", "--bg --out output --err error sh", "echo 'hi'\necho 'hello' >&2")
823 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
823 nt.assert_equal(ip.user_ns['output'].read(), b'hi\n')
824 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
824 nt.assert_equal(ip.user_ns['error'].read(), b'hello\n')
825
825
826 def test_script_defaults():
826 def test_script_defaults():
827 ip = get_ipython()
827 ip = get_ipython()
828 for cmd in ['sh', 'bash', 'perl', 'ruby']:
828 for cmd in ['sh', 'bash', 'perl', 'ruby']:
829 try:
829 try:
830 find_cmd(cmd)
830 find_cmd(cmd)
831 except Exception:
831 except Exception:
832 pass
832 pass
833 else:
833 else:
834 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
834 nt.assert_in(cmd, ip.magics_manager.magics['cell'])
835
835
836
836
837 @magics_class
837 @magics_class
838 class FooFoo(Magics):
838 class FooFoo(Magics):
839 """class with both %foo and %%foo magics"""
839 """class with both %foo and %%foo magics"""
840 @line_magic('foo')
840 @line_magic('foo')
841 def line_foo(self, line):
841 def line_foo(self, line):
842 "I am line foo"
842 "I am line foo"
843 pass
843 pass
844
844
845 @cell_magic("foo")
845 @cell_magic("foo")
846 def cell_foo(self, line, cell):
846 def cell_foo(self, line, cell):
847 "I am cell foo, not line foo"
847 "I am cell foo, not line foo"
848 pass
848 pass
849
849
850 def test_line_cell_info():
850 def test_line_cell_info():
851 """%%foo and %foo magics are distinguishable to inspect"""
851 """%%foo and %foo magics are distinguishable to inspect"""
852 ip = get_ipython()
852 ip = get_ipython()
853 ip.magics_manager.register(FooFoo)
853 ip.magics_manager.register(FooFoo)
854 oinfo = ip.object_inspect('foo')
854 oinfo = ip.object_inspect('foo')
855 nt.assert_true(oinfo['found'])
855 nt.assert_true(oinfo['found'])
856 nt.assert_true(oinfo['ismagic'])
856 nt.assert_true(oinfo['ismagic'])
857
857
858 oinfo = ip.object_inspect('%%foo')
858 oinfo = ip.object_inspect('%%foo')
859 nt.assert_true(oinfo['found'])
859 nt.assert_true(oinfo['found'])
860 nt.assert_true(oinfo['ismagic'])
860 nt.assert_true(oinfo['ismagic'])
861 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
861 nt.assert_equal(oinfo['docstring'], FooFoo.cell_foo.__doc__)
862
862
863 oinfo = ip.object_inspect('%foo')
863 oinfo = ip.object_inspect('%foo')
864 nt.assert_true(oinfo['found'])
864 nt.assert_true(oinfo['found'])
865 nt.assert_true(oinfo['ismagic'])
865 nt.assert_true(oinfo['ismagic'])
866 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
866 nt.assert_equal(oinfo['docstring'], FooFoo.line_foo.__doc__)
867
867
868 def test_multiple_magics():
868 def test_multiple_magics():
869 ip = get_ipython()
869 ip = get_ipython()
870 foo1 = FooFoo(ip)
870 foo1 = FooFoo(ip)
871 foo2 = FooFoo(ip)
871 foo2 = FooFoo(ip)
872 mm = ip.magics_manager
872 mm = ip.magics_manager
873 mm.register(foo1)
873 mm.register(foo1)
874 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
874 nt.assert_true(mm.magics['line']['foo'].__self__ is foo1)
875 mm.register(foo2)
875 mm.register(foo2)
876 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
876 nt.assert_true(mm.magics['line']['foo'].__self__ is foo2)
877
877
878 def test_alias_magic():
878 def test_alias_magic():
879 """Test %alias_magic."""
879 """Test %alias_magic."""
880 ip = get_ipython()
880 ip = get_ipython()
881 mm = ip.magics_manager
881 mm = ip.magics_manager
882
882
883 # Basic operation: both cell and line magics are created, if possible.
883 # Basic operation: both cell and line magics are created, if possible.
884 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
884 ip.run_line_magic('alias_magic', 'timeit_alias timeit')
885 nt.assert_in('timeit_alias', mm.magics['line'])
885 nt.assert_in('timeit_alias', mm.magics['line'])
886 nt.assert_in('timeit_alias', mm.magics['cell'])
886 nt.assert_in('timeit_alias', mm.magics['cell'])
887
887
888 # --cell is specified, line magic not created.
888 # --cell is specified, line magic not created.
889 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
889 ip.run_line_magic('alias_magic', '--cell timeit_cell_alias timeit')
890 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
890 nt.assert_not_in('timeit_cell_alias', mm.magics['line'])
891 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
891 nt.assert_in('timeit_cell_alias', mm.magics['cell'])
892
892
893 # Test that line alias is created successfully.
893 # Test that line alias is created successfully.
894 ip.run_line_magic('alias_magic', '--line env_alias env')
894 ip.run_line_magic('alias_magic', '--line env_alias env')
895 nt.assert_equal(ip.run_line_magic('env', ''),
895 nt.assert_equal(ip.run_line_magic('env', ''),
896 ip.run_line_magic('env_alias', ''))
896 ip.run_line_magic('env_alias', ''))
897
897
898 # Test that line alias with parameters passed in is created successfully.
898 # Test that line alias with parameters passed in is created successfully.
899 ip.run_line_magic('alias_magic', '--line history_alias history --params ' + shlex.quote('3'))
899 ip.run_line_magic('alias_magic', '--line history_alias history --params ' + shlex.quote('3'))
900 nt.assert_in('history_alias', mm.magics['line'])
900 nt.assert_in('history_alias', mm.magics['line'])
901
901
902
902
903 def test_save():
903 def test_save():
904 """Test %save."""
904 """Test %save."""
905 ip = get_ipython()
905 ip = get_ipython()
906 ip.history_manager.reset() # Clear any existing history.
906 ip.history_manager.reset() # Clear any existing history.
907 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
907 cmds = [u"a=1", u"def b():\n return a**2", u"print(a, b())"]
908 for i, cmd in enumerate(cmds, start=1):
908 for i, cmd in enumerate(cmds, start=1):
909 ip.history_manager.store_inputs(i, cmd)
909 ip.history_manager.store_inputs(i, cmd)
910 with TemporaryDirectory() as tmpdir:
910 with TemporaryDirectory() as tmpdir:
911 file = os.path.join(tmpdir, "testsave.py")
911 file = os.path.join(tmpdir, "testsave.py")
912 ip.run_line_magic("save", "%s 1-10" % file)
912 ip.run_line_magic("save", "%s 1-10" % file)
913 with open(file) as f:
913 with open(file) as f:
914 content = f.read()
914 content = f.read()
915 nt.assert_equal(content.count(cmds[0]), 1)
915 nt.assert_equal(content.count(cmds[0]), 1)
916 nt.assert_in('coding: utf-8', content)
916 nt.assert_in('coding: utf-8', content)
917 ip.run_line_magic("save", "-a %s 1-10" % file)
917 ip.run_line_magic("save", "-a %s 1-10" % file)
918 with open(file) as f:
918 with open(file) as f:
919 content = f.read()
919 content = f.read()
920 nt.assert_equal(content.count(cmds[0]), 2)
920 nt.assert_equal(content.count(cmds[0]), 2)
921 nt.assert_in('coding: utf-8', content)
921 nt.assert_in('coding: utf-8', content)
922
922
923
923
924 def test_store():
924 def test_store():
925 """Test %store."""
925 """Test %store."""
926 ip = get_ipython()
926 ip = get_ipython()
927 ip.run_line_magic('load_ext', 'storemagic')
927 ip.run_line_magic('load_ext', 'storemagic')
928
928
929 # make sure the storage is empty
929 # make sure the storage is empty
930 ip.run_line_magic('store', '-z')
930 ip.run_line_magic('store', '-z')
931 ip.user_ns['var'] = 42
931 ip.user_ns['var'] = 42
932 ip.run_line_magic('store', 'var')
932 ip.run_line_magic('store', 'var')
933 ip.user_ns['var'] = 39
933 ip.user_ns['var'] = 39
934 ip.run_line_magic('store', '-r')
934 ip.run_line_magic('store', '-r')
935 nt.assert_equal(ip.user_ns['var'], 42)
935 nt.assert_equal(ip.user_ns['var'], 42)
936
936
937 ip.run_line_magic('store', '-d var')
937 ip.run_line_magic('store', '-d var')
938 ip.user_ns['var'] = 39
938 ip.user_ns['var'] = 39
939 ip.run_line_magic('store' , '-r')
939 ip.run_line_magic('store' , '-r')
940 nt.assert_equal(ip.user_ns['var'], 39)
940 nt.assert_equal(ip.user_ns['var'], 39)
941
941
942
942
943 def _run_edit_test(arg_s, exp_filename=None,
943 def _run_edit_test(arg_s, exp_filename=None,
944 exp_lineno=-1,
944 exp_lineno=-1,
945 exp_contents=None,
945 exp_contents=None,
946 exp_is_temp=None):
946 exp_is_temp=None):
947 ip = get_ipython()
947 ip = get_ipython()
948 M = code.CodeMagics(ip)
948 M = code.CodeMagics(ip)
949 last_call = ['','']
949 last_call = ['','']
950 opts,args = M.parse_options(arg_s,'prxn:')
950 opts,args = M.parse_options(arg_s,'prxn:')
951 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
951 filename, lineno, is_temp = M._find_edit_target(ip, args, opts, last_call)
952
952
953 if exp_filename is not None:
953 if exp_filename is not None:
954 nt.assert_equal(exp_filename, filename)
954 nt.assert_equal(exp_filename, filename)
955 if exp_contents is not None:
955 if exp_contents is not None:
956 with io.open(filename, 'r', encoding='utf-8') as f:
956 with io.open(filename, 'r', encoding='utf-8') as f:
957 contents = f.read()
957 contents = f.read()
958 nt.assert_equal(exp_contents, contents)
958 nt.assert_equal(exp_contents, contents)
959 if exp_lineno != -1:
959 if exp_lineno != -1:
960 nt.assert_equal(exp_lineno, lineno)
960 nt.assert_equal(exp_lineno, lineno)
961 if exp_is_temp is not None:
961 if exp_is_temp is not None:
962 nt.assert_equal(exp_is_temp, is_temp)
962 nt.assert_equal(exp_is_temp, is_temp)
963
963
964
964
965 def test_edit_interactive():
965 def test_edit_interactive():
966 """%edit on interactively defined objects"""
966 """%edit on interactively defined objects"""
967 ip = get_ipython()
967 ip = get_ipython()
968 n = ip.execution_count
968 n = ip.execution_count
969 ip.run_cell(u"def foo(): return 1", store_history=True)
969 ip.run_cell(u"def foo(): return 1", store_history=True)
970
970
971 try:
971 try:
972 _run_edit_test("foo")
972 _run_edit_test("foo")
973 except code.InteractivelyDefined as e:
973 except code.InteractivelyDefined as e:
974 nt.assert_equal(e.index, n)
974 nt.assert_equal(e.index, n)
975 else:
975 else:
976 raise AssertionError("Should have raised InteractivelyDefined")
976 raise AssertionError("Should have raised InteractivelyDefined")
977
977
978
978
979 def test_edit_cell():
979 def test_edit_cell():
980 """%edit [cell id]"""
980 """%edit [cell id]"""
981 ip = get_ipython()
981 ip = get_ipython()
982
982
983 ip.run_cell(u"def foo(): return 1", store_history=True)
983 ip.run_cell(u"def foo(): return 1", store_history=True)
984
984
985 # test
985 # test
986 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
986 _run_edit_test("1", exp_contents=ip.user_ns['In'][1], exp_is_temp=True)
987
987
988 def test_bookmark():
988 def test_bookmark():
989 ip = get_ipython()
989 ip = get_ipython()
990 ip.run_line_magic('bookmark', 'bmname')
990 ip.run_line_magic('bookmark', 'bmname')
991 with tt.AssertPrints('bmname'):
991 with tt.AssertPrints('bmname'):
992 ip.run_line_magic('bookmark', '-l')
992 ip.run_line_magic('bookmark', '-l')
993 ip.run_line_magic('bookmark', '-d bmname')
993 ip.run_line_magic('bookmark', '-d bmname')
994
994
995 def test_ls_magic():
995 def test_ls_magic():
996 ip = get_ipython()
996 ip = get_ipython()
997 json_formatter = ip.display_formatter.formatters['application/json']
997 json_formatter = ip.display_formatter.formatters['application/json']
998 json_formatter.enabled = True
998 json_formatter.enabled = True
999 lsmagic = ip.magic('lsmagic')
999 lsmagic = ip.magic('lsmagic')
1000 with warnings.catch_warnings(record=True) as w:
1000 with warnings.catch_warnings(record=True) as w:
1001 j = json_formatter(lsmagic)
1001 j = json_formatter(lsmagic)
1002 nt.assert_equal(sorted(j), ['cell', 'line'])
1002 nt.assert_equal(sorted(j), ['cell', 'line'])
1003 nt.assert_equal(w, []) # no warnings
1003 nt.assert_equal(w, []) # no warnings
1004
1004
1005 def test_strip_initial_indent():
1005 def test_strip_initial_indent():
1006 def sii(s):
1006 def sii(s):
1007 lines = s.splitlines()
1007 lines = s.splitlines()
1008 return '\n'.join(code.strip_initial_indent(lines))
1008 return '\n'.join(code.strip_initial_indent(lines))
1009
1009
1010 nt.assert_equal(sii(" a = 1\nb = 2"), "a = 1\nb = 2")
1010 nt.assert_equal(sii(" a = 1\nb = 2"), "a = 1\nb = 2")
1011 nt.assert_equal(sii(" a\n b\nc"), "a\n b\nc")
1011 nt.assert_equal(sii(" a\n b\nc"), "a\n b\nc")
1012 nt.assert_equal(sii("a\n b"), "a\n b")
1012 nt.assert_equal(sii("a\n b"), "a\n b")
1013
1013
1014 def test_logging_magic_quiet_from_arg():
1014 def test_logging_magic_quiet_from_arg():
1015 _ip.config.LoggingMagics.quiet = False
1015 _ip.config.LoggingMagics.quiet = False
1016 lm = logging.LoggingMagics(shell=_ip)
1016 lm = logging.LoggingMagics(shell=_ip)
1017 with TemporaryDirectory() as td:
1017 with TemporaryDirectory() as td:
1018 try:
1018 try:
1019 with tt.AssertNotPrints(re.compile("Activating.*")):
1019 with tt.AssertNotPrints(re.compile("Activating.*")):
1020 lm.logstart('-q {}'.format(
1020 lm.logstart('-q {}'.format(
1021 os.path.join(td, "quiet_from_arg.log")))
1021 os.path.join(td, "quiet_from_arg.log")))
1022 finally:
1022 finally:
1023 _ip.logger.logstop()
1023 _ip.logger.logstop()
1024
1024
1025 def test_logging_magic_quiet_from_config():
1025 def test_logging_magic_quiet_from_config():
1026 _ip.config.LoggingMagics.quiet = True
1026 _ip.config.LoggingMagics.quiet = True
1027 lm = logging.LoggingMagics(shell=_ip)
1027 lm = logging.LoggingMagics(shell=_ip)
1028 with TemporaryDirectory() as td:
1028 with TemporaryDirectory() as td:
1029 try:
1029 try:
1030 with tt.AssertNotPrints(re.compile("Activating.*")):
1030 with tt.AssertNotPrints(re.compile("Activating.*")):
1031 lm.logstart(os.path.join(td, "quiet_from_config.log"))
1031 lm.logstart(os.path.join(td, "quiet_from_config.log"))
1032 finally:
1032 finally:
1033 _ip.logger.logstop()
1033 _ip.logger.logstop()
1034
1034
1035 def test_logging_magic_not_quiet():
1035 def test_logging_magic_not_quiet():
1036 _ip.config.LoggingMagics.quiet = False
1036 _ip.config.LoggingMagics.quiet = False
1037 lm = logging.LoggingMagics(shell=_ip)
1037 lm = logging.LoggingMagics(shell=_ip)
1038 with TemporaryDirectory() as td:
1038 with TemporaryDirectory() as td:
1039 try:
1039 try:
1040 with tt.AssertPrints(re.compile("Activating.*")):
1040 with tt.AssertPrints(re.compile("Activating.*")):
1041 lm.logstart(os.path.join(td, "not_quiet.log"))
1041 lm.logstart(os.path.join(td, "not_quiet.log"))
1042 finally:
1042 finally:
1043 _ip.logger.logstop()
1043 _ip.logger.logstop()
1044
1044
General Comments 0
You need to be logged in to leave comments. Login now