##// END OF EJS Templates
Add experimental support for cell-based execution....
Fernando Perez -
Show More
@@ -1,868 +1,954 b''
1 """Analysis of text input into executable blocks.
1 """Analysis of text input into executable blocks.
2
2
3 The main class in this module, :class:`InputSplitter`, is designed to break
3 The main class in this module, :class:`InputSplitter`, is designed to break
4 input from either interactive, line-by-line environments or block-based ones,
4 input from either interactive, line-by-line environments or block-based ones,
5 into standalone blocks that can be executed by Python as 'single' statements
5 into standalone blocks that can be executed by Python as 'single' statements
6 (thus triggering sys.displayhook).
6 (thus triggering sys.displayhook).
7
7
8 A companion, :class:`IPythonInputSplitter`, provides the same functionality but
8 A companion, :class:`IPythonInputSplitter`, provides the same functionality but
9 with full support for the extended IPython syntax (magics, system calls, etc).
9 with full support for the extended IPython syntax (magics, system calls, etc).
10
10
11 For more details, see the class docstring below.
11 For more details, see the class docstring below.
12
12
13 Syntax Transformations
13 Syntax Transformations
14 ----------------------
14 ----------------------
15
15
16 One of the main jobs of the code in this file is to apply all syntax
16 One of the main jobs of the code in this file is to apply all syntax
17 transformations that make up 'the IPython language', i.e. magics, shell
17 transformations that make up 'the IPython language', i.e. magics, shell
18 escapes, etc. All transformations should be implemented as *fully stateless*
18 escapes, etc. All transformations should be implemented as *fully stateless*
19 entities, that simply take one line as their input and return a line.
19 entities, that simply take one line as their input and return a line.
20 Internally for implementation purposes they may be a normal function or a
20 Internally for implementation purposes they may be a normal function or a
21 callable object, but the only input they receive will be a single line and they
21 callable object, but the only input they receive will be a single line and they
22 should only return a line, without holding any data-dependent state between
22 should only return a line, without holding any data-dependent state between
23 calls.
23 calls.
24
24
25 As an example, the EscapedTransformer is a class so we can more clearly group
25 As an example, the EscapedTransformer is a class so we can more clearly group
26 together the functionality of dispatching to individual functions based on the
26 together the functionality of dispatching to individual functions based on the
27 starting escape character, but the only method for public use is its call
27 starting escape character, but the only method for public use is its call
28 method.
28 method.
29
29
30
30
31 ToDo
31 ToDo
32 ----
32 ----
33
33
34 - Should we make push() actually raise an exception once push_accepts_more()
34 - Should we make push() actually raise an exception once push_accepts_more()
35 returns False?
35 returns False?
36
36
37 - Naming cleanups. The tr_* names aren't the most elegant, though now they are
37 - Naming cleanups. The tr_* names aren't the most elegant, though now they are
38 at least just attributes of a class so not really very exposed.
38 at least just attributes of a class so not really very exposed.
39
39
40 - Think about the best way to support dynamic things: automagic, autocall,
40 - Think about the best way to support dynamic things: automagic, autocall,
41 macros, etc.
41 macros, etc.
42
42
43 - Think of a better heuristic for the application of the transforms in
43 - Think of a better heuristic for the application of the transforms in
44 IPythonInputSplitter.push() than looking at the buffer ending in ':'. Idea:
44 IPythonInputSplitter.push() than looking at the buffer ending in ':'. Idea:
45 track indentation change events (indent, dedent, nothing) and apply them only
45 track indentation change events (indent, dedent, nothing) and apply them only
46 if the indentation went up, but not otherwise.
46 if the indentation went up, but not otherwise.
47
47
48 - Think of the cleanest way for supporting user-specified transformations (the
48 - Think of the cleanest way for supporting user-specified transformations (the
49 user prefilters we had before).
49 user prefilters we had before).
50
50
51 Authors
51 Authors
52 -------
52 -------
53
53
54 * Fernando Perez
54 * Fernando Perez
55 * Brian Granger
55 * Brian Granger
56 """
56 """
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58 # Copyright (C) 2010 The IPython Development Team
58 # Copyright (C) 2010 The IPython Development Team
59 #
59 #
60 # Distributed under the terms of the BSD License. The full license is in
60 # Distributed under the terms of the BSD License. The full license is in
61 # the file COPYING, distributed as part of this software.
61 # the file COPYING, distributed as part of this software.
62 #-----------------------------------------------------------------------------
62 #-----------------------------------------------------------------------------
63
63
64 #-----------------------------------------------------------------------------
64 #-----------------------------------------------------------------------------
65 # Imports
65 # Imports
66 #-----------------------------------------------------------------------------
66 #-----------------------------------------------------------------------------
67 # stdlib
67 # stdlib
68 import codeop
68 import codeop
69 import re
69 import re
70 import sys
70 import sys
71
71
72 # IPython modules
72 # IPython modules
73 from IPython.utils.text import make_quoted_expr
73 from IPython.utils.text import make_quoted_expr
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75 # Globals
75 # Globals
76 #-----------------------------------------------------------------------------
76 #-----------------------------------------------------------------------------
77
77
78 # The escape sequences that define the syntax transformations IPython will
78 # The escape sequences that define the syntax transformations IPython will
79 # apply to user input. These can NOT be just changed here: many regular
79 # apply to user input. These can NOT be just changed here: many regular
80 # expressions and other parts of the code may use their hardcoded values, and
80 # expressions and other parts of the code may use their hardcoded values, and
81 # for all intents and purposes they constitute the 'IPython syntax', so they
81 # for all intents and purposes they constitute the 'IPython syntax', so they
82 # should be considered fixed.
82 # should be considered fixed.
83
83
84 ESC_SHELL = '!'
84 ESC_SHELL = '!'
85 ESC_SH_CAP = '!!'
85 ESC_SH_CAP = '!!'
86 ESC_HELP = '?'
86 ESC_HELP = '?'
87 ESC_HELP2 = '??'
87 ESC_HELP2 = '??'
88 ESC_MAGIC = '%'
88 ESC_MAGIC = '%'
89 ESC_QUOTE = ','
89 ESC_QUOTE = ','
90 ESC_QUOTE2 = ';'
90 ESC_QUOTE2 = ';'
91 ESC_PAREN = '/'
91 ESC_PAREN = '/'
92
92
93 #-----------------------------------------------------------------------------
93 #-----------------------------------------------------------------------------
94 # Utilities
94 # Utilities
95 #-----------------------------------------------------------------------------
95 #-----------------------------------------------------------------------------
96
96
97 # FIXME: These are general-purpose utilities that later can be moved to the
97 # FIXME: These are general-purpose utilities that later can be moved to the
98 # general ward. Kept here for now because we're being very strict about test
98 # general ward. Kept here for now because we're being very strict about test
99 # coverage with this code, and this lets us ensure that we keep 100% coverage
99 # coverage with this code, and this lets us ensure that we keep 100% coverage
100 # while developing.
100 # while developing.
101
101
102 # compiled regexps for autoindent management
102 # compiled regexps for autoindent management
103 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
103 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
104 ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')
104 ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)')
105
105
106
106
107 def num_ini_spaces(s):
107 def num_ini_spaces(s):
108 """Return the number of initial spaces in a string.
108 """Return the number of initial spaces in a string.
109
109
110 Note that tabs are counted as a single space. For now, we do *not* support
110 Note that tabs are counted as a single space. For now, we do *not* support
111 mixing of tabs and spaces in the user's input.
111 mixing of tabs and spaces in the user's input.
112
112
113 Parameters
113 Parameters
114 ----------
114 ----------
115 s : string
115 s : string
116
116
117 Returns
117 Returns
118 -------
118 -------
119 n : int
119 n : int
120 """
120 """
121
121
122 ini_spaces = ini_spaces_re.match(s)
122 ini_spaces = ini_spaces_re.match(s)
123 if ini_spaces:
123 if ini_spaces:
124 return ini_spaces.end()
124 return ini_spaces.end()
125 else:
125 else:
126 return 0
126 return 0
127
127
128
128
129 def remove_comments(src):
129 def remove_comments(src):
130 """Remove all comments from input source.
130 """Remove all comments from input source.
131
131
132 Note: comments are NOT recognized inside of strings!
132 Note: comments are NOT recognized inside of strings!
133
133
134 Parameters
134 Parameters
135 ----------
135 ----------
136 src : string
136 src : string
137 A single or multiline input string.
137 A single or multiline input string.
138
138
139 Returns
139 Returns
140 -------
140 -------
141 String with all Python comments removed.
141 String with all Python comments removed.
142 """
142 """
143
143
144 return re.sub('#.*', '', src)
144 return re.sub('#.*', '', src)
145
145
146
146
147 def get_input_encoding():
147 def get_input_encoding():
148 """Return the default standard input encoding.
148 """Return the default standard input encoding.
149
149
150 If sys.stdin has no encoding, 'ascii' is returned."""
150 If sys.stdin has no encoding, 'ascii' is returned."""
151 # There are strange environments for which sys.stdin.encoding is None. We
151 # There are strange environments for which sys.stdin.encoding is None. We
152 # ensure that a valid encoding is returned.
152 # ensure that a valid encoding is returned.
153 encoding = getattr(sys.stdin, 'encoding', None)
153 encoding = getattr(sys.stdin, 'encoding', None)
154 if encoding is None:
154 if encoding is None:
155 encoding = 'ascii'
155 encoding = 'ascii'
156 return encoding
156 return encoding
157
157
158 #-----------------------------------------------------------------------------
158 #-----------------------------------------------------------------------------
159 # Classes and functions for normal Python syntax handling
159 # Classes and functions for normal Python syntax handling
160 #-----------------------------------------------------------------------------
160 #-----------------------------------------------------------------------------
161
161
162 # HACK! This implementation, written by Robert K a while ago using the
163 # compiler module, is more robust than the other one below, but it expects its
164 # input to be pure python (no ipython syntax). For now we're using it as a
165 # second-pass splitter after the first pass transforms the input to pure
166 # python.
167
168 def split_blocks(python):
169 """ Split multiple lines of code into discrete commands that can be
170 executed singly.
171
172 Parameters
173 ----------
174 python : str
175 Pure, exec'able Python code.
176
177 Returns
178 -------
179 commands : list of str
180 Separate commands that can be exec'ed independently.
181 """
182
183 import compiler
184
185 # compiler.parse treats trailing spaces after a newline as a
186 # SyntaxError. This is different than codeop.CommandCompiler, which
187 # will compile the trailng spaces just fine. We simply strip any
188 # trailing whitespace off. Passing a string with trailing whitespace
189 # to exec will fail however. There seems to be some inconsistency in
190 # how trailing whitespace is handled, but this seems to work.
191 python_ori = python # save original in case we bail on error
192 python = python.strip()
193
194 # The compiler module does not like unicode. We need to convert
195 # it encode it:
196 if isinstance(python, unicode):
197 # Use the utf-8-sig BOM so the compiler detects this a UTF-8
198 # encode string.
199 python = '\xef\xbb\xbf' + python.encode('utf-8')
200
201 # The compiler module will parse the code into an abstract syntax tree.
202 # This has a bug with str("a\nb"), but not str("""a\nb""")!!!
203 try:
204 ast = compiler.parse(python)
205 except:
206 return [python_ori]
207
208 # Uncomment to help debug the ast tree
209 # for n in ast.node:
210 # print n.lineno,'->',n
211
212 # Each separate command is available by iterating over ast.node. The
213 # lineno attribute is the line number (1-indexed) beginning the commands
214 # suite.
215 # lines ending with ";" yield a Discard Node that doesn't have a lineno
216 # attribute. These nodes can and should be discarded. But there are
217 # other situations that cause Discard nodes that shouldn't be discarded.
218 # We might eventually discover other cases where lineno is None and have
219 # to put in a more sophisticated test.
220 linenos = [x.lineno-1 for x in ast.node if x.lineno is not None]
221
222 # When we finally get the slices, we will need to slice all the way to
223 # the end even though we don't have a line number for it. Fortunately,
224 # None does the job nicely.
225 linenos.append(None)
226
227 # Same problem at the other end: sometimes the ast tree has its
228 # first complete statement not starting on line 0. In this case
229 # we might miss part of it. This fixes ticket 266993. Thanks Gael!
230 linenos[0] = 0
231
232 lines = python.splitlines()
233
234 # Create a list of atomic commands.
235 cmds = []
236 for i, j in zip(linenos[:-1], linenos[1:]):
237 cmd = lines[i:j]
238 if cmd:
239 cmds.append('\n'.join(cmd)+'\n')
240
241 return cmds
242
243
162 class InputSplitter(object):
244 class InputSplitter(object):
163 """An object that can split Python source input in executable blocks.
245 """An object that can split Python source input in executable blocks.
164
246
165 This object is designed to be used in one of two basic modes:
247 This object is designed to be used in one of two basic modes:
166
248
167 1. By feeding it python source line-by-line, using :meth:`push`. In this
249 1. By feeding it python source line-by-line, using :meth:`push`. In this
168 mode, it will return on each push whether the currently pushed code
250 mode, it will return on each push whether the currently pushed code
169 could be executed already. In addition, it provides a method called
251 could be executed already. In addition, it provides a method called
170 :meth:`push_accepts_more` that can be used to query whether more input
252 :meth:`push_accepts_more` that can be used to query whether more input
171 can be pushed into a single interactive block.
253 can be pushed into a single interactive block.
172
254
173 2. By calling :meth:`split_blocks` with a single, multiline Python string,
255 2. By calling :meth:`split_blocks` with a single, multiline Python string,
174 that is then split into blocks each of which can be executed
256 that is then split into blocks each of which can be executed
175 interactively as a single statement.
257 interactively as a single statement.
176
258
177 This is a simple example of how an interactive terminal-based client can use
259 This is a simple example of how an interactive terminal-based client can use
178 this tool::
260 this tool::
179
261
180 isp = InputSplitter()
262 isp = InputSplitter()
181 while isp.push_accepts_more():
263 while isp.push_accepts_more():
182 indent = ' '*isp.indent_spaces
264 indent = ' '*isp.indent_spaces
183 prompt = '>>> ' + indent
265 prompt = '>>> ' + indent
184 line = indent + raw_input(prompt)
266 line = indent + raw_input(prompt)
185 isp.push(line)
267 isp.push(line)
186 print 'Input source was:\n', isp.source_reset(),
268 print 'Input source was:\n', isp.source_reset(),
187 """
269 """
188 # Number of spaces of indentation computed from input that has been pushed
270 # Number of spaces of indentation computed from input that has been pushed
189 # so far. This is the attributes callers should query to get the current
271 # so far. This is the attributes callers should query to get the current
190 # indentation level, in order to provide auto-indent facilities.
272 # indentation level, in order to provide auto-indent facilities.
191 indent_spaces = 0
273 indent_spaces = 0
192 # String, indicating the default input encoding. It is computed by default
274 # String, indicating the default input encoding. It is computed by default
193 # at initialization time via get_input_encoding(), but it can be reset by a
275 # at initialization time via get_input_encoding(), but it can be reset by a
194 # client with specific knowledge of the encoding.
276 # client with specific knowledge of the encoding.
195 encoding = ''
277 encoding = ''
196 # String where the current full source input is stored, properly encoded.
278 # String where the current full source input is stored, properly encoded.
197 # Reading this attribute is the normal way of querying the currently pushed
279 # Reading this attribute is the normal way of querying the currently pushed
198 # source code, that has been properly encoded.
280 # source code, that has been properly encoded.
199 source = ''
281 source = ''
200 # Code object corresponding to the current source. It is automatically
282 # Code object corresponding to the current source. It is automatically
201 # synced to the source, so it can be queried at any time to obtain the code
283 # synced to the source, so it can be queried at any time to obtain the code
202 # object; it will be None if the source doesn't compile to valid Python.
284 # object; it will be None if the source doesn't compile to valid Python.
203 code = None
285 code = None
204 # Input mode
286 # Input mode
205 input_mode = 'line'
287 input_mode = 'line'
206
288
207 # Private attributes
289 # Private attributes
208
290
209 # List with lines of input accumulated so far
291 # List with lines of input accumulated so far
210 _buffer = None
292 _buffer = None
211 # Command compiler
293 # Command compiler
212 _compile = None
294 _compile = None
213 # Mark when input has changed indentation all the way back to flush-left
295 # Mark when input has changed indentation all the way back to flush-left
214 _full_dedent = False
296 _full_dedent = False
215 # Boolean indicating whether the current block is complete
297 # Boolean indicating whether the current block is complete
216 _is_complete = None
298 _is_complete = None
217
299
218 def __init__(self, input_mode=None):
300 def __init__(self, input_mode=None):
219 """Create a new InputSplitter instance.
301 """Create a new InputSplitter instance.
220
302
221 Parameters
303 Parameters
222 ----------
304 ----------
223 input_mode : str
305 input_mode : str
224
306
225 One of ['line', 'block']; default is 'line'.
307 One of ['line', 'block']; default is 'line'.
226
308
227 The input_mode parameter controls how new inputs are used when fed via
309 The input_mode parameter controls how new inputs are used when fed via
228 the :meth:`push` method:
310 the :meth:`push` method:
229
311
230 - 'line': meant for line-oriented clients, inputs are appended one at a
312 - 'line': meant for line-oriented clients, inputs are appended one at a
231 time to the internal buffer and the whole buffer is compiled.
313 time to the internal buffer and the whole buffer is compiled.
232
314
233 - 'block': meant for clients that can edit multi-line blocks of text at
315 - 'block': meant for clients that can edit multi-line blocks of text at
234 a time. Each new input new input completely replaces all prior
316 a time. Each new input new input completely replaces all prior
235 inputs. Block mode is thus equivalent to prepending a full reset()
317 inputs. Block mode is thus equivalent to prepending a full reset()
236 to every push() call.
318 to every push() call.
237 """
319 """
238 self._buffer = []
320 self._buffer = []
239 self._compile = codeop.CommandCompiler()
321 self._compile = codeop.CommandCompiler()
240 self.encoding = get_input_encoding()
322 self.encoding = get_input_encoding()
241 self.input_mode = InputSplitter.input_mode if input_mode is None \
323 self.input_mode = InputSplitter.input_mode if input_mode is None \
242 else input_mode
324 else input_mode
243
325
244 def reset(self):
326 def reset(self):
245 """Reset the input buffer and associated state."""
327 """Reset the input buffer and associated state."""
246 self.indent_spaces = 0
328 self.indent_spaces = 0
247 self._buffer[:] = []
329 self._buffer[:] = []
248 self.source = ''
330 self.source = ''
249 self.code = None
331 self.code = None
250 self._is_complete = False
332 self._is_complete = False
251 self._full_dedent = False
333 self._full_dedent = False
252
334
253 def source_reset(self):
335 def source_reset(self):
254 """Return the input source and perform a full reset.
336 """Return the input source and perform a full reset.
255 """
337 """
256 out = self.source
338 out = self.source
257 self.reset()
339 self.reset()
258 return out
340 return out
259
341
260 def push(self, lines):
342 def push(self, lines):
261 """Push one ore more lines of input.
343 """Push one ore more lines of input.
262
344
263 This stores the given lines and returns a status code indicating
345 This stores the given lines and returns a status code indicating
264 whether the code forms a complete Python block or not.
346 whether the code forms a complete Python block or not.
265
347
266 Any exceptions generated in compilation are swallowed, but if an
348 Any exceptions generated in compilation are swallowed, but if an
267 exception was produced, the method returns True.
349 exception was produced, the method returns True.
268
350
269 Parameters
351 Parameters
270 ----------
352 ----------
271 lines : string
353 lines : string
272 One or more lines of Python input.
354 One or more lines of Python input.
273
355
274 Returns
356 Returns
275 -------
357 -------
276 is_complete : boolean
358 is_complete : boolean
277 True if the current input source (the result of the current input
359 True if the current input source (the result of the current input
278 plus prior inputs) forms a complete Python execution block. Note that
360 plus prior inputs) forms a complete Python execution block. Note that
279 this value is also stored as a private attribute (_is_complete), so it
361 this value is also stored as a private attribute (_is_complete), so it
280 can be queried at any time.
362 can be queried at any time.
281 """
363 """
282 if self.input_mode == 'block':
364 if self.input_mode == 'block':
283 self.reset()
365 self.reset()
284
366
285 # If the source code has leading blanks, add 'if 1:\n' to it
367 # If the source code has leading blanks, add 'if 1:\n' to it
286 # this allows execution of indented pasted code. It is tempting
368 # this allows execution of indented pasted code. It is tempting
287 # to add '\n' at the end of source to run commands like ' a=1'
369 # to add '\n' at the end of source to run commands like ' a=1'
288 # directly, but this fails for more complicated scenarios
370 # directly, but this fails for more complicated scenarios
289 if not self._buffer and lines[:1] in [' ', '\t']:
371 if not self._buffer and lines[:1] in [' ', '\t']:
290 lines = 'if 1:\n%s' % lines
372 lines = 'if 1:\n%s' % lines
291
373
292 self._store(lines)
374 self._store(lines)
293 source = self.source
375 source = self.source
294
376
295 # Before calling _compile(), reset the code object to None so that if an
377 # Before calling _compile(), reset the code object to None so that if an
296 # exception is raised in compilation, we don't mislead by having
378 # exception is raised in compilation, we don't mislead by having
297 # inconsistent code/source attributes.
379 # inconsistent code/source attributes.
298 self.code, self._is_complete = None, None
380 self.code, self._is_complete = None, None
299
381
300 self._update_indent(lines)
382 self._update_indent(lines)
301 try:
383 try:
302 self.code = self._compile(source)
384 self.code = self._compile(source)
303 # Invalid syntax can produce any of a number of different errors from
385 # Invalid syntax can produce any of a number of different errors from
304 # inside the compiler, so we have to catch them all. Syntax errors
386 # inside the compiler, so we have to catch them all. Syntax errors
305 # immediately produce a 'ready' block, so the invalid Python can be
387 # immediately produce a 'ready' block, so the invalid Python can be
306 # sent to the kernel for evaluation with possible ipython
388 # sent to the kernel for evaluation with possible ipython
307 # special-syntax conversion.
389 # special-syntax conversion.
308 except (SyntaxError, OverflowError, ValueError, TypeError,
390 except (SyntaxError, OverflowError, ValueError, TypeError,
309 MemoryError):
391 MemoryError):
310 self._is_complete = True
392 self._is_complete = True
311 else:
393 else:
312 # Compilation didn't produce any exceptions (though it may not have
394 # Compilation didn't produce any exceptions (though it may not have
313 # given a complete code object)
395 # given a complete code object)
314 self._is_complete = self.code is not None
396 self._is_complete = self.code is not None
315
397
316 return self._is_complete
398 return self._is_complete
317
399
318 def push_accepts_more(self):
400 def push_accepts_more(self):
319 """Return whether a block of interactive input can accept more input.
401 """Return whether a block of interactive input can accept more input.
320
402
321 This method is meant to be used by line-oriented frontends, who need to
403 This method is meant to be used by line-oriented frontends, who need to
322 guess whether a block is complete or not based solely on prior and
404 guess whether a block is complete or not based solely on prior and
323 current input lines. The InputSplitter considers it has a complete
405 current input lines. The InputSplitter considers it has a complete
324 interactive block and will not accept more input only when either a
406 interactive block and will not accept more input only when either a
325 SyntaxError is raised, or *all* of the following are true:
407 SyntaxError is raised, or *all* of the following are true:
326
408
327 1. The input compiles to a complete statement.
409 1. The input compiles to a complete statement.
328
410
329 2. The indentation level is flush-left (because if we are indented,
411 2. The indentation level is flush-left (because if we are indented,
330 like inside a function definition or for loop, we need to keep
412 like inside a function definition or for loop, we need to keep
331 reading new input).
413 reading new input).
332
414
333 3. There is one extra line consisting only of whitespace.
415 3. There is one extra line consisting only of whitespace.
334
416
335 Because of condition #3, this method should be used only by
417 Because of condition #3, this method should be used only by
336 *line-oriented* frontends, since it means that intermediate blank lines
418 *line-oriented* frontends, since it means that intermediate blank lines
337 are not allowed in function definitions (or any other indented block).
419 are not allowed in function definitions (or any other indented block).
338
420
339 Block-oriented frontends that have a separate keyboard event to
421 Block-oriented frontends that have a separate keyboard event to
340 indicate execution should use the :meth:`split_blocks` method instead.
422 indicate execution should use the :meth:`split_blocks` method instead.
341
423
342 If the current input produces a syntax error, this method immediately
424 If the current input produces a syntax error, this method immediately
343 returns False but does *not* raise the syntax error exception, as
425 returns False but does *not* raise the syntax error exception, as
344 typically clients will want to send invalid syntax to an execution
426 typically clients will want to send invalid syntax to an execution
345 backend which might convert the invalid syntax into valid Python via
427 backend which might convert the invalid syntax into valid Python via
346 one of the dynamic IPython mechanisms.
428 one of the dynamic IPython mechanisms.
347 """
429 """
348
430
349 if not self._is_complete:
431 if not self._is_complete:
350 return True
432 return True
351
433
352 if self.indent_spaces==0:
434 if self.indent_spaces==0:
353 return False
435 return False
354
436
355 last_line = self.source.splitlines()[-1]
437 last_line = self.source.splitlines()[-1]
356 return bool(last_line and not last_line.isspace())
438 return bool(last_line and not last_line.isspace())
357
439
358 def split_blocks(self, lines):
440 def split_blocks(self, lines):
359 """Split a multiline string into multiple input blocks.
441 """Split a multiline string into multiple input blocks.
360
442
361 Note: this method starts by performing a full reset().
443 Note: this method starts by performing a full reset().
362
444
363 Parameters
445 Parameters
364 ----------
446 ----------
365 lines : str
447 lines : str
366 A possibly multiline string.
448 A possibly multiline string.
367
449
368 Returns
450 Returns
369 -------
451 -------
370 blocks : list
452 blocks : list
371 A list of strings, each possibly multiline. Each string corresponds
453 A list of strings, each possibly multiline. Each string corresponds
372 to a single block that can be compiled in 'single' mode (unless it
454 to a single block that can be compiled in 'single' mode (unless it
373 has a syntax error)."""
455 has a syntax error)."""
374
456
375 # This code is fairly delicate. If you make any changes here, make
457 # This code is fairly delicate. If you make any changes here, make
376 # absolutely sure that you do run the full test suite and ALL tests
458 # absolutely sure that you do run the full test suite and ALL tests
377 # pass.
459 # pass.
378
460
379 self.reset()
461 self.reset()
380 blocks = []
462 blocks = []
381
463
382 # Reversed copy so we can use pop() efficiently and consume the input
464 # Reversed copy so we can use pop() efficiently and consume the input
383 # as a stack
465 # as a stack
384 lines = lines.splitlines()[::-1]
466 lines = lines.splitlines()[::-1]
385 # Outer loop over all input
467 # Outer loop over all input
386 while lines:
468 while lines:
387 #print 'Current lines:', lines # dbg
469 #print 'Current lines:', lines # dbg
388 # Inner loop to build each block
470 # Inner loop to build each block
389 while True:
471 while True:
390 # Safety exit from inner loop
472 # Safety exit from inner loop
391 if not lines:
473 if not lines:
392 break
474 break
393 # Grab next line but don't push it yet
475 # Grab next line but don't push it yet
394 next_line = lines.pop()
476 next_line = lines.pop()
395 # Blank/empty lines are pushed as-is
477 # Blank/empty lines are pushed as-is
396 if not next_line or next_line.isspace():
478 if not next_line or next_line.isspace():
397 self.push(next_line)
479 self.push(next_line)
398 continue
480 continue
399
481
400 # Check indentation changes caused by the *next* line
482 # Check indentation changes caused by the *next* line
401 indent_spaces, _full_dedent = self._find_indent(next_line)
483 indent_spaces, _full_dedent = self._find_indent(next_line)
402
484
403 # If the next line causes a dedent, it can be for two differnt
485 # If the next line causes a dedent, it can be for two differnt
404 # reasons: either an explicit de-dent by the user or a
486 # reasons: either an explicit de-dent by the user or a
405 # return/raise/pass statement. These MUST be handled
487 # return/raise/pass statement. These MUST be handled
406 # separately:
488 # separately:
407 #
489 #
408 # 1. the first case is only detected when the actual explicit
490 # 1. the first case is only detected when the actual explicit
409 # dedent happens, and that would be the *first* line of a *new*
491 # dedent happens, and that would be the *first* line of a *new*
410 # block. Thus, we must put the line back into the input buffer
492 # block. Thus, we must put the line back into the input buffer
411 # so that it starts a new block on the next pass.
493 # so that it starts a new block on the next pass.
412 #
494 #
413 # 2. the second case is detected in the line before the actual
495 # 2. the second case is detected in the line before the actual
414 # dedent happens, so , we consume the line and we can break out
496 # dedent happens, so , we consume the line and we can break out
415 # to start a new block.
497 # to start a new block.
416
498
417 # Case 1, explicit dedent causes a break.
499 # Case 1, explicit dedent causes a break.
418 # Note: check that we weren't on the very last line, else we'll
500 # Note: check that we weren't on the very last line, else we'll
419 # enter an infinite loop adding/removing the last line.
501 # enter an infinite loop adding/removing the last line.
420 if _full_dedent and lines and not next_line.startswith(' '):
502 if _full_dedent and lines and not next_line.startswith(' '):
421 lines.append(next_line)
503 lines.append(next_line)
422 break
504 break
423
505
424 # Otherwise any line is pushed
506 # Otherwise any line is pushed
425 self.push(next_line)
507 self.push(next_line)
426
508
427 # Case 2, full dedent with full block ready:
509 # Case 2, full dedent with full block ready:
428 if _full_dedent or \
510 if _full_dedent or \
429 self.indent_spaces==0 and not self.push_accepts_more():
511 self.indent_spaces==0 and not self.push_accepts_more():
430 break
512 break
431 # Form the new block with the current source input
513 # Form the new block with the current source input
432 blocks.append(self.source_reset())
514 blocks.append(self.source_reset())
433
515
434 return blocks
516 #return blocks
517 # HACK!!! Now that our input is in blocks but guaranteed to be pure
518 # python syntax, feed it back a second time through the AST-based
519 # splitter, which is more accurate than ours.
520 return split_blocks(''.join(blocks))
435
521
436 #------------------------------------------------------------------------
522 #------------------------------------------------------------------------
437 # Private interface
523 # Private interface
438 #------------------------------------------------------------------------
524 #------------------------------------------------------------------------
439
525
440 def _find_indent(self, line):
526 def _find_indent(self, line):
441 """Compute the new indentation level for a single line.
527 """Compute the new indentation level for a single line.
442
528
443 Parameters
529 Parameters
444 ----------
530 ----------
445 line : str
531 line : str
446 A single new line of non-whitespace, non-comment Python input.
532 A single new line of non-whitespace, non-comment Python input.
447
533
448 Returns
534 Returns
449 -------
535 -------
450 indent_spaces : int
536 indent_spaces : int
451 New value for the indent level (it may be equal to self.indent_spaces
537 New value for the indent level (it may be equal to self.indent_spaces
452 if indentation doesn't change.
538 if indentation doesn't change.
453
539
454 full_dedent : boolean
540 full_dedent : boolean
455 Whether the new line causes a full flush-left dedent.
541 Whether the new line causes a full flush-left dedent.
456 """
542 """
457 indent_spaces = self.indent_spaces
543 indent_spaces = self.indent_spaces
458 full_dedent = self._full_dedent
544 full_dedent = self._full_dedent
459
545
460 inisp = num_ini_spaces(line)
546 inisp = num_ini_spaces(line)
461 if inisp < indent_spaces:
547 if inisp < indent_spaces:
462 indent_spaces = inisp
548 indent_spaces = inisp
463 if indent_spaces <= 0:
549 if indent_spaces <= 0:
464 #print 'Full dedent in text',self.source # dbg
550 #print 'Full dedent in text',self.source # dbg
465 full_dedent = True
551 full_dedent = True
466
552
467 if line[-1] == ':':
553 if line[-1] == ':':
468 indent_spaces += 4
554 indent_spaces += 4
469 elif dedent_re.match(line):
555 elif dedent_re.match(line):
470 indent_spaces -= 4
556 indent_spaces -= 4
471 if indent_spaces <= 0:
557 if indent_spaces <= 0:
472 full_dedent = True
558 full_dedent = True
473
559
474 # Safety
560 # Safety
475 if indent_spaces < 0:
561 if indent_spaces < 0:
476 indent_spaces = 0
562 indent_spaces = 0
477 #print 'safety' # dbg
563 #print 'safety' # dbg
478
564
479 return indent_spaces, full_dedent
565 return indent_spaces, full_dedent
480
566
481 def _update_indent(self, lines):
567 def _update_indent(self, lines):
482 for line in remove_comments(lines).splitlines():
568 for line in remove_comments(lines).splitlines():
483 if line and not line.isspace():
569 if line and not line.isspace():
484 self.indent_spaces, self._full_dedent = self._find_indent(line)
570 self.indent_spaces, self._full_dedent = self._find_indent(line)
485
571
486 def _store(self, lines):
572 def _store(self, lines):
487 """Store one or more lines of input.
573 """Store one or more lines of input.
488
574
489 If input lines are not newline-terminated, a newline is automatically
575 If input lines are not newline-terminated, a newline is automatically
490 appended."""
576 appended."""
491
577
492 if lines.endswith('\n'):
578 if lines.endswith('\n'):
493 self._buffer.append(lines)
579 self._buffer.append(lines)
494 else:
580 else:
495 self._buffer.append(lines+'\n')
581 self._buffer.append(lines+'\n')
496 self._set_source()
582 self._set_source()
497
583
498 def _set_source(self):
584 def _set_source(self):
499 self.source = ''.join(self._buffer).encode(self.encoding)
585 self.source = ''.join(self._buffer).encode(self.encoding)
500
586
501
587
502 #-----------------------------------------------------------------------------
588 #-----------------------------------------------------------------------------
503 # Functions and classes for IPython-specific syntactic support
589 # Functions and classes for IPython-specific syntactic support
504 #-----------------------------------------------------------------------------
590 #-----------------------------------------------------------------------------
505
591
506 # RegExp for splitting line contents into pre-char//first word-method//rest.
592 # RegExp for splitting line contents into pre-char//first word-method//rest.
507 # For clarity, each group in on one line.
593 # For clarity, each group in on one line.
508
594
509 line_split = re.compile("""
595 line_split = re.compile("""
510 ^(\s*) # any leading space
596 ^(\s*) # any leading space
511 ([,;/%]|!!?|\?\??) # escape character or characters
597 ([,;/%]|!!?|\?\??) # escape character or characters
512 \s*(%?[\w\.]*) # function/method, possibly with leading %
598 \s*(%?[\w\.]*) # function/method, possibly with leading %
513 # to correctly treat things like '?%magic'
599 # to correctly treat things like '?%magic'
514 (\s+.*$|$) # rest of line
600 (\s+.*$|$) # rest of line
515 """, re.VERBOSE)
601 """, re.VERBOSE)
516
602
517
603
518 def split_user_input(line):
604 def split_user_input(line):
519 """Split user input into early whitespace, esc-char, function part and rest.
605 """Split user input into early whitespace, esc-char, function part and rest.
520
606
521 This is currently handles lines with '=' in them in a very inconsistent
607 This is currently handles lines with '=' in them in a very inconsistent
522 manner.
608 manner.
523
609
524 Examples
610 Examples
525 ========
611 ========
526 >>> split_user_input('x=1')
612 >>> split_user_input('x=1')
527 ('', '', 'x=1', '')
613 ('', '', 'x=1', '')
528 >>> split_user_input('?')
614 >>> split_user_input('?')
529 ('', '?', '', '')
615 ('', '?', '', '')
530 >>> split_user_input('??')
616 >>> split_user_input('??')
531 ('', '??', '', '')
617 ('', '??', '', '')
532 >>> split_user_input(' ?')
618 >>> split_user_input(' ?')
533 (' ', '?', '', '')
619 (' ', '?', '', '')
534 >>> split_user_input(' ??')
620 >>> split_user_input(' ??')
535 (' ', '??', '', '')
621 (' ', '??', '', '')
536 >>> split_user_input('??x')
622 >>> split_user_input('??x')
537 ('', '??', 'x', '')
623 ('', '??', 'x', '')
538 >>> split_user_input('?x=1')
624 >>> split_user_input('?x=1')
539 ('', '', '?x=1', '')
625 ('', '', '?x=1', '')
540 >>> split_user_input('!ls')
626 >>> split_user_input('!ls')
541 ('', '!', 'ls', '')
627 ('', '!', 'ls', '')
542 >>> split_user_input(' !ls')
628 >>> split_user_input(' !ls')
543 (' ', '!', 'ls', '')
629 (' ', '!', 'ls', '')
544 >>> split_user_input('!!ls')
630 >>> split_user_input('!!ls')
545 ('', '!!', 'ls', '')
631 ('', '!!', 'ls', '')
546 >>> split_user_input(' !!ls')
632 >>> split_user_input(' !!ls')
547 (' ', '!!', 'ls', '')
633 (' ', '!!', 'ls', '')
548 >>> split_user_input(',ls')
634 >>> split_user_input(',ls')
549 ('', ',', 'ls', '')
635 ('', ',', 'ls', '')
550 >>> split_user_input(';ls')
636 >>> split_user_input(';ls')
551 ('', ';', 'ls', '')
637 ('', ';', 'ls', '')
552 >>> split_user_input(' ;ls')
638 >>> split_user_input(' ;ls')
553 (' ', ';', 'ls', '')
639 (' ', ';', 'ls', '')
554 >>> split_user_input('f.g(x)')
640 >>> split_user_input('f.g(x)')
555 ('', '', 'f.g(x)', '')
641 ('', '', 'f.g(x)', '')
556 >>> split_user_input('f.g (x)')
642 >>> split_user_input('f.g (x)')
557 ('', '', 'f.g', '(x)')
643 ('', '', 'f.g', '(x)')
558 >>> split_user_input('?%hist')
644 >>> split_user_input('?%hist')
559 ('', '?', '%hist', '')
645 ('', '?', '%hist', '')
560 """
646 """
561 match = line_split.match(line)
647 match = line_split.match(line)
562 if match:
648 if match:
563 lspace, esc, fpart, rest = match.groups()
649 lspace, esc, fpart, rest = match.groups()
564 else:
650 else:
565 # print "match failed for line '%s'" % line
651 # print "match failed for line '%s'" % line
566 try:
652 try:
567 fpart, rest = line.split(None, 1)
653 fpart, rest = line.split(None, 1)
568 except ValueError:
654 except ValueError:
569 # print "split failed for line '%s'" % line
655 # print "split failed for line '%s'" % line
570 fpart, rest = line,''
656 fpart, rest = line,''
571 lspace = re.match('^(\s*)(.*)', line).groups()[0]
657 lspace = re.match('^(\s*)(.*)', line).groups()[0]
572 esc = ''
658 esc = ''
573
659
574 # fpart has to be a valid python identifier, so it better be only pure
660 # fpart has to be a valid python identifier, so it better be only pure
575 # ascii, no unicode:
661 # ascii, no unicode:
576 try:
662 try:
577 fpart = fpart.encode('ascii')
663 fpart = fpart.encode('ascii')
578 except UnicodeEncodeError:
664 except UnicodeEncodeError:
579 lspace = unicode(lspace)
665 lspace = unicode(lspace)
580 rest = fpart + u' ' + rest
666 rest = fpart + u' ' + rest
581 fpart = u''
667 fpart = u''
582
668
583 #print 'line:<%s>' % line # dbg
669 #print 'line:<%s>' % line # dbg
584 #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg
670 #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg
585 return lspace, esc, fpart.strip(), rest.lstrip()
671 return lspace, esc, fpart.strip(), rest.lstrip()
586
672
587
673
588 # The escaped translators ALL receive a line where their own escape has been
674 # The escaped translators ALL receive a line where their own escape has been
589 # stripped. Only '?' is valid at the end of the line, all others can only be
675 # stripped. Only '?' is valid at the end of the line, all others can only be
590 # placed at the start.
676 # placed at the start.
591
677
592 class LineInfo(object):
678 class LineInfo(object):
593 """A single line of input and associated info.
679 """A single line of input and associated info.
594
680
595 This is a utility class that mostly wraps the output of
681 This is a utility class that mostly wraps the output of
596 :func:`split_user_input` into a convenient object to be passed around
682 :func:`split_user_input` into a convenient object to be passed around
597 during input transformations.
683 during input transformations.
598
684
599 Includes the following as properties:
685 Includes the following as properties:
600
686
601 line
687 line
602 The original, raw line
688 The original, raw line
603
689
604 lspace
690 lspace
605 Any early whitespace before actual text starts.
691 Any early whitespace before actual text starts.
606
692
607 esc
693 esc
608 The initial esc character (or characters, for double-char escapes like
694 The initial esc character (or characters, for double-char escapes like
609 '??' or '!!').
695 '??' or '!!').
610
696
611 fpart
697 fpart
612 The 'function part', which is basically the maximal initial sequence
698 The 'function part', which is basically the maximal initial sequence
613 of valid python identifiers and the '.' character. This is what is
699 of valid python identifiers and the '.' character. This is what is
614 checked for alias and magic transformations, used for auto-calling,
700 checked for alias and magic transformations, used for auto-calling,
615 etc.
701 etc.
616
702
617 rest
703 rest
618 Everything else on the line.
704 Everything else on the line.
619 """
705 """
620 def __init__(self, line):
706 def __init__(self, line):
621 self.line = line
707 self.line = line
622 self.lspace, self.esc, self.fpart, self.rest = \
708 self.lspace, self.esc, self.fpart, self.rest = \
623 split_user_input(line)
709 split_user_input(line)
624
710
625 def __str__(self):
711 def __str__(self):
626 return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc,
712 return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc,
627 self.fpart, self.rest)
713 self.fpart, self.rest)
628
714
629
715
630 # Transformations of the special syntaxes that don't rely on an explicit escape
716 # Transformations of the special syntaxes that don't rely on an explicit escape
631 # character but instead on patterns on the input line
717 # character but instead on patterns on the input line
632
718
633 # The core transformations are implemented as standalone functions that can be
719 # The core transformations are implemented as standalone functions that can be
634 # tested and validated in isolation. Each of these uses a regexp, we
720 # tested and validated in isolation. Each of these uses a regexp, we
635 # pre-compile these and keep them close to each function definition for clarity
721 # pre-compile these and keep them close to each function definition for clarity
636
722
637 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
723 _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
638 r'\s*=\s*!\s*(?P<cmd>.*)')
724 r'\s*=\s*!\s*(?P<cmd>.*)')
639
725
640 def transform_assign_system(line):
726 def transform_assign_system(line):
641 """Handle the `files = !ls` syntax."""
727 """Handle the `files = !ls` syntax."""
642 # FIXME: This transforms the line to use %sc, but we've listed that magic
728 # FIXME: This transforms the line to use %sc, but we've listed that magic
643 # as deprecated. We should then implement this functionality in a
729 # as deprecated. We should then implement this functionality in a
644 # standalone api that we can transform to, without going through a
730 # standalone api that we can transform to, without going through a
645 # deprecated magic.
731 # deprecated magic.
646 m = _assign_system_re.match(line)
732 m = _assign_system_re.match(line)
647 if m is not None:
733 if m is not None:
648 cmd = m.group('cmd')
734 cmd = m.group('cmd')
649 lhs = m.group('lhs')
735 lhs = m.group('lhs')
650 expr = make_quoted_expr("sc -l = %s" % cmd)
736 expr = make_quoted_expr("sc -l = %s" % cmd)
651 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
737 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
652 return new_line
738 return new_line
653 return line
739 return line
654
740
655
741
656 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
742 _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
657 r'\s*=\s*%\s*(?P<cmd>.*)')
743 r'\s*=\s*%\s*(?P<cmd>.*)')
658
744
659 def transform_assign_magic(line):
745 def transform_assign_magic(line):
660 """Handle the `a = %who` syntax."""
746 """Handle the `a = %who` syntax."""
661 m = _assign_magic_re.match(line)
747 m = _assign_magic_re.match(line)
662 if m is not None:
748 if m is not None:
663 cmd = m.group('cmd')
749 cmd = m.group('cmd')
664 lhs = m.group('lhs')
750 lhs = m.group('lhs')
665 expr = make_quoted_expr(cmd)
751 expr = make_quoted_expr(cmd)
666 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
752 new_line = '%s = get_ipython().magic(%s)' % (lhs, expr)
667 return new_line
753 return new_line
668 return line
754 return line
669
755
670
756
671 _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )')
757 _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )')
672
758
673 def transform_classic_prompt(line):
759 def transform_classic_prompt(line):
674 """Handle inputs that start with '>>> ' syntax."""
760 """Handle inputs that start with '>>> ' syntax."""
675
761
676 if not line or line.isspace():
762 if not line or line.isspace():
677 return line
763 return line
678 m = _classic_prompt_re.match(line)
764 m = _classic_prompt_re.match(line)
679 if m:
765 if m:
680 return line[len(m.group(0)):]
766 return line[len(m.group(0)):]
681 else:
767 else:
682 return line
768 return line
683
769
684
770
685 _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
771 _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )')
686
772
687 def transform_ipy_prompt(line):
773 def transform_ipy_prompt(line):
688 """Handle inputs that start classic IPython prompt syntax."""
774 """Handle inputs that start classic IPython prompt syntax."""
689
775
690 if not line or line.isspace():
776 if not line or line.isspace():
691 return line
777 return line
692 #print 'LINE: %r' % line # dbg
778 #print 'LINE: %r' % line # dbg
693 m = _ipy_prompt_re.match(line)
779 m = _ipy_prompt_re.match(line)
694 if m:
780 if m:
695 #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
781 #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg
696 return line[len(m.group(0)):]
782 return line[len(m.group(0)):]
697 else:
783 else:
698 return line
784 return line
699
785
700
786
701 class EscapedTransformer(object):
787 class EscapedTransformer(object):
702 """Class to transform lines that are explicitly escaped out."""
788 """Class to transform lines that are explicitly escaped out."""
703
789
704 def __init__(self):
790 def __init__(self):
705 tr = { ESC_SHELL : self._tr_system,
791 tr = { ESC_SHELL : self._tr_system,
706 ESC_SH_CAP : self._tr_system2,
792 ESC_SH_CAP : self._tr_system2,
707 ESC_HELP : self._tr_help,
793 ESC_HELP : self._tr_help,
708 ESC_HELP2 : self._tr_help,
794 ESC_HELP2 : self._tr_help,
709 ESC_MAGIC : self._tr_magic,
795 ESC_MAGIC : self._tr_magic,
710 ESC_QUOTE : self._tr_quote,
796 ESC_QUOTE : self._tr_quote,
711 ESC_QUOTE2 : self._tr_quote2,
797 ESC_QUOTE2 : self._tr_quote2,
712 ESC_PAREN : self._tr_paren }
798 ESC_PAREN : self._tr_paren }
713 self.tr = tr
799 self.tr = tr
714
800
715 # Support for syntax transformations that use explicit escapes typed by the
801 # Support for syntax transformations that use explicit escapes typed by the
716 # user at the beginning of a line
802 # user at the beginning of a line
717 @staticmethod
803 @staticmethod
718 def _tr_system(line_info):
804 def _tr_system(line_info):
719 "Translate lines escaped with: !"
805 "Translate lines escaped with: !"
720 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
806 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
721 return '%sget_ipython().system(%s)' % (line_info.lspace,
807 return '%sget_ipython().system(%s)' % (line_info.lspace,
722 make_quoted_expr(cmd))
808 make_quoted_expr(cmd))
723
809
724 @staticmethod
810 @staticmethod
725 def _tr_system2(line_info):
811 def _tr_system2(line_info):
726 "Translate lines escaped with: !!"
812 "Translate lines escaped with: !!"
727 cmd = line_info.line.lstrip()[2:]
813 cmd = line_info.line.lstrip()[2:]
728 return '%sget_ipython().getoutput(%s)' % (line_info.lspace,
814 return '%sget_ipython().getoutput(%s)' % (line_info.lspace,
729 make_quoted_expr(cmd))
815 make_quoted_expr(cmd))
730
816
731 @staticmethod
817 @staticmethod
732 def _tr_help(line_info):
818 def _tr_help(line_info):
733 "Translate lines escaped with: ?/??"
819 "Translate lines escaped with: ?/??"
734 # A naked help line should just fire the intro help screen
820 # A naked help line should just fire the intro help screen
735 if not line_info.line[1:]:
821 if not line_info.line[1:]:
736 return 'get_ipython().show_usage()'
822 return 'get_ipython().show_usage()'
737
823
738 # There may be one or two '?' at the end, move them to the front so that
824 # There may be one or two '?' at the end, move them to the front so that
739 # the rest of the logic can assume escapes are at the start
825 # the rest of the logic can assume escapes are at the start
740 line = line_info.line
826 line = line_info.line
741 if line.endswith('?'):
827 if line.endswith('?'):
742 line = line[-1] + line[:-1]
828 line = line[-1] + line[:-1]
743 if line.endswith('?'):
829 if line.endswith('?'):
744 line = line[-1] + line[:-1]
830 line = line[-1] + line[:-1]
745 line_info = LineInfo(line)
831 line_info = LineInfo(line)
746
832
747 # From here on, simply choose which level of detail to get.
833 # From here on, simply choose which level of detail to get.
748 if line_info.esc == '?':
834 if line_info.esc == '?':
749 pinfo = 'pinfo'
835 pinfo = 'pinfo'
750 elif line_info.esc == '??':
836 elif line_info.esc == '??':
751 pinfo = 'pinfo2'
837 pinfo = 'pinfo2'
752
838
753 tpl = '%sget_ipython().magic("%s %s")'
839 tpl = '%sget_ipython().magic("%s %s")'
754 return tpl % (line_info.lspace, pinfo,
840 return tpl % (line_info.lspace, pinfo,
755 ' '.join([line_info.fpart, line_info.rest]).strip())
841 ' '.join([line_info.fpart, line_info.rest]).strip())
756
842
757 @staticmethod
843 @staticmethod
758 def _tr_magic(line_info):
844 def _tr_magic(line_info):
759 "Translate lines escaped with: %"
845 "Translate lines escaped with: %"
760 tpl = '%sget_ipython().magic(%s)'
846 tpl = '%sget_ipython().magic(%s)'
761 cmd = make_quoted_expr(' '.join([line_info.fpart,
847 cmd = make_quoted_expr(' '.join([line_info.fpart,
762 line_info.rest]).strip())
848 line_info.rest]).strip())
763 return tpl % (line_info.lspace, cmd)
849 return tpl % (line_info.lspace, cmd)
764
850
765 @staticmethod
851 @staticmethod
766 def _tr_quote(line_info):
852 def _tr_quote(line_info):
767 "Translate lines escaped with: ,"
853 "Translate lines escaped with: ,"
768 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
854 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
769 '", "'.join(line_info.rest.split()) )
855 '", "'.join(line_info.rest.split()) )
770
856
771 @staticmethod
857 @staticmethod
772 def _tr_quote2(line_info):
858 def _tr_quote2(line_info):
773 "Translate lines escaped with: ;"
859 "Translate lines escaped with: ;"
774 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
860 return '%s%s("%s")' % (line_info.lspace, line_info.fpart,
775 line_info.rest)
861 line_info.rest)
776
862
777 @staticmethod
863 @staticmethod
778 def _tr_paren(line_info):
864 def _tr_paren(line_info):
779 "Translate lines escaped with: /"
865 "Translate lines escaped with: /"
780 return '%s%s(%s)' % (line_info.lspace, line_info.fpart,
866 return '%s%s(%s)' % (line_info.lspace, line_info.fpart,
781 ", ".join(line_info.rest.split()))
867 ", ".join(line_info.rest.split()))
782
868
783 def __call__(self, line):
869 def __call__(self, line):
784 """Class to transform lines that are explicitly escaped out.
870 """Class to transform lines that are explicitly escaped out.
785
871
786 This calls the above _tr_* static methods for the actual line
872 This calls the above _tr_* static methods for the actual line
787 translations."""
873 translations."""
788
874
789 # Empty lines just get returned unmodified
875 # Empty lines just get returned unmodified
790 if not line or line.isspace():
876 if not line or line.isspace():
791 return line
877 return line
792
878
793 # Get line endpoints, where the escapes can be
879 # Get line endpoints, where the escapes can be
794 line_info = LineInfo(line)
880 line_info = LineInfo(line)
795
881
796 # If the escape is not at the start, only '?' needs to be special-cased.
882 # If the escape is not at the start, only '?' needs to be special-cased.
797 # All other escapes are only valid at the start
883 # All other escapes are only valid at the start
798 if not line_info.esc in self.tr:
884 if not line_info.esc in self.tr:
799 if line.endswith(ESC_HELP):
885 if line.endswith(ESC_HELP):
800 return self._tr_help(line_info)
886 return self._tr_help(line_info)
801 else:
887 else:
802 # If we don't recognize the escape, don't modify the line
888 # If we don't recognize the escape, don't modify the line
803 return line
889 return line
804
890
805 return self.tr[line_info.esc](line_info)
891 return self.tr[line_info.esc](line_info)
806
892
807
893
808 # A function-looking object to be used by the rest of the code. The purpose of
894 # A function-looking object to be used by the rest of the code. The purpose of
809 # the class in this case is to organize related functionality, more than to
895 # the class in this case is to organize related functionality, more than to
810 # manage state.
896 # manage state.
811 transform_escaped = EscapedTransformer()
897 transform_escaped = EscapedTransformer()
812
898
813
899
814 class IPythonInputSplitter(InputSplitter):
900 class IPythonInputSplitter(InputSplitter):
815 """An input splitter that recognizes all of IPython's special syntax."""
901 """An input splitter that recognizes all of IPython's special syntax."""
816
902
817 def push(self, lines):
903 def push(self, lines):
818 """Push one or more lines of IPython input.
904 """Push one or more lines of IPython input.
819 """
905 """
820 if not lines:
906 if not lines:
821 return super(IPythonInputSplitter, self).push(lines)
907 return super(IPythonInputSplitter, self).push(lines)
822
908
823 lines_list = lines.splitlines()
909 lines_list = lines.splitlines()
824
910
825 transforms = [transform_escaped, transform_assign_system,
911 transforms = [transform_escaped, transform_assign_system,
826 transform_assign_magic, transform_ipy_prompt,
912 transform_assign_magic, transform_ipy_prompt,
827 transform_classic_prompt]
913 transform_classic_prompt]
828
914
829 # Transform logic
915 # Transform logic
830 #
916 #
831 # We only apply the line transformers to the input if we have either no
917 # We only apply the line transformers to the input if we have either no
832 # input yet, or complete input, or if the last line of the buffer ends
918 # input yet, or complete input, or if the last line of the buffer ends
833 # with ':' (opening an indented block). This prevents the accidental
919 # with ':' (opening an indented block). This prevents the accidental
834 # transformation of escapes inside multiline expressions like
920 # transformation of escapes inside multiline expressions like
835 # triple-quoted strings or parenthesized expressions.
921 # triple-quoted strings or parenthesized expressions.
836 #
922 #
837 # The last heuristic, while ugly, ensures that the first line of an
923 # The last heuristic, while ugly, ensures that the first line of an
838 # indented block is correctly transformed.
924 # indented block is correctly transformed.
839 #
925 #
840 # FIXME: try to find a cleaner approach for this last bit.
926 # FIXME: try to find a cleaner approach for this last bit.
841
927
842 # If we were in 'block' mode, since we're going to pump the parent
928 # If we were in 'block' mode, since we're going to pump the parent
843 # class by hand line by line, we need to temporarily switch out to
929 # class by hand line by line, we need to temporarily switch out to
844 # 'line' mode, do a single manual reset and then feed the lines one
930 # 'line' mode, do a single manual reset and then feed the lines one
845 # by one. Note that this only matters if the input has more than one
931 # by one. Note that this only matters if the input has more than one
846 # line.
932 # line.
847 changed_input_mode = False
933 changed_input_mode = False
848
934
849 if len(lines_list)>1 and self.input_mode == 'block':
935 if len(lines_list)>1 and self.input_mode == 'block':
850 self.reset()
936 self.reset()
851 changed_input_mode = True
937 changed_input_mode = True
852 saved_input_mode = 'block'
938 saved_input_mode = 'block'
853 self.input_mode = 'line'
939 self.input_mode = 'line'
854
940
855 try:
941 try:
856 push = super(IPythonInputSplitter, self).push
942 push = super(IPythonInputSplitter, self).push
857 for line in lines_list:
943 for line in lines_list:
858 if self._is_complete or not self._buffer or \
944 if self._is_complete or not self._buffer or \
859 (self._buffer and self._buffer[-1].rstrip().endswith(':')):
945 (self._buffer and self._buffer[-1].rstrip().endswith(':')):
860 for f in transforms:
946 for f in transforms:
861 line = f(line)
947 line = f(line)
862
948
863 out = push(line)
949 out = push(line)
864 finally:
950 finally:
865 if changed_input_mode:
951 if changed_input_mode:
866 self.input_mode = saved_input_mode
952 self.input_mode = saved_input_mode
867
953
868 return out
954 return out
@@ -1,2403 +1,2449 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-2010 The IPython Development Team
7 # Copyright (C) 2008-2010 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 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16
16
17 from __future__ import with_statement
17 from __future__ import with_statement
18 from __future__ import absolute_import
18 from __future__ import absolute_import
19
19
20 import __builtin__
20 import __builtin__
21 import __future__
21 import __future__
22 import abc
22 import abc
23 import atexit
23 import atexit
24 import codeop
24 import codeop
25 import exceptions
25 import exceptions
26 import new
26 import new
27 import os
27 import os
28 import re
28 import re
29 import string
29 import string
30 import sys
30 import sys
31 import tempfile
31 import tempfile
32 from contextlib import nested
32 from contextlib import nested
33
33
34 from IPython.config.configurable import Configurable
34 from IPython.config.configurable import Configurable
35 from IPython.core import debugger, oinspect
35 from IPython.core import debugger, oinspect
36 from IPython.core import history as ipcorehist
36 from IPython.core import history as ipcorehist
37 from IPython.core import page
37 from IPython.core import page
38 from IPython.core import prefilter
38 from IPython.core import prefilter
39 from IPython.core import shadowns
39 from IPython.core import shadowns
40 from IPython.core import ultratb
40 from IPython.core import ultratb
41 from IPython.core.alias import AliasManager
41 from IPython.core.alias import AliasManager
42 from IPython.core.builtin_trap import BuiltinTrap
42 from IPython.core.builtin_trap import BuiltinTrap
43 from IPython.core.display_trap import DisplayTrap
43 from IPython.core.display_trap import DisplayTrap
44 from IPython.core.displayhook import DisplayHook
44 from IPython.core.displayhook import DisplayHook
45 from IPython.core.error import TryNext, UsageError
45 from IPython.core.error import TryNext, UsageError
46 from IPython.core.extensions import ExtensionManager
46 from IPython.core.extensions import ExtensionManager
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
47 from IPython.core.fakemodule import FakeModule, init_fakemod_dict
48 from IPython.core.inputlist import InputList
48 from IPython.core.inputlist import InputList
49 from IPython.core.inputsplitter import IPythonInputSplitter
49 from IPython.core.logger import Logger
50 from IPython.core.logger import Logger
50 from IPython.core.magic import Magic
51 from IPython.core.magic import Magic
51 from IPython.core.payload import PayloadManager
52 from IPython.core.payload import PayloadManager
52 from IPython.core.plugin import PluginManager
53 from IPython.core.plugin import PluginManager
53 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 from IPython.core.prefilter import PrefilterManager, ESC_MAGIC
54 from IPython.external.Itpl import ItplNS
55 from IPython.external.Itpl import ItplNS
55 from IPython.utils import PyColorize
56 from IPython.utils import PyColorize
56 from IPython.utils import io
57 from IPython.utils import io
57 from IPython.utils import pickleshare
58 from IPython.utils import pickleshare
58 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.doctestreload import doctest_reload
59 from IPython.utils.io import ask_yes_no, rprint
60 from IPython.utils.io import ask_yes_no, rprint
60 from IPython.utils.ipstruct import Struct
61 from IPython.utils.ipstruct import Struct
61 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError
62 from IPython.utils.process import system, getoutput
63 from IPython.utils.process import system, getoutput
63 from IPython.utils.strdispatch import StrDispatch
64 from IPython.utils.strdispatch import StrDispatch
64 from IPython.utils.syspathcontext import prepended_to_syspath
65 from IPython.utils.syspathcontext import prepended_to_syspath
65 from IPython.utils.text import num_ini_spaces, format_screen
66 from IPython.utils.text import num_ini_spaces, format_screen
66 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum,
67 List, Unicode, Instance, Type)
68 List, Unicode, Instance, Type)
68 from IPython.utils.warn import warn, error, fatal
69 from IPython.utils.warn import warn, error, fatal
69 import IPython.core.hooks
70 import IPython.core.hooks
70
71
71 #-----------------------------------------------------------------------------
72 #-----------------------------------------------------------------------------
72 # Globals
73 # Globals
73 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
74
75
75 # compiled regexps for autoindent management
76 # compiled regexps for autoindent management
76 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77 dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass')
77
78
78 #-----------------------------------------------------------------------------
79 #-----------------------------------------------------------------------------
79 # Utilities
80 # Utilities
80 #-----------------------------------------------------------------------------
81 #-----------------------------------------------------------------------------
81
82
82 # store the builtin raw_input globally, and use this always, in case user code
83 # store the builtin raw_input globally, and use this always, in case user code
83 # overwrites it (like wx.py.PyShell does)
84 # overwrites it (like wx.py.PyShell does)
84 raw_input_original = raw_input
85 raw_input_original = raw_input
85
86
86 def softspace(file, newvalue):
87 def softspace(file, newvalue):
87 """Copied from code.py, to remove the dependency"""
88 """Copied from code.py, to remove the dependency"""
88
89
89 oldvalue = 0
90 oldvalue = 0
90 try:
91 try:
91 oldvalue = file.softspace
92 oldvalue = file.softspace
92 except AttributeError:
93 except AttributeError:
93 pass
94 pass
94 try:
95 try:
95 file.softspace = newvalue
96 file.softspace = newvalue
96 except (AttributeError, TypeError):
97 except (AttributeError, TypeError):
97 # "attribute-less object" or "read-only attributes"
98 # "attribute-less object" or "read-only attributes"
98 pass
99 pass
99 return oldvalue
100 return oldvalue
100
101
101
102
102 def no_op(*a, **kw): pass
103 def no_op(*a, **kw): pass
103
104
104 class SpaceInInput(exceptions.Exception): pass
105 class SpaceInInput(exceptions.Exception): pass
105
106
106 class Bunch: pass
107 class Bunch: pass
107
108
108
109
109 def get_default_colors():
110 def get_default_colors():
110 if sys.platform=='darwin':
111 if sys.platform=='darwin':
111 return "LightBG"
112 return "LightBG"
112 elif os.name=='nt':
113 elif os.name=='nt':
113 return 'Linux'
114 return 'Linux'
114 else:
115 else:
115 return 'Linux'
116 return 'Linux'
116
117
117
118
118 class SeparateStr(Str):
119 class SeparateStr(Str):
119 """A Str subclass to validate separate_in, separate_out, etc.
120 """A Str subclass to validate separate_in, separate_out, etc.
120
121
121 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 This is a Str based trait that converts '0'->'' and '\\n'->'\n'.
122 """
123 """
123
124
124 def validate(self, obj, value):
125 def validate(self, obj, value):
125 if value == '0': value = ''
126 if value == '0': value = ''
126 value = value.replace('\\n','\n')
127 value = value.replace('\\n','\n')
127 return super(SeparateStr, self).validate(obj, value)
128 return super(SeparateStr, self).validate(obj, value)
128
129
129 class MultipleInstanceError(Exception):
130 class MultipleInstanceError(Exception):
130 pass
131 pass
131
132
132
133
133 #-----------------------------------------------------------------------------
134 #-----------------------------------------------------------------------------
134 # Main IPython class
135 # Main IPython class
135 #-----------------------------------------------------------------------------
136 #-----------------------------------------------------------------------------
136
137
137
138
138 class InteractiveShell(Configurable, Magic):
139 class InteractiveShell(Configurable, Magic):
139 """An enhanced, interactive shell for Python."""
140 """An enhanced, interactive shell for Python."""
140
141
141 _instance = None
142 _instance = None
142 autocall = Enum((0,1,2), default_value=1, config=True)
143 autocall = Enum((0,1,2), default_value=1, config=True)
143 # TODO: remove all autoindent logic and put into frontends.
144 # TODO: remove all autoindent logic and put into frontends.
144 # We can't do this yet because even runlines uses the autoindent.
145 # We can't do this yet because even runlines uses the autoindent.
145 autoindent = CBool(True, config=True)
146 autoindent = CBool(True, config=True)
146 automagic = CBool(True, config=True)
147 automagic = CBool(True, config=True)
147 cache_size = Int(1000, config=True)
148 cache_size = Int(1000, config=True)
148 color_info = CBool(True, config=True)
149 color_info = CBool(True, config=True)
149 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
150 colors = CaselessStrEnum(('NoColor','LightBG','Linux'),
150 default_value=get_default_colors(), config=True)
151 default_value=get_default_colors(), config=True)
151 debug = CBool(False, config=True)
152 debug = CBool(False, config=True)
152 deep_reload = CBool(False, config=True)
153 deep_reload = CBool(False, config=True)
153 displayhook_class = Type(DisplayHook)
154 displayhook_class = Type(DisplayHook)
154 exit_now = CBool(False)
155 exit_now = CBool(False)
155 filename = Str("<ipython console>")
156 filename = Str("<ipython console>")
156 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
157 ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__
158 input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter')
157 logstart = CBool(False, config=True)
159 logstart = CBool(False, config=True)
158 logfile = Str('', config=True)
160 logfile = Str('', config=True)
159 logappend = Str('', config=True)
161 logappend = Str('', config=True)
160 object_info_string_level = Enum((0,1,2), default_value=0,
162 object_info_string_level = Enum((0,1,2), default_value=0,
161 config=True)
163 config=True)
162 pdb = CBool(False, config=True)
164 pdb = CBool(False, config=True)
163 pprint = CBool(True, config=True)
165 pprint = CBool(True, config=True)
164 profile = Str('', config=True)
166 profile = Str('', config=True)
165 prompt_in1 = Str('In [\\#]: ', config=True)
167 prompt_in1 = Str('In [\\#]: ', config=True)
166 prompt_in2 = Str(' .\\D.: ', config=True)
168 prompt_in2 = Str(' .\\D.: ', config=True)
167 prompt_out = Str('Out[\\#]: ', config=True)
169 prompt_out = Str('Out[\\#]: ', config=True)
168 prompts_pad_left = CBool(True, config=True)
170 prompts_pad_left = CBool(True, config=True)
169 quiet = CBool(False, config=True)
171 quiet = CBool(False, config=True)
170
172
171 # The readline stuff will eventually be moved to the terminal subclass
173 # The readline stuff will eventually be moved to the terminal subclass
172 # but for now, we can't do that as readline is welded in everywhere.
174 # but for now, we can't do that as readline is welded in everywhere.
173 readline_use = CBool(True, config=True)
175 readline_use = CBool(True, config=True)
174 readline_merge_completions = CBool(True, config=True)
176 readline_merge_completions = CBool(True, config=True)
175 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
177 readline_omit__names = Enum((0,1,2), default_value=0, config=True)
176 readline_remove_delims = Str('-/~', config=True)
178 readline_remove_delims = Str('-/~', config=True)
177 readline_parse_and_bind = List([
179 readline_parse_and_bind = List([
178 'tab: complete',
180 'tab: complete',
179 '"\C-l": clear-screen',
181 '"\C-l": clear-screen',
180 'set show-all-if-ambiguous on',
182 'set show-all-if-ambiguous on',
181 '"\C-o": tab-insert',
183 '"\C-o": tab-insert',
182 '"\M-i": " "',
184 '"\M-i": " "',
183 '"\M-o": "\d\d\d\d"',
185 '"\M-o": "\d\d\d\d"',
184 '"\M-I": "\d\d\d\d"',
186 '"\M-I": "\d\d\d\d"',
185 '"\C-r": reverse-search-history',
187 '"\C-r": reverse-search-history',
186 '"\C-s": forward-search-history',
188 '"\C-s": forward-search-history',
187 '"\C-p": history-search-backward',
189 '"\C-p": history-search-backward',
188 '"\C-n": history-search-forward',
190 '"\C-n": history-search-forward',
189 '"\e[A": history-search-backward',
191 '"\e[A": history-search-backward',
190 '"\e[B": history-search-forward',
192 '"\e[B": history-search-forward',
191 '"\C-k": kill-line',
193 '"\C-k": kill-line',
192 '"\C-u": unix-line-discard',
194 '"\C-u": unix-line-discard',
193 ], allow_none=False, config=True)
195 ], allow_none=False, config=True)
194
196
195 # TODO: this part of prompt management should be moved to the frontends.
197 # TODO: this part of prompt management should be moved to the frontends.
196 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
198 # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n'
197 separate_in = SeparateStr('\n', config=True)
199 separate_in = SeparateStr('\n', config=True)
198 separate_out = SeparateStr('', config=True)
200 separate_out = SeparateStr('', config=True)
199 separate_out2 = SeparateStr('', config=True)
201 separate_out2 = SeparateStr('', config=True)
200 wildcards_case_sensitive = CBool(True, config=True)
202 wildcards_case_sensitive = CBool(True, config=True)
201 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
203 xmode = CaselessStrEnum(('Context','Plain', 'Verbose'),
202 default_value='Context', config=True)
204 default_value='Context', config=True)
203
205
204 # Subcomponents of InteractiveShell
206 # Subcomponents of InteractiveShell
205 alias_manager = Instance('IPython.core.alias.AliasManager')
207 alias_manager = Instance('IPython.core.alias.AliasManager')
206 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
208 prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager')
207 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
209 builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap')
208 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
210 display_trap = Instance('IPython.core.display_trap.DisplayTrap')
209 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
211 extension_manager = Instance('IPython.core.extensions.ExtensionManager')
210 plugin_manager = Instance('IPython.core.plugin.PluginManager')
212 plugin_manager = Instance('IPython.core.plugin.PluginManager')
211 payload_manager = Instance('IPython.core.payload.PayloadManager')
213 payload_manager = Instance('IPython.core.payload.PayloadManager')
212
214
213 def __init__(self, config=None, ipython_dir=None,
215 def __init__(self, config=None, ipython_dir=None,
214 user_ns=None, user_global_ns=None,
216 user_ns=None, user_global_ns=None,
215 custom_exceptions=((),None)):
217 custom_exceptions=((), None)):
216
218
217 # This is where traits with a config_key argument are updated
219 # This is where traits with a config_key argument are updated
218 # from the values on config.
220 # from the values on config.
219 super(InteractiveShell, self).__init__(config=config)
221 super(InteractiveShell, self).__init__(config=config)
220
222
221 # These are relatively independent and stateless
223 # These are relatively independent and stateless
222 self.init_ipython_dir(ipython_dir)
224 self.init_ipython_dir(ipython_dir)
223 self.init_instance_attrs()
225 self.init_instance_attrs()
224
226
225 # Create namespaces (user_ns, user_global_ns, etc.)
227 # Create namespaces (user_ns, user_global_ns, etc.)
226 self.init_create_namespaces(user_ns, user_global_ns)
228 self.init_create_namespaces(user_ns, user_global_ns)
227 # This has to be done after init_create_namespaces because it uses
229 # This has to be done after init_create_namespaces because it uses
228 # something in self.user_ns, but before init_sys_modules, which
230 # something in self.user_ns, but before init_sys_modules, which
229 # is the first thing to modify sys.
231 # is the first thing to modify sys.
230 # TODO: When we override sys.stdout and sys.stderr before this class
232 # TODO: When we override sys.stdout and sys.stderr before this class
231 # is created, we are saving the overridden ones here. Not sure if this
233 # is created, we are saving the overridden ones here. Not sure if this
232 # is what we want to do.
234 # is what we want to do.
233 self.save_sys_module_state()
235 self.save_sys_module_state()
234 self.init_sys_modules()
236 self.init_sys_modules()
235
237
236 self.init_history()
238 self.init_history()
237 self.init_encoding()
239 self.init_encoding()
238 self.init_prefilter()
240 self.init_prefilter()
239
241
240 Magic.__init__(self, self)
242 Magic.__init__(self, self)
241
243
242 self.init_syntax_highlighting()
244 self.init_syntax_highlighting()
243 self.init_hooks()
245 self.init_hooks()
244 self.init_pushd_popd_magic()
246 self.init_pushd_popd_magic()
245 # self.init_traceback_handlers use to be here, but we moved it below
247 # self.init_traceback_handlers use to be here, but we moved it below
246 # because it and init_io have to come after init_readline.
248 # because it and init_io have to come after init_readline.
247 self.init_user_ns()
249 self.init_user_ns()
248 self.init_logger()
250 self.init_logger()
249 self.init_alias()
251 self.init_alias()
250 self.init_builtins()
252 self.init_builtins()
251
253
252 # pre_config_initialization
254 # pre_config_initialization
253 self.init_shadow_hist()
255 self.init_shadow_hist()
254
256
255 # The next section should contain averything that was in ipmaker.
257 # The next section should contain everything that was in ipmaker.
256 self.init_logstart()
258 self.init_logstart()
257
259
258 # The following was in post_config_initialization
260 # The following was in post_config_initialization
259 self.init_inspector()
261 self.init_inspector()
260 # init_readline() must come before init_io(), because init_io uses
262 # init_readline() must come before init_io(), because init_io uses
261 # readline related things.
263 # readline related things.
262 self.init_readline()
264 self.init_readline()
263 # init_completer must come after init_readline, because it needs to
265 # init_completer must come after init_readline, because it needs to
264 # know whether readline is present or not system-wide to configure the
266 # know whether readline is present or not system-wide to configure the
265 # completers, since the completion machinery can now operate
267 # completers, since the completion machinery can now operate
266 # independently of readline (e.g. over the network)
268 # independently of readline (e.g. over the network)
267 self.init_completer()
269 self.init_completer()
268 # TODO: init_io() needs to happen before init_traceback handlers
270 # TODO: init_io() needs to happen before init_traceback handlers
269 # because the traceback handlers hardcode the stdout/stderr streams.
271 # because the traceback handlers hardcode the stdout/stderr streams.
270 # This logic in in debugger.Pdb and should eventually be changed.
272 # This logic in in debugger.Pdb and should eventually be changed.
271 self.init_io()
273 self.init_io()
272 self.init_traceback_handlers(custom_exceptions)
274 self.init_traceback_handlers(custom_exceptions)
273 self.init_prompts()
275 self.init_prompts()
274 self.init_displayhook()
276 self.init_displayhook()
275 self.init_reload_doctest()
277 self.init_reload_doctest()
276 self.init_magics()
278 self.init_magics()
277 self.init_pdb()
279 self.init_pdb()
278 self.init_extension_manager()
280 self.init_extension_manager()
279 self.init_plugin_manager()
281 self.init_plugin_manager()
280 self.init_payload()
282 self.init_payload()
281 self.hooks.late_startup_hook()
283 self.hooks.late_startup_hook()
282 atexit.register(self.atexit_operations)
284 atexit.register(self.atexit_operations)
283
285
284 @classmethod
286 @classmethod
285 def instance(cls, *args, **kwargs):
287 def instance(cls, *args, **kwargs):
286 """Returns a global InteractiveShell instance."""
288 """Returns a global InteractiveShell instance."""
287 if cls._instance is None:
289 if cls._instance is None:
288 inst = cls(*args, **kwargs)
290 inst = cls(*args, **kwargs)
289 # Now make sure that the instance will also be returned by
291 # Now make sure that the instance will also be returned by
290 # the subclasses instance attribute.
292 # the subclasses instance attribute.
291 for subclass in cls.mro():
293 for subclass in cls.mro():
292 if issubclass(cls, subclass) and \
294 if issubclass(cls, subclass) and \
293 issubclass(subclass, InteractiveShell):
295 issubclass(subclass, InteractiveShell):
294 subclass._instance = inst
296 subclass._instance = inst
295 else:
297 else:
296 break
298 break
297 if isinstance(cls._instance, cls):
299 if isinstance(cls._instance, cls):
298 return cls._instance
300 return cls._instance
299 else:
301 else:
300 raise MultipleInstanceError(
302 raise MultipleInstanceError(
301 'Multiple incompatible subclass instances of '
303 'Multiple incompatible subclass instances of '
302 'InteractiveShell are being created.'
304 'InteractiveShell are being created.'
303 )
305 )
304
306
305 @classmethod
307 @classmethod
306 def initialized(cls):
308 def initialized(cls):
307 return hasattr(cls, "_instance")
309 return hasattr(cls, "_instance")
308
310
309 def get_ipython(self):
311 def get_ipython(self):
310 """Return the currently running IPython instance."""
312 """Return the currently running IPython instance."""
311 return self
313 return self
312
314
313 #-------------------------------------------------------------------------
315 #-------------------------------------------------------------------------
314 # Trait changed handlers
316 # Trait changed handlers
315 #-------------------------------------------------------------------------
317 #-------------------------------------------------------------------------
316
318
317 def _ipython_dir_changed(self, name, new):
319 def _ipython_dir_changed(self, name, new):
318 if not os.path.isdir(new):
320 if not os.path.isdir(new):
319 os.makedirs(new, mode = 0777)
321 os.makedirs(new, mode = 0777)
320
322
321 def set_autoindent(self,value=None):
323 def set_autoindent(self,value=None):
322 """Set the autoindent flag, checking for readline support.
324 """Set the autoindent flag, checking for readline support.
323
325
324 If called with no arguments, it acts as a toggle."""
326 If called with no arguments, it acts as a toggle."""
325
327
326 if not self.has_readline:
328 if not self.has_readline:
327 if os.name == 'posix':
329 if os.name == 'posix':
328 warn("The auto-indent feature requires the readline library")
330 warn("The auto-indent feature requires the readline library")
329 self.autoindent = 0
331 self.autoindent = 0
330 return
332 return
331 if value is None:
333 if value is None:
332 self.autoindent = not self.autoindent
334 self.autoindent = not self.autoindent
333 else:
335 else:
334 self.autoindent = value
336 self.autoindent = value
335
337
336 #-------------------------------------------------------------------------
338 #-------------------------------------------------------------------------
337 # init_* methods called by __init__
339 # init_* methods called by __init__
338 #-------------------------------------------------------------------------
340 #-------------------------------------------------------------------------
339
341
340 def init_ipython_dir(self, ipython_dir):
342 def init_ipython_dir(self, ipython_dir):
341 if ipython_dir is not None:
343 if ipython_dir is not None:
342 self.ipython_dir = ipython_dir
344 self.ipython_dir = ipython_dir
343 self.config.Global.ipython_dir = self.ipython_dir
345 self.config.Global.ipython_dir = self.ipython_dir
344 return
346 return
345
347
346 if hasattr(self.config.Global, 'ipython_dir'):
348 if hasattr(self.config.Global, 'ipython_dir'):
347 self.ipython_dir = self.config.Global.ipython_dir
349 self.ipython_dir = self.config.Global.ipython_dir
348 else:
350 else:
349 self.ipython_dir = get_ipython_dir()
351 self.ipython_dir = get_ipython_dir()
350
352
351 # All children can just read this
353 # All children can just read this
352 self.config.Global.ipython_dir = self.ipython_dir
354 self.config.Global.ipython_dir = self.ipython_dir
353
355
354 def init_instance_attrs(self):
356 def init_instance_attrs(self):
355 self.more = False
357 self.more = False
356
358
357 # command compiler
359 # command compiler
358 self.compile = codeop.CommandCompiler()
360 self.compile = codeop.CommandCompiler()
359
361
360 # User input buffer
362 # User input buffer
361 self.buffer = []
363 self.buffer = []
362
364
363 # Make an empty namespace, which extension writers can rely on both
365 # Make an empty namespace, which extension writers can rely on both
364 # existing and NEVER being used by ipython itself. This gives them a
366 # existing and NEVER being used by ipython itself. This gives them a
365 # convenient location for storing additional information and state
367 # convenient location for storing additional information and state
366 # their extensions may require, without fear of collisions with other
368 # their extensions may require, without fear of collisions with other
367 # ipython names that may develop later.
369 # ipython names that may develop later.
368 self.meta = Struct()
370 self.meta = Struct()
369
371
370 # Object variable to store code object waiting execution. This is
372 # Object variable to store code object waiting execution. This is
371 # used mainly by the multithreaded shells, but it can come in handy in
373 # used mainly by the multithreaded shells, but it can come in handy in
372 # other situations. No need to use a Queue here, since it's a single
374 # other situations. No need to use a Queue here, since it's a single
373 # item which gets cleared once run.
375 # item which gets cleared once run.
374 self.code_to_run = None
376 self.code_to_run = None
375
377
376 # Temporary files used for various purposes. Deleted at exit.
378 # Temporary files used for various purposes. Deleted at exit.
377 self.tempfiles = []
379 self.tempfiles = []
378
380
379 # Keep track of readline usage (later set by init_readline)
381 # Keep track of readline usage (later set by init_readline)
380 self.has_readline = False
382 self.has_readline = False
381
383
382 # keep track of where we started running (mainly for crash post-mortem)
384 # keep track of where we started running (mainly for crash post-mortem)
383 # This is not being used anywhere currently.
385 # This is not being used anywhere currently.
384 self.starting_dir = os.getcwd()
386 self.starting_dir = os.getcwd()
385
387
386 # Indentation management
388 # Indentation management
387 self.indent_current_nsp = 0
389 self.indent_current_nsp = 0
388
390
391 # Input splitter, to split entire cells of input into either individual
392 # interactive statements or whole blocks.
393 self.input_splitter = IPythonInputSplitter()
394
389 def init_encoding(self):
395 def init_encoding(self):
390 # Get system encoding at startup time. Certain terminals (like Emacs
396 # Get system encoding at startup time. Certain terminals (like Emacs
391 # under Win32 have it set to None, and we need to have a known valid
397 # under Win32 have it set to None, and we need to have a known valid
392 # encoding to use in the raw_input() method
398 # encoding to use in the raw_input() method
393 try:
399 try:
394 self.stdin_encoding = sys.stdin.encoding or 'ascii'
400 self.stdin_encoding = sys.stdin.encoding or 'ascii'
395 except AttributeError:
401 except AttributeError:
396 self.stdin_encoding = 'ascii'
402 self.stdin_encoding = 'ascii'
397
403
398 def init_syntax_highlighting(self):
404 def init_syntax_highlighting(self):
399 # Python source parser/formatter for syntax highlighting
405 # Python source parser/formatter for syntax highlighting
400 pyformat = PyColorize.Parser().format
406 pyformat = PyColorize.Parser().format
401 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
407 self.pycolorize = lambda src: pyformat(src,'str',self.colors)
402
408
403 def init_pushd_popd_magic(self):
409 def init_pushd_popd_magic(self):
404 # for pushd/popd management
410 # for pushd/popd management
405 try:
411 try:
406 self.home_dir = get_home_dir()
412 self.home_dir = get_home_dir()
407 except HomeDirError, msg:
413 except HomeDirError, msg:
408 fatal(msg)
414 fatal(msg)
409
415
410 self.dir_stack = []
416 self.dir_stack = []
411
417
412 def init_logger(self):
418 def init_logger(self):
413 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
419 self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate')
414 # local shortcut, this is used a LOT
420 # local shortcut, this is used a LOT
415 self.log = self.logger.log
421 self.log = self.logger.log
416
422
417 def init_logstart(self):
423 def init_logstart(self):
418 if self.logappend:
424 if self.logappend:
419 self.magic_logstart(self.logappend + ' append')
425 self.magic_logstart(self.logappend + ' append')
420 elif self.logfile:
426 elif self.logfile:
421 self.magic_logstart(self.logfile)
427 self.magic_logstart(self.logfile)
422 elif self.logstart:
428 elif self.logstart:
423 self.magic_logstart()
429 self.magic_logstart()
424
430
425 def init_builtins(self):
431 def init_builtins(self):
426 self.builtin_trap = BuiltinTrap(shell=self)
432 self.builtin_trap = BuiltinTrap(shell=self)
427
433
428 def init_inspector(self):
434 def init_inspector(self):
429 # Object inspector
435 # Object inspector
430 self.inspector = oinspect.Inspector(oinspect.InspectColors,
436 self.inspector = oinspect.Inspector(oinspect.InspectColors,
431 PyColorize.ANSICodeColors,
437 PyColorize.ANSICodeColors,
432 'NoColor',
438 'NoColor',
433 self.object_info_string_level)
439 self.object_info_string_level)
434
440
435 def init_io(self):
441 def init_io(self):
436 import IPython.utils.io
442 import IPython.utils.io
437 if sys.platform == 'win32' and self.has_readline:
443 if sys.platform == 'win32' and self.has_readline:
438 Term = io.IOTerm(
444 Term = io.IOTerm(
439 cout=self.readline._outputfile,cerr=self.readline._outputfile
445 cout=self.readline._outputfile,cerr=self.readline._outputfile
440 )
446 )
441 else:
447 else:
442 Term = io.IOTerm()
448 Term = io.IOTerm()
443 io.Term = Term
449 io.Term = Term
444
450
445 def init_prompts(self):
451 def init_prompts(self):
446 # TODO: This is a pass for now because the prompts are managed inside
452 # TODO: This is a pass for now because the prompts are managed inside
447 # the DisplayHook. Once there is a separate prompt manager, this
453 # the DisplayHook. Once there is a separate prompt manager, this
448 # will initialize that object and all prompt related information.
454 # will initialize that object and all prompt related information.
449 pass
455 pass
450
456
451 def init_displayhook(self):
457 def init_displayhook(self):
452 # Initialize displayhook, set in/out prompts and printing system
458 # Initialize displayhook, set in/out prompts and printing system
453 self.displayhook = self.displayhook_class(
459 self.displayhook = self.displayhook_class(
454 shell=self,
460 shell=self,
455 cache_size=self.cache_size,
461 cache_size=self.cache_size,
456 input_sep = self.separate_in,
462 input_sep = self.separate_in,
457 output_sep = self.separate_out,
463 output_sep = self.separate_out,
458 output_sep2 = self.separate_out2,
464 output_sep2 = self.separate_out2,
459 ps1 = self.prompt_in1,
465 ps1 = self.prompt_in1,
460 ps2 = self.prompt_in2,
466 ps2 = self.prompt_in2,
461 ps_out = self.prompt_out,
467 ps_out = self.prompt_out,
462 pad_left = self.prompts_pad_left
468 pad_left = self.prompts_pad_left
463 )
469 )
464 # This is a context manager that installs/revmoes the displayhook at
470 # This is a context manager that installs/revmoes the displayhook at
465 # the appropriate time.
471 # the appropriate time.
466 self.display_trap = DisplayTrap(hook=self.displayhook)
472 self.display_trap = DisplayTrap(hook=self.displayhook)
467
473
468 def init_reload_doctest(self):
474 def init_reload_doctest(self):
469 # Do a proper resetting of doctest, including the necessary displayhook
475 # Do a proper resetting of doctest, including the necessary displayhook
470 # monkeypatching
476 # monkeypatching
471 try:
477 try:
472 doctest_reload()
478 doctest_reload()
473 except ImportError:
479 except ImportError:
474 warn("doctest module does not exist.")
480 warn("doctest module does not exist.")
475
481
476 #-------------------------------------------------------------------------
482 #-------------------------------------------------------------------------
477 # Things related to injections into the sys module
483 # Things related to injections into the sys module
478 #-------------------------------------------------------------------------
484 #-------------------------------------------------------------------------
479
485
480 def save_sys_module_state(self):
486 def save_sys_module_state(self):
481 """Save the state of hooks in the sys module.
487 """Save the state of hooks in the sys module.
482
488
483 This has to be called after self.user_ns is created.
489 This has to be called after self.user_ns is created.
484 """
490 """
485 self._orig_sys_module_state = {}
491 self._orig_sys_module_state = {}
486 self._orig_sys_module_state['stdin'] = sys.stdin
492 self._orig_sys_module_state['stdin'] = sys.stdin
487 self._orig_sys_module_state['stdout'] = sys.stdout
493 self._orig_sys_module_state['stdout'] = sys.stdout
488 self._orig_sys_module_state['stderr'] = sys.stderr
494 self._orig_sys_module_state['stderr'] = sys.stderr
489 self._orig_sys_module_state['excepthook'] = sys.excepthook
495 self._orig_sys_module_state['excepthook'] = sys.excepthook
490 try:
496 try:
491 self._orig_sys_modules_main_name = self.user_ns['__name__']
497 self._orig_sys_modules_main_name = self.user_ns['__name__']
492 except KeyError:
498 except KeyError:
493 pass
499 pass
494
500
495 def restore_sys_module_state(self):
501 def restore_sys_module_state(self):
496 """Restore the state of the sys module."""
502 """Restore the state of the sys module."""
497 try:
503 try:
498 for k, v in self._orig_sys_module_state.items():
504 for k, v in self._orig_sys_module_state.items():
499 setattr(sys, k, v)
505 setattr(sys, k, v)
500 except AttributeError:
506 except AttributeError:
501 pass
507 pass
502 # Reset what what done in self.init_sys_modules
508 # Reset what what done in self.init_sys_modules
503 try:
509 try:
504 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
510 sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name
505 except (AttributeError, KeyError):
511 except (AttributeError, KeyError):
506 pass
512 pass
507
513
508 #-------------------------------------------------------------------------
514 #-------------------------------------------------------------------------
509 # Things related to hooks
515 # Things related to hooks
510 #-------------------------------------------------------------------------
516 #-------------------------------------------------------------------------
511
517
512 def init_hooks(self):
518 def init_hooks(self):
513 # hooks holds pointers used for user-side customizations
519 # hooks holds pointers used for user-side customizations
514 self.hooks = Struct()
520 self.hooks = Struct()
515
521
516 self.strdispatchers = {}
522 self.strdispatchers = {}
517
523
518 # Set all default hooks, defined in the IPython.hooks module.
524 # Set all default hooks, defined in the IPython.hooks module.
519 hooks = IPython.core.hooks
525 hooks = IPython.core.hooks
520 for hook_name in hooks.__all__:
526 for hook_name in hooks.__all__:
521 # default hooks have priority 100, i.e. low; user hooks should have
527 # default hooks have priority 100, i.e. low; user hooks should have
522 # 0-100 priority
528 # 0-100 priority
523 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
529 self.set_hook(hook_name,getattr(hooks,hook_name), 100)
524
530
525 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
531 def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None):
526 """set_hook(name,hook) -> sets an internal IPython hook.
532 """set_hook(name,hook) -> sets an internal IPython hook.
527
533
528 IPython exposes some of its internal API as user-modifiable hooks. By
534 IPython exposes some of its internal API as user-modifiable hooks. By
529 adding your function to one of these hooks, you can modify IPython's
535 adding your function to one of these hooks, you can modify IPython's
530 behavior to call at runtime your own routines."""
536 behavior to call at runtime your own routines."""
531
537
532 # At some point in the future, this should validate the hook before it
538 # At some point in the future, this should validate the hook before it
533 # accepts it. Probably at least check that the hook takes the number
539 # accepts it. Probably at least check that the hook takes the number
534 # of args it's supposed to.
540 # of args it's supposed to.
535
541
536 f = new.instancemethod(hook,self,self.__class__)
542 f = new.instancemethod(hook,self,self.__class__)
537
543
538 # check if the hook is for strdispatcher first
544 # check if the hook is for strdispatcher first
539 if str_key is not None:
545 if str_key is not None:
540 sdp = self.strdispatchers.get(name, StrDispatch())
546 sdp = self.strdispatchers.get(name, StrDispatch())
541 sdp.add_s(str_key, f, priority )
547 sdp.add_s(str_key, f, priority )
542 self.strdispatchers[name] = sdp
548 self.strdispatchers[name] = sdp
543 return
549 return
544 if re_key is not None:
550 if re_key is not None:
545 sdp = self.strdispatchers.get(name, StrDispatch())
551 sdp = self.strdispatchers.get(name, StrDispatch())
546 sdp.add_re(re.compile(re_key), f, priority )
552 sdp.add_re(re.compile(re_key), f, priority )
547 self.strdispatchers[name] = sdp
553 self.strdispatchers[name] = sdp
548 return
554 return
549
555
550 dp = getattr(self.hooks, name, None)
556 dp = getattr(self.hooks, name, None)
551 if name not in IPython.core.hooks.__all__:
557 if name not in IPython.core.hooks.__all__:
552 print "Warning! Hook '%s' is not one of %s" % \
558 print "Warning! Hook '%s' is not one of %s" % \
553 (name, IPython.core.hooks.__all__ )
559 (name, IPython.core.hooks.__all__ )
554 if not dp:
560 if not dp:
555 dp = IPython.core.hooks.CommandChainDispatcher()
561 dp = IPython.core.hooks.CommandChainDispatcher()
556
562
557 try:
563 try:
558 dp.add(f,priority)
564 dp.add(f,priority)
559 except AttributeError:
565 except AttributeError:
560 # it was not commandchain, plain old func - replace
566 # it was not commandchain, plain old func - replace
561 dp = f
567 dp = f
562
568
563 setattr(self.hooks,name, dp)
569 setattr(self.hooks,name, dp)
564
570
565 #-------------------------------------------------------------------------
571 #-------------------------------------------------------------------------
566 # Things related to the "main" module
572 # Things related to the "main" module
567 #-------------------------------------------------------------------------
573 #-------------------------------------------------------------------------
568
574
569 def new_main_mod(self,ns=None):
575 def new_main_mod(self,ns=None):
570 """Return a new 'main' module object for user code execution.
576 """Return a new 'main' module object for user code execution.
571 """
577 """
572 main_mod = self._user_main_module
578 main_mod = self._user_main_module
573 init_fakemod_dict(main_mod,ns)
579 init_fakemod_dict(main_mod,ns)
574 return main_mod
580 return main_mod
575
581
576 def cache_main_mod(self,ns,fname):
582 def cache_main_mod(self,ns,fname):
577 """Cache a main module's namespace.
583 """Cache a main module's namespace.
578
584
579 When scripts are executed via %run, we must keep a reference to the
585 When scripts are executed via %run, we must keep a reference to the
580 namespace of their __main__ module (a FakeModule instance) around so
586 namespace of their __main__ module (a FakeModule instance) around so
581 that Python doesn't clear it, rendering objects defined therein
587 that Python doesn't clear it, rendering objects defined therein
582 useless.
588 useless.
583
589
584 This method keeps said reference in a private dict, keyed by the
590 This method keeps said reference in a private dict, keyed by the
585 absolute path of the module object (which corresponds to the script
591 absolute path of the module object (which corresponds to the script
586 path). This way, for multiple executions of the same script we only
592 path). This way, for multiple executions of the same script we only
587 keep one copy of the namespace (the last one), thus preventing memory
593 keep one copy of the namespace (the last one), thus preventing memory
588 leaks from old references while allowing the objects from the last
594 leaks from old references while allowing the objects from the last
589 execution to be accessible.
595 execution to be accessible.
590
596
591 Note: we can not allow the actual FakeModule instances to be deleted,
597 Note: we can not allow the actual FakeModule instances to be deleted,
592 because of how Python tears down modules (it hard-sets all their
598 because of how Python tears down modules (it hard-sets all their
593 references to None without regard for reference counts). This method
599 references to None without regard for reference counts). This method
594 must therefore make a *copy* of the given namespace, to allow the
600 must therefore make a *copy* of the given namespace, to allow the
595 original module's __dict__ to be cleared and reused.
601 original module's __dict__ to be cleared and reused.
596
602
597
603
598 Parameters
604 Parameters
599 ----------
605 ----------
600 ns : a namespace (a dict, typically)
606 ns : a namespace (a dict, typically)
601
607
602 fname : str
608 fname : str
603 Filename associated with the namespace.
609 Filename associated with the namespace.
604
610
605 Examples
611 Examples
606 --------
612 --------
607
613
608 In [10]: import IPython
614 In [10]: import IPython
609
615
610 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
616 In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
611
617
612 In [12]: IPython.__file__ in _ip._main_ns_cache
618 In [12]: IPython.__file__ in _ip._main_ns_cache
613 Out[12]: True
619 Out[12]: True
614 """
620 """
615 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
621 self._main_ns_cache[os.path.abspath(fname)] = ns.copy()
616
622
617 def clear_main_mod_cache(self):
623 def clear_main_mod_cache(self):
618 """Clear the cache of main modules.
624 """Clear the cache of main modules.
619
625
620 Mainly for use by utilities like %reset.
626 Mainly for use by utilities like %reset.
621
627
622 Examples
628 Examples
623 --------
629 --------
624
630
625 In [15]: import IPython
631 In [15]: import IPython
626
632
627 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
633 In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__)
628
634
629 In [17]: len(_ip._main_ns_cache) > 0
635 In [17]: len(_ip._main_ns_cache) > 0
630 Out[17]: True
636 Out[17]: True
631
637
632 In [18]: _ip.clear_main_mod_cache()
638 In [18]: _ip.clear_main_mod_cache()
633
639
634 In [19]: len(_ip._main_ns_cache) == 0
640 In [19]: len(_ip._main_ns_cache) == 0
635 Out[19]: True
641 Out[19]: True
636 """
642 """
637 self._main_ns_cache.clear()
643 self._main_ns_cache.clear()
638
644
639 #-------------------------------------------------------------------------
645 #-------------------------------------------------------------------------
640 # Things related to debugging
646 # Things related to debugging
641 #-------------------------------------------------------------------------
647 #-------------------------------------------------------------------------
642
648
643 def init_pdb(self):
649 def init_pdb(self):
644 # Set calling of pdb on exceptions
650 # Set calling of pdb on exceptions
645 # self.call_pdb is a property
651 # self.call_pdb is a property
646 self.call_pdb = self.pdb
652 self.call_pdb = self.pdb
647
653
648 def _get_call_pdb(self):
654 def _get_call_pdb(self):
649 return self._call_pdb
655 return self._call_pdb
650
656
651 def _set_call_pdb(self,val):
657 def _set_call_pdb(self,val):
652
658
653 if val not in (0,1,False,True):
659 if val not in (0,1,False,True):
654 raise ValueError,'new call_pdb value must be boolean'
660 raise ValueError,'new call_pdb value must be boolean'
655
661
656 # store value in instance
662 # store value in instance
657 self._call_pdb = val
663 self._call_pdb = val
658
664
659 # notify the actual exception handlers
665 # notify the actual exception handlers
660 self.InteractiveTB.call_pdb = val
666 self.InteractiveTB.call_pdb = val
661
667
662 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
668 call_pdb = property(_get_call_pdb,_set_call_pdb,None,
663 'Control auto-activation of pdb at exceptions')
669 'Control auto-activation of pdb at exceptions')
664
670
665 def debugger(self,force=False):
671 def debugger(self,force=False):
666 """Call the pydb/pdb debugger.
672 """Call the pydb/pdb debugger.
667
673
668 Keywords:
674 Keywords:
669
675
670 - force(False): by default, this routine checks the instance call_pdb
676 - force(False): by default, this routine checks the instance call_pdb
671 flag and does not actually invoke the debugger if the flag is false.
677 flag and does not actually invoke the debugger if the flag is false.
672 The 'force' option forces the debugger to activate even if the flag
678 The 'force' option forces the debugger to activate even if the flag
673 is false.
679 is false.
674 """
680 """
675
681
676 if not (force or self.call_pdb):
682 if not (force or self.call_pdb):
677 return
683 return
678
684
679 if not hasattr(sys,'last_traceback'):
685 if not hasattr(sys,'last_traceback'):
680 error('No traceback has been produced, nothing to debug.')
686 error('No traceback has been produced, nothing to debug.')
681 return
687 return
682
688
683 # use pydb if available
689 # use pydb if available
684 if debugger.has_pydb:
690 if debugger.has_pydb:
685 from pydb import pm
691 from pydb import pm
686 else:
692 else:
687 # fallback to our internal debugger
693 # fallback to our internal debugger
688 pm = lambda : self.InteractiveTB.debugger(force=True)
694 pm = lambda : self.InteractiveTB.debugger(force=True)
689 self.history_saving_wrapper(pm)()
695 self.history_saving_wrapper(pm)()
690
696
691 #-------------------------------------------------------------------------
697 #-------------------------------------------------------------------------
692 # Things related to IPython's various namespaces
698 # Things related to IPython's various namespaces
693 #-------------------------------------------------------------------------
699 #-------------------------------------------------------------------------
694
700
695 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
701 def init_create_namespaces(self, user_ns=None, user_global_ns=None):
696 # Create the namespace where the user will operate. user_ns is
702 # Create the namespace where the user will operate. user_ns is
697 # normally the only one used, and it is passed to the exec calls as
703 # normally the only one used, and it is passed to the exec calls as
698 # the locals argument. But we do carry a user_global_ns namespace
704 # the locals argument. But we do carry a user_global_ns namespace
699 # given as the exec 'globals' argument, This is useful in embedding
705 # given as the exec 'globals' argument, This is useful in embedding
700 # situations where the ipython shell opens in a context where the
706 # situations where the ipython shell opens in a context where the
701 # distinction between locals and globals is meaningful. For
707 # distinction between locals and globals is meaningful. For
702 # non-embedded contexts, it is just the same object as the user_ns dict.
708 # non-embedded contexts, it is just the same object as the user_ns dict.
703
709
704 # FIXME. For some strange reason, __builtins__ is showing up at user
710 # FIXME. For some strange reason, __builtins__ is showing up at user
705 # level as a dict instead of a module. This is a manual fix, but I
711 # level as a dict instead of a module. This is a manual fix, but I
706 # should really track down where the problem is coming from. Alex
712 # should really track down where the problem is coming from. Alex
707 # Schmolck reported this problem first.
713 # Schmolck reported this problem first.
708
714
709 # A useful post by Alex Martelli on this topic:
715 # A useful post by Alex Martelli on this topic:
710 # Re: inconsistent value from __builtins__
716 # Re: inconsistent value from __builtins__
711 # Von: Alex Martelli <aleaxit@yahoo.com>
717 # Von: Alex Martelli <aleaxit@yahoo.com>
712 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
718 # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends
713 # Gruppen: comp.lang.python
719 # Gruppen: comp.lang.python
714
720
715 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
721 # Michael Hohn <hohn@hooknose.lbl.gov> wrote:
716 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
722 # > >>> print type(builtin_check.get_global_binding('__builtins__'))
717 # > <type 'dict'>
723 # > <type 'dict'>
718 # > >>> print type(__builtins__)
724 # > >>> print type(__builtins__)
719 # > <type 'module'>
725 # > <type 'module'>
720 # > Is this difference in return value intentional?
726 # > Is this difference in return value intentional?
721
727
722 # Well, it's documented that '__builtins__' can be either a dictionary
728 # Well, it's documented that '__builtins__' can be either a dictionary
723 # or a module, and it's been that way for a long time. Whether it's
729 # or a module, and it's been that way for a long time. Whether it's
724 # intentional (or sensible), I don't know. In any case, the idea is
730 # intentional (or sensible), I don't know. In any case, the idea is
725 # that if you need to access the built-in namespace directly, you
731 # that if you need to access the built-in namespace directly, you
726 # should start with "import __builtin__" (note, no 's') which will
732 # should start with "import __builtin__" (note, no 's') which will
727 # definitely give you a module. Yeah, it's somewhat confusing:-(.
733 # definitely give you a module. Yeah, it's somewhat confusing:-(.
728
734
729 # These routines return properly built dicts as needed by the rest of
735 # These routines return properly built dicts as needed by the rest of
730 # the code, and can also be used by extension writers to generate
736 # the code, and can also be used by extension writers to generate
731 # properly initialized namespaces.
737 # properly initialized namespaces.
732 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
738 user_ns, user_global_ns = self.make_user_namespaces(user_ns,
733 user_global_ns)
739 user_global_ns)
734
740
735 # Assign namespaces
741 # Assign namespaces
736 # This is the namespace where all normal user variables live
742 # This is the namespace where all normal user variables live
737 self.user_ns = user_ns
743 self.user_ns = user_ns
738 self.user_global_ns = user_global_ns
744 self.user_global_ns = user_global_ns
739
745
740 # An auxiliary namespace that checks what parts of the user_ns were
746 # An auxiliary namespace that checks what parts of the user_ns were
741 # loaded at startup, so we can list later only variables defined in
747 # loaded at startup, so we can list later only variables defined in
742 # actual interactive use. Since it is always a subset of user_ns, it
748 # actual interactive use. Since it is always a subset of user_ns, it
743 # doesn't need to be separately tracked in the ns_table.
749 # doesn't need to be separately tracked in the ns_table.
744 self.user_ns_hidden = {}
750 self.user_ns_hidden = {}
745
751
746 # A namespace to keep track of internal data structures to prevent
752 # A namespace to keep track of internal data structures to prevent
747 # them from cluttering user-visible stuff. Will be updated later
753 # them from cluttering user-visible stuff. Will be updated later
748 self.internal_ns = {}
754 self.internal_ns = {}
749
755
750 # Now that FakeModule produces a real module, we've run into a nasty
756 # Now that FakeModule produces a real module, we've run into a nasty
751 # problem: after script execution (via %run), the module where the user
757 # problem: after script execution (via %run), the module where the user
752 # code ran is deleted. Now that this object is a true module (needed
758 # code ran is deleted. Now that this object is a true module (needed
753 # so docetst and other tools work correctly), the Python module
759 # so docetst and other tools work correctly), the Python module
754 # teardown mechanism runs over it, and sets to None every variable
760 # teardown mechanism runs over it, and sets to None every variable
755 # present in that module. Top-level references to objects from the
761 # present in that module. Top-level references to objects from the
756 # script survive, because the user_ns is updated with them. However,
762 # script survive, because the user_ns is updated with them. However,
757 # calling functions defined in the script that use other things from
763 # calling functions defined in the script that use other things from
758 # the script will fail, because the function's closure had references
764 # the script will fail, because the function's closure had references
759 # to the original objects, which are now all None. So we must protect
765 # to the original objects, which are now all None. So we must protect
760 # these modules from deletion by keeping a cache.
766 # these modules from deletion by keeping a cache.
761 #
767 #
762 # To avoid keeping stale modules around (we only need the one from the
768 # To avoid keeping stale modules around (we only need the one from the
763 # last run), we use a dict keyed with the full path to the script, so
769 # last run), we use a dict keyed with the full path to the script, so
764 # only the last version of the module is held in the cache. Note,
770 # only the last version of the module is held in the cache. Note,
765 # however, that we must cache the module *namespace contents* (their
771 # however, that we must cache the module *namespace contents* (their
766 # __dict__). Because if we try to cache the actual modules, old ones
772 # __dict__). Because if we try to cache the actual modules, old ones
767 # (uncached) could be destroyed while still holding references (such as
773 # (uncached) could be destroyed while still holding references (such as
768 # those held by GUI objects that tend to be long-lived)>
774 # those held by GUI objects that tend to be long-lived)>
769 #
775 #
770 # The %reset command will flush this cache. See the cache_main_mod()
776 # The %reset command will flush this cache. See the cache_main_mod()
771 # and clear_main_mod_cache() methods for details on use.
777 # and clear_main_mod_cache() methods for details on use.
772
778
773 # This is the cache used for 'main' namespaces
779 # This is the cache used for 'main' namespaces
774 self._main_ns_cache = {}
780 self._main_ns_cache = {}
775 # And this is the single instance of FakeModule whose __dict__ we keep
781 # And this is the single instance of FakeModule whose __dict__ we keep
776 # copying and clearing for reuse on each %run
782 # copying and clearing for reuse on each %run
777 self._user_main_module = FakeModule()
783 self._user_main_module = FakeModule()
778
784
779 # A table holding all the namespaces IPython deals with, so that
785 # A table holding all the namespaces IPython deals with, so that
780 # introspection facilities can search easily.
786 # introspection facilities can search easily.
781 self.ns_table = {'user':user_ns,
787 self.ns_table = {'user':user_ns,
782 'user_global':user_global_ns,
788 'user_global':user_global_ns,
783 'internal':self.internal_ns,
789 'internal':self.internal_ns,
784 'builtin':__builtin__.__dict__
790 'builtin':__builtin__.__dict__
785 }
791 }
786
792
787 # Similarly, track all namespaces where references can be held and that
793 # Similarly, track all namespaces where references can be held and that
788 # we can safely clear (so it can NOT include builtin). This one can be
794 # we can safely clear (so it can NOT include builtin). This one can be
789 # a simple list.
795 # a simple list.
790 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
796 self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden,
791 self.internal_ns, self._main_ns_cache ]
797 self.internal_ns, self._main_ns_cache ]
792
798
793 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
799 def make_user_namespaces(self, user_ns=None, user_global_ns=None):
794 """Return a valid local and global user interactive namespaces.
800 """Return a valid local and global user interactive namespaces.
795
801
796 This builds a dict with the minimal information needed to operate as a
802 This builds a dict with the minimal information needed to operate as a
797 valid IPython user namespace, which you can pass to the various
803 valid IPython user namespace, which you can pass to the various
798 embedding classes in ipython. The default implementation returns the
804 embedding classes in ipython. The default implementation returns the
799 same dict for both the locals and the globals to allow functions to
805 same dict for both the locals and the globals to allow functions to
800 refer to variables in the namespace. Customized implementations can
806 refer to variables in the namespace. Customized implementations can
801 return different dicts. The locals dictionary can actually be anything
807 return different dicts. The locals dictionary can actually be anything
802 following the basic mapping protocol of a dict, but the globals dict
808 following the basic mapping protocol of a dict, but the globals dict
803 must be a true dict, not even a subclass. It is recommended that any
809 must be a true dict, not even a subclass. It is recommended that any
804 custom object for the locals namespace synchronize with the globals
810 custom object for the locals namespace synchronize with the globals
805 dict somehow.
811 dict somehow.
806
812
807 Raises TypeError if the provided globals namespace is not a true dict.
813 Raises TypeError if the provided globals namespace is not a true dict.
808
814
809 Parameters
815 Parameters
810 ----------
816 ----------
811 user_ns : dict-like, optional
817 user_ns : dict-like, optional
812 The current user namespace. The items in this namespace should
818 The current user namespace. The items in this namespace should
813 be included in the output. If None, an appropriate blank
819 be included in the output. If None, an appropriate blank
814 namespace should be created.
820 namespace should be created.
815 user_global_ns : dict, optional
821 user_global_ns : dict, optional
816 The current user global namespace. The items in this namespace
822 The current user global namespace. The items in this namespace
817 should be included in the output. If None, an appropriate
823 should be included in the output. If None, an appropriate
818 blank namespace should be created.
824 blank namespace should be created.
819
825
820 Returns
826 Returns
821 -------
827 -------
822 A pair of dictionary-like object to be used as the local namespace
828 A pair of dictionary-like object to be used as the local namespace
823 of the interpreter and a dict to be used as the global namespace.
829 of the interpreter and a dict to be used as the global namespace.
824 """
830 """
825
831
826
832
827 # We must ensure that __builtin__ (without the final 's') is always
833 # We must ensure that __builtin__ (without the final 's') is always
828 # available and pointing to the __builtin__ *module*. For more details:
834 # available and pointing to the __builtin__ *module*. For more details:
829 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
835 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
830
836
831 if user_ns is None:
837 if user_ns is None:
832 # Set __name__ to __main__ to better match the behavior of the
838 # Set __name__ to __main__ to better match the behavior of the
833 # normal interpreter.
839 # normal interpreter.
834 user_ns = {'__name__' :'__main__',
840 user_ns = {'__name__' :'__main__',
835 '__builtin__' : __builtin__,
841 '__builtin__' : __builtin__,
836 '__builtins__' : __builtin__,
842 '__builtins__' : __builtin__,
837 }
843 }
838 else:
844 else:
839 user_ns.setdefault('__name__','__main__')
845 user_ns.setdefault('__name__','__main__')
840 user_ns.setdefault('__builtin__',__builtin__)
846 user_ns.setdefault('__builtin__',__builtin__)
841 user_ns.setdefault('__builtins__',__builtin__)
847 user_ns.setdefault('__builtins__',__builtin__)
842
848
843 if user_global_ns is None:
849 if user_global_ns is None:
844 user_global_ns = user_ns
850 user_global_ns = user_ns
845 if type(user_global_ns) is not dict:
851 if type(user_global_ns) is not dict:
846 raise TypeError("user_global_ns must be a true dict; got %r"
852 raise TypeError("user_global_ns must be a true dict; got %r"
847 % type(user_global_ns))
853 % type(user_global_ns))
848
854
849 return user_ns, user_global_ns
855 return user_ns, user_global_ns
850
856
851 def init_sys_modules(self):
857 def init_sys_modules(self):
852 # We need to insert into sys.modules something that looks like a
858 # We need to insert into sys.modules something that looks like a
853 # module but which accesses the IPython namespace, for shelve and
859 # module but which accesses the IPython namespace, for shelve and
854 # pickle to work interactively. Normally they rely on getting
860 # pickle to work interactively. Normally they rely on getting
855 # everything out of __main__, but for embedding purposes each IPython
861 # everything out of __main__, but for embedding purposes each IPython
856 # instance has its own private namespace, so we can't go shoving
862 # instance has its own private namespace, so we can't go shoving
857 # everything into __main__.
863 # everything into __main__.
858
864
859 # note, however, that we should only do this for non-embedded
865 # note, however, that we should only do this for non-embedded
860 # ipythons, which really mimic the __main__.__dict__ with their own
866 # ipythons, which really mimic the __main__.__dict__ with their own
861 # namespace. Embedded instances, on the other hand, should not do
867 # namespace. Embedded instances, on the other hand, should not do
862 # this because they need to manage the user local/global namespaces
868 # this because they need to manage the user local/global namespaces
863 # only, but they live within a 'normal' __main__ (meaning, they
869 # only, but they live within a 'normal' __main__ (meaning, they
864 # shouldn't overtake the execution environment of the script they're
870 # shouldn't overtake the execution environment of the script they're
865 # embedded in).
871 # embedded in).
866
872
867 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
873 # This is overridden in the InteractiveShellEmbed subclass to a no-op.
868
874
869 try:
875 try:
870 main_name = self.user_ns['__name__']
876 main_name = self.user_ns['__name__']
871 except KeyError:
877 except KeyError:
872 raise KeyError('user_ns dictionary MUST have a "__name__" key')
878 raise KeyError('user_ns dictionary MUST have a "__name__" key')
873 else:
879 else:
874 sys.modules[main_name] = FakeModule(self.user_ns)
880 sys.modules[main_name] = FakeModule(self.user_ns)
875
881
876 def init_user_ns(self):
882 def init_user_ns(self):
877 """Initialize all user-visible namespaces to their minimum defaults.
883 """Initialize all user-visible namespaces to their minimum defaults.
878
884
879 Certain history lists are also initialized here, as they effectively
885 Certain history lists are also initialized here, as they effectively
880 act as user namespaces.
886 act as user namespaces.
881
887
882 Notes
888 Notes
883 -----
889 -----
884 All data structures here are only filled in, they are NOT reset by this
890 All data structures here are only filled in, they are NOT reset by this
885 method. If they were not empty before, data will simply be added to
891 method. If they were not empty before, data will simply be added to
886 therm.
892 therm.
887 """
893 """
888 # This function works in two parts: first we put a few things in
894 # This function works in two parts: first we put a few things in
889 # user_ns, and we sync that contents into user_ns_hidden so that these
895 # user_ns, and we sync that contents into user_ns_hidden so that these
890 # initial variables aren't shown by %who. After the sync, we add the
896 # initial variables aren't shown by %who. After the sync, we add the
891 # rest of what we *do* want the user to see with %who even on a new
897 # rest of what we *do* want the user to see with %who even on a new
892 # session (probably nothing, so theye really only see their own stuff)
898 # session (probably nothing, so theye really only see their own stuff)
893
899
894 # The user dict must *always* have a __builtin__ reference to the
900 # The user dict must *always* have a __builtin__ reference to the
895 # Python standard __builtin__ namespace, which must be imported.
901 # Python standard __builtin__ namespace, which must be imported.
896 # This is so that certain operations in prompt evaluation can be
902 # This is so that certain operations in prompt evaluation can be
897 # reliably executed with builtins. Note that we can NOT use
903 # reliably executed with builtins. Note that we can NOT use
898 # __builtins__ (note the 's'), because that can either be a dict or a
904 # __builtins__ (note the 's'), because that can either be a dict or a
899 # module, and can even mutate at runtime, depending on the context
905 # module, and can even mutate at runtime, depending on the context
900 # (Python makes no guarantees on it). In contrast, __builtin__ is
906 # (Python makes no guarantees on it). In contrast, __builtin__ is
901 # always a module object, though it must be explicitly imported.
907 # always a module object, though it must be explicitly imported.
902
908
903 # For more details:
909 # For more details:
904 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
910 # http://mail.python.org/pipermail/python-dev/2001-April/014068.html
905 ns = dict(__builtin__ = __builtin__)
911 ns = dict(__builtin__ = __builtin__)
906
912
907 # Put 'help' in the user namespace
913 # Put 'help' in the user namespace
908 try:
914 try:
909 from site import _Helper
915 from site import _Helper
910 ns['help'] = _Helper()
916 ns['help'] = _Helper()
911 except ImportError:
917 except ImportError:
912 warn('help() not available - check site.py')
918 warn('help() not available - check site.py')
913
919
914 # make global variables for user access to the histories
920 # make global variables for user access to the histories
915 ns['_ih'] = self.input_hist
921 ns['_ih'] = self.input_hist
916 ns['_oh'] = self.output_hist
922 ns['_oh'] = self.output_hist
917 ns['_dh'] = self.dir_hist
923 ns['_dh'] = self.dir_hist
918
924
919 ns['_sh'] = shadowns
925 ns['_sh'] = shadowns
920
926
921 # user aliases to input and output histories. These shouldn't show up
927 # user aliases to input and output histories. These shouldn't show up
922 # in %who, as they can have very large reprs.
928 # in %who, as they can have very large reprs.
923 ns['In'] = self.input_hist
929 ns['In'] = self.input_hist
924 ns['Out'] = self.output_hist
930 ns['Out'] = self.output_hist
925
931
926 # Store myself as the public api!!!
932 # Store myself as the public api!!!
927 ns['get_ipython'] = self.get_ipython
933 ns['get_ipython'] = self.get_ipython
928
934
929 # Sync what we've added so far to user_ns_hidden so these aren't seen
935 # Sync what we've added so far to user_ns_hidden so these aren't seen
930 # by %who
936 # by %who
931 self.user_ns_hidden.update(ns)
937 self.user_ns_hidden.update(ns)
932
938
933 # Anything put into ns now would show up in %who. Think twice before
939 # Anything put into ns now would show up in %who. Think twice before
934 # putting anything here, as we really want %who to show the user their
940 # putting anything here, as we really want %who to show the user their
935 # stuff, not our variables.
941 # stuff, not our variables.
936
942
937 # Finally, update the real user's namespace
943 # Finally, update the real user's namespace
938 self.user_ns.update(ns)
944 self.user_ns.update(ns)
939
945
940
946
941 def reset(self):
947 def reset(self):
942 """Clear all internal namespaces.
948 """Clear all internal namespaces.
943
949
944 Note that this is much more aggressive than %reset, since it clears
950 Note that this is much more aggressive than %reset, since it clears
945 fully all namespaces, as well as all input/output lists.
951 fully all namespaces, as well as all input/output lists.
946 """
952 """
947 for ns in self.ns_refs_table:
953 for ns in self.ns_refs_table:
948 ns.clear()
954 ns.clear()
949
955
950 self.alias_manager.clear_aliases()
956 self.alias_manager.clear_aliases()
951
957
952 # Clear input and output histories
958 # Clear input and output histories
953 self.input_hist[:] = []
959 self.input_hist[:] = []
954 self.input_hist_raw[:] = []
960 self.input_hist_raw[:] = []
955 self.output_hist.clear()
961 self.output_hist.clear()
956
962
957 # Restore the user namespaces to minimal usability
963 # Restore the user namespaces to minimal usability
958 self.init_user_ns()
964 self.init_user_ns()
959
965
960 # Restore the default and user aliases
966 # Restore the default and user aliases
961 self.alias_manager.init_aliases()
967 self.alias_manager.init_aliases()
962
968
963 def reset_selective(self, regex=None):
969 def reset_selective(self, regex=None):
964 """Clear selective variables from internal namespaces based on a
970 """Clear selective variables from internal namespaces based on a
965 specified regular expression.
971 specified regular expression.
966
972
967 Parameters
973 Parameters
968 ----------
974 ----------
969 regex : string or compiled pattern, optional
975 regex : string or compiled pattern, optional
970 A regular expression pattern that will be used in searching
976 A regular expression pattern that will be used in searching
971 variable names in the users namespaces.
977 variable names in the users namespaces.
972 """
978 """
973 if regex is not None:
979 if regex is not None:
974 try:
980 try:
975 m = re.compile(regex)
981 m = re.compile(regex)
976 except TypeError:
982 except TypeError:
977 raise TypeError('regex must be a string or compiled pattern')
983 raise TypeError('regex must be a string or compiled pattern')
978 # Search for keys in each namespace that match the given regex
984 # Search for keys in each namespace that match the given regex
979 # If a match is found, delete the key/value pair.
985 # If a match is found, delete the key/value pair.
980 for ns in self.ns_refs_table:
986 for ns in self.ns_refs_table:
981 for var in ns:
987 for var in ns:
982 if m.search(var):
988 if m.search(var):
983 del ns[var]
989 del ns[var]
984
990
985 def push(self, variables, interactive=True):
991 def push(self, variables, interactive=True):
986 """Inject a group of variables into the IPython user namespace.
992 """Inject a group of variables into the IPython user namespace.
987
993
988 Parameters
994 Parameters
989 ----------
995 ----------
990 variables : dict, str or list/tuple of str
996 variables : dict, str or list/tuple of str
991 The variables to inject into the user's namespace. If a dict, a
997 The variables to inject into the user's namespace. If a dict, a
992 simple update is done. If a str, the string is assumed to have
998 simple update is done. If a str, the string is assumed to have
993 variable names separated by spaces. A list/tuple of str can also
999 variable names separated by spaces. A list/tuple of str can also
994 be used to give the variable names. If just the variable names are
1000 be used to give the variable names. If just the variable names are
995 give (list/tuple/str) then the variable values looked up in the
1001 give (list/tuple/str) then the variable values looked up in the
996 callers frame.
1002 callers frame.
997 interactive : bool
1003 interactive : bool
998 If True (default), the variables will be listed with the ``who``
1004 If True (default), the variables will be listed with the ``who``
999 magic.
1005 magic.
1000 """
1006 """
1001 vdict = None
1007 vdict = None
1002
1008
1003 # We need a dict of name/value pairs to do namespace updates.
1009 # We need a dict of name/value pairs to do namespace updates.
1004 if isinstance(variables, dict):
1010 if isinstance(variables, dict):
1005 vdict = variables
1011 vdict = variables
1006 elif isinstance(variables, (basestring, list, tuple)):
1012 elif isinstance(variables, (basestring, list, tuple)):
1007 if isinstance(variables, basestring):
1013 if isinstance(variables, basestring):
1008 vlist = variables.split()
1014 vlist = variables.split()
1009 else:
1015 else:
1010 vlist = variables
1016 vlist = variables
1011 vdict = {}
1017 vdict = {}
1012 cf = sys._getframe(1)
1018 cf = sys._getframe(1)
1013 for name in vlist:
1019 for name in vlist:
1014 try:
1020 try:
1015 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1021 vdict[name] = eval(name, cf.f_globals, cf.f_locals)
1016 except:
1022 except:
1017 print ('Could not get variable %s from %s' %
1023 print ('Could not get variable %s from %s' %
1018 (name,cf.f_code.co_name))
1024 (name,cf.f_code.co_name))
1019 else:
1025 else:
1020 raise ValueError('variables must be a dict/str/list/tuple')
1026 raise ValueError('variables must be a dict/str/list/tuple')
1021
1027
1022 # Propagate variables to user namespace
1028 # Propagate variables to user namespace
1023 self.user_ns.update(vdict)
1029 self.user_ns.update(vdict)
1024
1030
1025 # And configure interactive visibility
1031 # And configure interactive visibility
1026 config_ns = self.user_ns_hidden
1032 config_ns = self.user_ns_hidden
1027 if interactive:
1033 if interactive:
1028 for name, val in vdict.iteritems():
1034 for name, val in vdict.iteritems():
1029 config_ns.pop(name, None)
1035 config_ns.pop(name, None)
1030 else:
1036 else:
1031 for name,val in vdict.iteritems():
1037 for name,val in vdict.iteritems():
1032 config_ns[name] = val
1038 config_ns[name] = val
1033
1039
1034 #-------------------------------------------------------------------------
1040 #-------------------------------------------------------------------------
1035 # Things related to object introspection
1041 # Things related to object introspection
1036 #-------------------------------------------------------------------------
1042 #-------------------------------------------------------------------------
1037 def _ofind(self, oname, namespaces=None):
1043 def _ofind(self, oname, namespaces=None):
1038 """Find an object in the available namespaces.
1044 """Find an object in the available namespaces.
1039
1045
1040 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1046 self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
1041
1047
1042 Has special code to detect magic functions.
1048 Has special code to detect magic functions.
1043 """
1049 """
1044 #oname = oname.strip()
1050 #oname = oname.strip()
1045 #print '1- oname: <%r>' % oname # dbg
1051 #print '1- oname: <%r>' % oname # dbg
1046 try:
1052 try:
1047 oname = oname.strip().encode('ascii')
1053 oname = oname.strip().encode('ascii')
1048 #print '2- oname: <%r>' % oname # dbg
1054 #print '2- oname: <%r>' % oname # dbg
1049 except UnicodeEncodeError:
1055 except UnicodeEncodeError:
1050 print 'Python identifiers can only contain ascii characters.'
1056 print 'Python identifiers can only contain ascii characters.'
1051 return dict(found=False)
1057 return dict(found=False)
1052
1058
1053 alias_ns = None
1059 alias_ns = None
1054 if namespaces is None:
1060 if namespaces is None:
1055 # Namespaces to search in:
1061 # Namespaces to search in:
1056 # Put them in a list. The order is important so that we
1062 # Put them in a list. The order is important so that we
1057 # find things in the same order that Python finds them.
1063 # find things in the same order that Python finds them.
1058 namespaces = [ ('Interactive', self.user_ns),
1064 namespaces = [ ('Interactive', self.user_ns),
1059 ('IPython internal', self.internal_ns),
1065 ('IPython internal', self.internal_ns),
1060 ('Python builtin', __builtin__.__dict__),
1066 ('Python builtin', __builtin__.__dict__),
1061 ('Alias', self.alias_manager.alias_table),
1067 ('Alias', self.alias_manager.alias_table),
1062 ]
1068 ]
1063 alias_ns = self.alias_manager.alias_table
1069 alias_ns = self.alias_manager.alias_table
1064
1070
1065 # initialize results to 'null'
1071 # initialize results to 'null'
1066 found = False; obj = None; ospace = None; ds = None;
1072 found = False; obj = None; ospace = None; ds = None;
1067 ismagic = False; isalias = False; parent = None
1073 ismagic = False; isalias = False; parent = None
1068
1074
1069 # We need to special-case 'print', which as of python2.6 registers as a
1075 # We need to special-case 'print', which as of python2.6 registers as a
1070 # function but should only be treated as one if print_function was
1076 # function but should only be treated as one if print_function was
1071 # loaded with a future import. In this case, just bail.
1077 # loaded with a future import. In this case, just bail.
1072 if (oname == 'print' and not (self.compile.compiler.flags &
1078 if (oname == 'print' and not (self.compile.compiler.flags &
1073 __future__.CO_FUTURE_PRINT_FUNCTION)):
1079 __future__.CO_FUTURE_PRINT_FUNCTION)):
1074 return {'found':found, 'obj':obj, 'namespace':ospace,
1080 return {'found':found, 'obj':obj, 'namespace':ospace,
1075 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1081 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1076
1082
1077 # Look for the given name by splitting it in parts. If the head is
1083 # Look for the given name by splitting it in parts. If the head is
1078 # found, then we look for all the remaining parts as members, and only
1084 # found, then we look for all the remaining parts as members, and only
1079 # declare success if we can find them all.
1085 # declare success if we can find them all.
1080 oname_parts = oname.split('.')
1086 oname_parts = oname.split('.')
1081 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1087 oname_head, oname_rest = oname_parts[0],oname_parts[1:]
1082 for nsname,ns in namespaces:
1088 for nsname,ns in namespaces:
1083 try:
1089 try:
1084 obj = ns[oname_head]
1090 obj = ns[oname_head]
1085 except KeyError:
1091 except KeyError:
1086 continue
1092 continue
1087 else:
1093 else:
1088 #print 'oname_rest:', oname_rest # dbg
1094 #print 'oname_rest:', oname_rest # dbg
1089 for part in oname_rest:
1095 for part in oname_rest:
1090 try:
1096 try:
1091 parent = obj
1097 parent = obj
1092 obj = getattr(obj,part)
1098 obj = getattr(obj,part)
1093 except:
1099 except:
1094 # Blanket except b/c some badly implemented objects
1100 # Blanket except b/c some badly implemented objects
1095 # allow __getattr__ to raise exceptions other than
1101 # allow __getattr__ to raise exceptions other than
1096 # AttributeError, which then crashes IPython.
1102 # AttributeError, which then crashes IPython.
1097 break
1103 break
1098 else:
1104 else:
1099 # If we finish the for loop (no break), we got all members
1105 # If we finish the for loop (no break), we got all members
1100 found = True
1106 found = True
1101 ospace = nsname
1107 ospace = nsname
1102 if ns == alias_ns:
1108 if ns == alias_ns:
1103 isalias = True
1109 isalias = True
1104 break # namespace loop
1110 break # namespace loop
1105
1111
1106 # Try to see if it's magic
1112 # Try to see if it's magic
1107 if not found:
1113 if not found:
1108 if oname.startswith(ESC_MAGIC):
1114 if oname.startswith(ESC_MAGIC):
1109 oname = oname[1:]
1115 oname = oname[1:]
1110 obj = getattr(self,'magic_'+oname,None)
1116 obj = getattr(self,'magic_'+oname,None)
1111 if obj is not None:
1117 if obj is not None:
1112 found = True
1118 found = True
1113 ospace = 'IPython internal'
1119 ospace = 'IPython internal'
1114 ismagic = True
1120 ismagic = True
1115
1121
1116 # Last try: special-case some literals like '', [], {}, etc:
1122 # Last try: special-case some literals like '', [], {}, etc:
1117 if not found and oname_head in ["''",'""','[]','{}','()']:
1123 if not found and oname_head in ["''",'""','[]','{}','()']:
1118 obj = eval(oname_head)
1124 obj = eval(oname_head)
1119 found = True
1125 found = True
1120 ospace = 'Interactive'
1126 ospace = 'Interactive'
1121
1127
1122 return {'found':found, 'obj':obj, 'namespace':ospace,
1128 return {'found':found, 'obj':obj, 'namespace':ospace,
1123 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1129 'ismagic':ismagic, 'isalias':isalias, 'parent':parent}
1124
1130
1125 def _ofind_property(self, oname, info):
1131 def _ofind_property(self, oname, info):
1126 """Second part of object finding, to look for property details."""
1132 """Second part of object finding, to look for property details."""
1127 if info.found:
1133 if info.found:
1128 # Get the docstring of the class property if it exists.
1134 # Get the docstring of the class property if it exists.
1129 path = oname.split('.')
1135 path = oname.split('.')
1130 root = '.'.join(path[:-1])
1136 root = '.'.join(path[:-1])
1131 if info.parent is not None:
1137 if info.parent is not None:
1132 try:
1138 try:
1133 target = getattr(info.parent, '__class__')
1139 target = getattr(info.parent, '__class__')
1134 # The object belongs to a class instance.
1140 # The object belongs to a class instance.
1135 try:
1141 try:
1136 target = getattr(target, path[-1])
1142 target = getattr(target, path[-1])
1137 # The class defines the object.
1143 # The class defines the object.
1138 if isinstance(target, property):
1144 if isinstance(target, property):
1139 oname = root + '.__class__.' + path[-1]
1145 oname = root + '.__class__.' + path[-1]
1140 info = Struct(self._ofind(oname))
1146 info = Struct(self._ofind(oname))
1141 except AttributeError: pass
1147 except AttributeError: pass
1142 except AttributeError: pass
1148 except AttributeError: pass
1143
1149
1144 # We return either the new info or the unmodified input if the object
1150 # We return either the new info or the unmodified input if the object
1145 # hadn't been found
1151 # hadn't been found
1146 return info
1152 return info
1147
1153
1148 def _object_find(self, oname, namespaces=None):
1154 def _object_find(self, oname, namespaces=None):
1149 """Find an object and return a struct with info about it."""
1155 """Find an object and return a struct with info about it."""
1150 inf = Struct(self._ofind(oname, namespaces))
1156 inf = Struct(self._ofind(oname, namespaces))
1151 return Struct(self._ofind_property(oname, inf))
1157 return Struct(self._ofind_property(oname, inf))
1152
1158
1153 def _inspect(self, meth, oname, namespaces=None, **kw):
1159 def _inspect(self, meth, oname, namespaces=None, **kw):
1154 """Generic interface to the inspector system.
1160 """Generic interface to the inspector system.
1155
1161
1156 This function is meant to be called by pdef, pdoc & friends."""
1162 This function is meant to be called by pdef, pdoc & friends."""
1157 info = self._object_find(oname)
1163 info = self._object_find(oname)
1158 if info.found:
1164 if info.found:
1159 pmethod = getattr(self.inspector, meth)
1165 pmethod = getattr(self.inspector, meth)
1160 formatter = format_screen if info.ismagic else None
1166 formatter = format_screen if info.ismagic else None
1161 if meth == 'pdoc':
1167 if meth == 'pdoc':
1162 pmethod(info.obj, oname, formatter)
1168 pmethod(info.obj, oname, formatter)
1163 elif meth == 'pinfo':
1169 elif meth == 'pinfo':
1164 pmethod(info.obj, oname, formatter, info, **kw)
1170 pmethod(info.obj, oname, formatter, info, **kw)
1165 else:
1171 else:
1166 pmethod(info.obj, oname)
1172 pmethod(info.obj, oname)
1167 else:
1173 else:
1168 print 'Object `%s` not found.' % oname
1174 print 'Object `%s` not found.' % oname
1169 return 'not found' # so callers can take other action
1175 return 'not found' # so callers can take other action
1170
1176
1171 def object_inspect(self, oname):
1177 def object_inspect(self, oname):
1172 info = self._object_find(oname)
1178 info = self._object_find(oname)
1173 if info.found:
1179 if info.found:
1174 return self.inspector.info(info.obj, info=info)
1180 return self.inspector.info(info.obj, info=info)
1175 else:
1181 else:
1176 return oinspect.mk_object_info({'found' : False})
1182 return oinspect.mk_object_info({'found' : False})
1177
1183
1178 #-------------------------------------------------------------------------
1184 #-------------------------------------------------------------------------
1179 # Things related to history management
1185 # Things related to history management
1180 #-------------------------------------------------------------------------
1186 #-------------------------------------------------------------------------
1181
1187
1182 def init_history(self):
1188 def init_history(self):
1183 # List of input with multi-line handling.
1189 # List of input with multi-line handling.
1184 self.input_hist = InputList()
1190 self.input_hist = InputList()
1185 # This one will hold the 'raw' input history, without any
1191 # This one will hold the 'raw' input history, without any
1186 # pre-processing. This will allow users to retrieve the input just as
1192 # pre-processing. This will allow users to retrieve the input just as
1187 # it was exactly typed in by the user, with %hist -r.
1193 # it was exactly typed in by the user, with %hist -r.
1188 self.input_hist_raw = InputList()
1194 self.input_hist_raw = InputList()
1189
1195
1190 # list of visited directories
1196 # list of visited directories
1191 try:
1197 try:
1192 self.dir_hist = [os.getcwd()]
1198 self.dir_hist = [os.getcwd()]
1193 except OSError:
1199 except OSError:
1194 self.dir_hist = []
1200 self.dir_hist = []
1195
1201
1196 # dict of output history
1202 # dict of output history
1197 self.output_hist = {}
1203 self.output_hist = {}
1198
1204
1199 # Now the history file
1205 # Now the history file
1200 if self.profile:
1206 if self.profile:
1201 histfname = 'history-%s' % self.profile
1207 histfname = 'history-%s' % self.profile
1202 else:
1208 else:
1203 histfname = 'history'
1209 histfname = 'history'
1204 self.histfile = os.path.join(self.ipython_dir, histfname)
1210 self.histfile = os.path.join(self.ipython_dir, histfname)
1205
1211
1206 # Fill the history zero entry, user counter starts at 1
1212 # Fill the history zero entry, user counter starts at 1
1207 self.input_hist.append('\n')
1213 self.input_hist.append('\n')
1208 self.input_hist_raw.append('\n')
1214 self.input_hist_raw.append('\n')
1209
1215
1210 def init_shadow_hist(self):
1216 def init_shadow_hist(self):
1211 try:
1217 try:
1212 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1218 self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db")
1213 except exceptions.UnicodeDecodeError:
1219 except exceptions.UnicodeDecodeError:
1214 print "Your ipython_dir can't be decoded to unicode!"
1220 print "Your ipython_dir can't be decoded to unicode!"
1215 print "Please set HOME environment variable to something that"
1221 print "Please set HOME environment variable to something that"
1216 print r"only has ASCII characters, e.g. c:\home"
1222 print r"only has ASCII characters, e.g. c:\home"
1217 print "Now it is", self.ipython_dir
1223 print "Now it is", self.ipython_dir
1218 sys.exit()
1224 sys.exit()
1219 self.shadowhist = ipcorehist.ShadowHist(self.db)
1225 self.shadowhist = ipcorehist.ShadowHist(self.db)
1220
1226
1221 def savehist(self):
1227 def savehist(self):
1222 """Save input history to a file (via readline library)."""
1228 """Save input history to a file (via readline library)."""
1223
1229
1224 try:
1230 try:
1225 self.readline.write_history_file(self.histfile)
1231 self.readline.write_history_file(self.histfile)
1226 except:
1232 except:
1227 print 'Unable to save IPython command history to file: ' + \
1233 print 'Unable to save IPython command history to file: ' + \
1228 `self.histfile`
1234 `self.histfile`
1229
1235
1230 def reloadhist(self):
1236 def reloadhist(self):
1231 """Reload the input history from disk file."""
1237 """Reload the input history from disk file."""
1232
1238
1233 try:
1239 try:
1234 self.readline.clear_history()
1240 self.readline.clear_history()
1235 self.readline.read_history_file(self.shell.histfile)
1241 self.readline.read_history_file(self.shell.histfile)
1236 except AttributeError:
1242 except AttributeError:
1237 pass
1243 pass
1238
1244
1239 def history_saving_wrapper(self, func):
1245 def history_saving_wrapper(self, func):
1240 """ Wrap func for readline history saving
1246 """ Wrap func for readline history saving
1241
1247
1242 Convert func into callable that saves & restores
1248 Convert func into callable that saves & restores
1243 history around the call """
1249 history around the call """
1244
1250
1245 if self.has_readline:
1251 if self.has_readline:
1246 from IPython.utils import rlineimpl as readline
1252 from IPython.utils import rlineimpl as readline
1247 else:
1253 else:
1248 return func
1254 return func
1249
1255
1250 def wrapper():
1256 def wrapper():
1251 self.savehist()
1257 self.savehist()
1252 try:
1258 try:
1253 func()
1259 func()
1254 finally:
1260 finally:
1255 readline.read_history_file(self.histfile)
1261 readline.read_history_file(self.histfile)
1256 return wrapper
1262 return wrapper
1257
1263
1258 def get_history(self, index=None, raw=False, output=True):
1264 def get_history(self, index=None, raw=False, output=True):
1259 """Get the history list.
1265 """Get the history list.
1260
1266
1261 Get the input and output history.
1267 Get the input and output history.
1262
1268
1263 Parameters
1269 Parameters
1264 ----------
1270 ----------
1265 index : n or (n1, n2) or None
1271 index : n or (n1, n2) or None
1266 If n, then the last entries. If a tuple, then all in
1272 If n, then the last entries. If a tuple, then all in
1267 range(n1, n2). If None, then all entries. Raises IndexError if
1273 range(n1, n2). If None, then all entries. Raises IndexError if
1268 the format of index is incorrect.
1274 the format of index is incorrect.
1269 raw : bool
1275 raw : bool
1270 If True, return the raw input.
1276 If True, return the raw input.
1271 output : bool
1277 output : bool
1272 If True, then return the output as well.
1278 If True, then return the output as well.
1273
1279
1274 Returns
1280 Returns
1275 -------
1281 -------
1276 If output is True, then return a dict of tuples, keyed by the prompt
1282 If output is True, then return a dict of tuples, keyed by the prompt
1277 numbers and with values of (input, output). If output is False, then
1283 numbers and with values of (input, output). If output is False, then
1278 a dict, keyed by the prompt number with the values of input. Raises
1284 a dict, keyed by the prompt number with the values of input. Raises
1279 IndexError if no history is found.
1285 IndexError if no history is found.
1280 """
1286 """
1281 if raw:
1287 if raw:
1282 input_hist = self.input_hist_raw
1288 input_hist = self.input_hist_raw
1283 else:
1289 else:
1284 input_hist = self.input_hist
1290 input_hist = self.input_hist
1285 if output:
1291 if output:
1286 output_hist = self.user_ns['Out']
1292 output_hist = self.user_ns['Out']
1287 n = len(input_hist)
1293 n = len(input_hist)
1288 if index is None:
1294 if index is None:
1289 start=0; stop=n
1295 start=0; stop=n
1290 elif isinstance(index, int):
1296 elif isinstance(index, int):
1291 start=n-index; stop=n
1297 start=n-index; stop=n
1292 elif isinstance(index, tuple) and len(index) == 2:
1298 elif isinstance(index, tuple) and len(index) == 2:
1293 start=index[0]; stop=index[1]
1299 start=index[0]; stop=index[1]
1294 else:
1300 else:
1295 raise IndexError('Not a valid index for the input history: %r'
1301 raise IndexError('Not a valid index for the input history: %r'
1296 % index)
1302 % index)
1297 hist = {}
1303 hist = {}
1298 for i in range(start, stop):
1304 for i in range(start, stop):
1299 if output:
1305 if output:
1300 hist[i] = (input_hist[i], output_hist.get(i))
1306 hist[i] = (input_hist[i], output_hist.get(i))
1301 else:
1307 else:
1302 hist[i] = input_hist[i]
1308 hist[i] = input_hist[i]
1303 if len(hist)==0:
1309 if len(hist)==0:
1304 raise IndexError('No history for range of indices: %r' % index)
1310 raise IndexError('No history for range of indices: %r' % index)
1305 return hist
1311 return hist
1306
1312
1307 #-------------------------------------------------------------------------
1313 #-------------------------------------------------------------------------
1308 # Things related to exception handling and tracebacks (not debugging)
1314 # Things related to exception handling and tracebacks (not debugging)
1309 #-------------------------------------------------------------------------
1315 #-------------------------------------------------------------------------
1310
1316
1311 def init_traceback_handlers(self, custom_exceptions):
1317 def init_traceback_handlers(self, custom_exceptions):
1312 # Syntax error handler.
1318 # Syntax error handler.
1313 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1319 self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor')
1314
1320
1315 # The interactive one is initialized with an offset, meaning we always
1321 # The interactive one is initialized with an offset, meaning we always
1316 # want to remove the topmost item in the traceback, which is our own
1322 # want to remove the topmost item in the traceback, which is our own
1317 # internal code. Valid modes: ['Plain','Context','Verbose']
1323 # internal code. Valid modes: ['Plain','Context','Verbose']
1318 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1324 self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain',
1319 color_scheme='NoColor',
1325 color_scheme='NoColor',
1320 tb_offset = 1)
1326 tb_offset = 1)
1321
1327
1322 # The instance will store a pointer to the system-wide exception hook,
1328 # The instance will store a pointer to the system-wide exception hook,
1323 # so that runtime code (such as magics) can access it. This is because
1329 # so that runtime code (such as magics) can access it. This is because
1324 # during the read-eval loop, it may get temporarily overwritten.
1330 # during the read-eval loop, it may get temporarily overwritten.
1325 self.sys_excepthook = sys.excepthook
1331 self.sys_excepthook = sys.excepthook
1326
1332
1327 # and add any custom exception handlers the user may have specified
1333 # and add any custom exception handlers the user may have specified
1328 self.set_custom_exc(*custom_exceptions)
1334 self.set_custom_exc(*custom_exceptions)
1329
1335
1330 # Set the exception mode
1336 # Set the exception mode
1331 self.InteractiveTB.set_mode(mode=self.xmode)
1337 self.InteractiveTB.set_mode(mode=self.xmode)
1332
1338
1333 def set_custom_exc(self, exc_tuple, handler):
1339 def set_custom_exc(self, exc_tuple, handler):
1334 """set_custom_exc(exc_tuple,handler)
1340 """set_custom_exc(exc_tuple,handler)
1335
1341
1336 Set a custom exception handler, which will be called if any of the
1342 Set a custom exception handler, which will be called if any of the
1337 exceptions in exc_tuple occur in the mainloop (specifically, in the
1343 exceptions in exc_tuple occur in the mainloop (specifically, in the
1338 runcode() method.
1344 runcode() method.
1339
1345
1340 Inputs:
1346 Inputs:
1341
1347
1342 - exc_tuple: a *tuple* of valid exceptions to call the defined
1348 - exc_tuple: a *tuple* of valid exceptions to call the defined
1343 handler for. It is very important that you use a tuple, and NOT A
1349 handler for. It is very important that you use a tuple, and NOT A
1344 LIST here, because of the way Python's except statement works. If
1350 LIST here, because of the way Python's except statement works. If
1345 you only want to trap a single exception, use a singleton tuple:
1351 you only want to trap a single exception, use a singleton tuple:
1346
1352
1347 exc_tuple == (MyCustomException,)
1353 exc_tuple == (MyCustomException,)
1348
1354
1349 - handler: this must be defined as a function with the following
1355 - handler: this must be defined as a function with the following
1350 basic interface::
1356 basic interface::
1351
1357
1352 def my_handler(self, etype, value, tb, tb_offset=None)
1358 def my_handler(self, etype, value, tb, tb_offset=None)
1353 ...
1359 ...
1354 # The return value must be
1360 # The return value must be
1355 return structured_traceback
1361 return structured_traceback
1356
1362
1357 This will be made into an instance method (via new.instancemethod)
1363 This will be made into an instance method (via new.instancemethod)
1358 of IPython itself, and it will be called if any of the exceptions
1364 of IPython itself, and it will be called if any of the exceptions
1359 listed in the exc_tuple are caught. If the handler is None, an
1365 listed in the exc_tuple are caught. If the handler is None, an
1360 internal basic one is used, which just prints basic info.
1366 internal basic one is used, which just prints basic info.
1361
1367
1362 WARNING: by putting in your own exception handler into IPython's main
1368 WARNING: by putting in your own exception handler into IPython's main
1363 execution loop, you run a very good chance of nasty crashes. This
1369 execution loop, you run a very good chance of nasty crashes. This
1364 facility should only be used if you really know what you are doing."""
1370 facility should only be used if you really know what you are doing."""
1365
1371
1366 assert type(exc_tuple)==type(()) , \
1372 assert type(exc_tuple)==type(()) , \
1367 "The custom exceptions must be given AS A TUPLE."
1373 "The custom exceptions must be given AS A TUPLE."
1368
1374
1369 def dummy_handler(self,etype,value,tb):
1375 def dummy_handler(self,etype,value,tb):
1370 print '*** Simple custom exception handler ***'
1376 print '*** Simple custom exception handler ***'
1371 print 'Exception type :',etype
1377 print 'Exception type :',etype
1372 print 'Exception value:',value
1378 print 'Exception value:',value
1373 print 'Traceback :',tb
1379 print 'Traceback :',tb
1374 print 'Source code :','\n'.join(self.buffer)
1380 print 'Source code :','\n'.join(self.buffer)
1375
1381
1376 if handler is None: handler = dummy_handler
1382 if handler is None: handler = dummy_handler
1377
1383
1378 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1384 self.CustomTB = new.instancemethod(handler,self,self.__class__)
1379 self.custom_exceptions = exc_tuple
1385 self.custom_exceptions = exc_tuple
1380
1386
1381 def excepthook(self, etype, value, tb):
1387 def excepthook(self, etype, value, tb):
1382 """One more defense for GUI apps that call sys.excepthook.
1388 """One more defense for GUI apps that call sys.excepthook.
1383
1389
1384 GUI frameworks like wxPython trap exceptions and call
1390 GUI frameworks like wxPython trap exceptions and call
1385 sys.excepthook themselves. I guess this is a feature that
1391 sys.excepthook themselves. I guess this is a feature that
1386 enables them to keep running after exceptions that would
1392 enables them to keep running after exceptions that would
1387 otherwise kill their mainloop. This is a bother for IPython
1393 otherwise kill their mainloop. This is a bother for IPython
1388 which excepts to catch all of the program exceptions with a try:
1394 which excepts to catch all of the program exceptions with a try:
1389 except: statement.
1395 except: statement.
1390
1396
1391 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1397 Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
1392 any app directly invokes sys.excepthook, it will look to the user like
1398 any app directly invokes sys.excepthook, it will look to the user like
1393 IPython crashed. In order to work around this, we can disable the
1399 IPython crashed. In order to work around this, we can disable the
1394 CrashHandler and replace it with this excepthook instead, which prints a
1400 CrashHandler and replace it with this excepthook instead, which prints a
1395 regular traceback using our InteractiveTB. In this fashion, apps which
1401 regular traceback using our InteractiveTB. In this fashion, apps which
1396 call sys.excepthook will generate a regular-looking exception from
1402 call sys.excepthook will generate a regular-looking exception from
1397 IPython, and the CrashHandler will only be triggered by real IPython
1403 IPython, and the CrashHandler will only be triggered by real IPython
1398 crashes.
1404 crashes.
1399
1405
1400 This hook should be used sparingly, only in places which are not likely
1406 This hook should be used sparingly, only in places which are not likely
1401 to be true IPython errors.
1407 to be true IPython errors.
1402 """
1408 """
1403 self.showtraceback((etype,value,tb),tb_offset=0)
1409 self.showtraceback((etype,value,tb),tb_offset=0)
1404
1410
1405 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1411 def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None,
1406 exception_only=False):
1412 exception_only=False):
1407 """Display the exception that just occurred.
1413 """Display the exception that just occurred.
1408
1414
1409 If nothing is known about the exception, this is the method which
1415 If nothing is known about the exception, this is the method which
1410 should be used throughout the code for presenting user tracebacks,
1416 should be used throughout the code for presenting user tracebacks,
1411 rather than directly invoking the InteractiveTB object.
1417 rather than directly invoking the InteractiveTB object.
1412
1418
1413 A specific showsyntaxerror() also exists, but this method can take
1419 A specific showsyntaxerror() also exists, but this method can take
1414 care of calling it if needed, so unless you are explicitly catching a
1420 care of calling it if needed, so unless you are explicitly catching a
1415 SyntaxError exception, don't try to analyze the stack manually and
1421 SyntaxError exception, don't try to analyze the stack manually and
1416 simply call this method."""
1422 simply call this method."""
1417
1423
1418 try:
1424 try:
1419 if exc_tuple is None:
1425 if exc_tuple is None:
1420 etype, value, tb = sys.exc_info()
1426 etype, value, tb = sys.exc_info()
1421 else:
1427 else:
1422 etype, value, tb = exc_tuple
1428 etype, value, tb = exc_tuple
1423
1429
1424 if etype is None:
1430 if etype is None:
1425 if hasattr(sys, 'last_type'):
1431 if hasattr(sys, 'last_type'):
1426 etype, value, tb = sys.last_type, sys.last_value, \
1432 etype, value, tb = sys.last_type, sys.last_value, \
1427 sys.last_traceback
1433 sys.last_traceback
1428 else:
1434 else:
1429 self.write_err('No traceback available to show.\n')
1435 self.write_err('No traceback available to show.\n')
1430 return
1436 return
1431
1437
1432 if etype is SyntaxError:
1438 if etype is SyntaxError:
1433 # Though this won't be called by syntax errors in the input
1439 # Though this won't be called by syntax errors in the input
1434 # line, there may be SyntaxError cases whith imported code.
1440 # line, there may be SyntaxError cases whith imported code.
1435 self.showsyntaxerror(filename)
1441 self.showsyntaxerror(filename)
1436 elif etype is UsageError:
1442 elif etype is UsageError:
1437 print "UsageError:", value
1443 print "UsageError:", value
1438 else:
1444 else:
1439 # WARNING: these variables are somewhat deprecated and not
1445 # WARNING: these variables are somewhat deprecated and not
1440 # necessarily safe to use in a threaded environment, but tools
1446 # necessarily safe to use in a threaded environment, but tools
1441 # like pdb depend on their existence, so let's set them. If we
1447 # like pdb depend on their existence, so let's set them. If we
1442 # find problems in the field, we'll need to revisit their use.
1448 # find problems in the field, we'll need to revisit their use.
1443 sys.last_type = etype
1449 sys.last_type = etype
1444 sys.last_value = value
1450 sys.last_value = value
1445 sys.last_traceback = tb
1451 sys.last_traceback = tb
1446
1452
1447 if etype in self.custom_exceptions:
1453 if etype in self.custom_exceptions:
1448 # FIXME: Old custom traceback objects may just return a
1454 # FIXME: Old custom traceback objects may just return a
1449 # string, in that case we just put it into a list
1455 # string, in that case we just put it into a list
1450 stb = self.CustomTB(etype, value, tb, tb_offset)
1456 stb = self.CustomTB(etype, value, tb, tb_offset)
1451 if isinstance(ctb, basestring):
1457 if isinstance(ctb, basestring):
1452 stb = [stb]
1458 stb = [stb]
1453 else:
1459 else:
1454 if exception_only:
1460 if exception_only:
1455 stb = ['An exception has occurred, use %tb to see '
1461 stb = ['An exception has occurred, use %tb to see '
1456 'the full traceback.\n']
1462 'the full traceback.\n']
1457 stb.extend(self.InteractiveTB.get_exception_only(etype,
1463 stb.extend(self.InteractiveTB.get_exception_only(etype,
1458 value))
1464 value))
1459 else:
1465 else:
1460 stb = self.InteractiveTB.structured_traceback(etype,
1466 stb = self.InteractiveTB.structured_traceback(etype,
1461 value, tb, tb_offset=tb_offset)
1467 value, tb, tb_offset=tb_offset)
1462 # FIXME: the pdb calling should be done by us, not by
1468 # FIXME: the pdb calling should be done by us, not by
1463 # the code computing the traceback.
1469 # the code computing the traceback.
1464 if self.InteractiveTB.call_pdb:
1470 if self.InteractiveTB.call_pdb:
1465 # pdb mucks up readline, fix it back
1471 # pdb mucks up readline, fix it back
1466 self.set_readline_completer()
1472 self.set_readline_completer()
1467
1473
1468 # Actually show the traceback
1474 # Actually show the traceback
1469 self._showtraceback(etype, value, stb)
1475 self._showtraceback(etype, value, stb)
1470
1476
1471 except KeyboardInterrupt:
1477 except KeyboardInterrupt:
1472 self.write_err("\nKeyboardInterrupt\n")
1478 self.write_err("\nKeyboardInterrupt\n")
1473
1479
1474 def _showtraceback(self, etype, evalue, stb):
1480 def _showtraceback(self, etype, evalue, stb):
1475 """Actually show a traceback.
1481 """Actually show a traceback.
1476
1482
1477 Subclasses may override this method to put the traceback on a different
1483 Subclasses may override this method to put the traceback on a different
1478 place, like a side channel.
1484 place, like a side channel.
1479 """
1485 """
1480 # FIXME: this should use the proper write channels, but our test suite
1486 # FIXME: this should use the proper write channels, but our test suite
1481 # relies on it coming out of stdout...
1487 # relies on it coming out of stdout...
1482 print >> sys.stdout, self.InteractiveTB.stb2text(stb)
1488 print >> sys.stdout, self.InteractiveTB.stb2text(stb)
1483
1489
1484 def showsyntaxerror(self, filename=None):
1490 def showsyntaxerror(self, filename=None):
1485 """Display the syntax error that just occurred.
1491 """Display the syntax error that just occurred.
1486
1492
1487 This doesn't display a stack trace because there isn't one.
1493 This doesn't display a stack trace because there isn't one.
1488
1494
1489 If a filename is given, it is stuffed in the exception instead
1495 If a filename is given, it is stuffed in the exception instead
1490 of what was there before (because Python's parser always uses
1496 of what was there before (because Python's parser always uses
1491 "<string>" when reading from a string).
1497 "<string>" when reading from a string).
1492 """
1498 """
1493 etype, value, last_traceback = sys.exc_info()
1499 etype, value, last_traceback = sys.exc_info()
1494
1500
1495 # See note about these variables in showtraceback() above
1501 # See note about these variables in showtraceback() above
1496 sys.last_type = etype
1502 sys.last_type = etype
1497 sys.last_value = value
1503 sys.last_value = value
1498 sys.last_traceback = last_traceback
1504 sys.last_traceback = last_traceback
1499
1505
1500 if filename and etype is SyntaxError:
1506 if filename and etype is SyntaxError:
1501 # Work hard to stuff the correct filename in the exception
1507 # Work hard to stuff the correct filename in the exception
1502 try:
1508 try:
1503 msg, (dummy_filename, lineno, offset, line) = value
1509 msg, (dummy_filename, lineno, offset, line) = value
1504 except:
1510 except:
1505 # Not the format we expect; leave it alone
1511 # Not the format we expect; leave it alone
1506 pass
1512 pass
1507 else:
1513 else:
1508 # Stuff in the right filename
1514 # Stuff in the right filename
1509 try:
1515 try:
1510 # Assume SyntaxError is a class exception
1516 # Assume SyntaxError is a class exception
1511 value = SyntaxError(msg, (filename, lineno, offset, line))
1517 value = SyntaxError(msg, (filename, lineno, offset, line))
1512 except:
1518 except:
1513 # If that failed, assume SyntaxError is a string
1519 # If that failed, assume SyntaxError is a string
1514 value = msg, (filename, lineno, offset, line)
1520 value = msg, (filename, lineno, offset, line)
1515 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1521 stb = self.SyntaxTB.structured_traceback(etype, value, [])
1516 self._showtraceback(etype, value, stb)
1522 self._showtraceback(etype, value, stb)
1517
1523
1518 #-------------------------------------------------------------------------
1524 #-------------------------------------------------------------------------
1519 # Things related to readline
1525 # Things related to readline
1520 #-------------------------------------------------------------------------
1526 #-------------------------------------------------------------------------
1521
1527
1522 def init_readline(self):
1528 def init_readline(self):
1523 """Command history completion/saving/reloading."""
1529 """Command history completion/saving/reloading."""
1524
1530
1525 if self.readline_use:
1531 if self.readline_use:
1526 import IPython.utils.rlineimpl as readline
1532 import IPython.utils.rlineimpl as readline
1527
1533
1528 self.rl_next_input = None
1534 self.rl_next_input = None
1529 self.rl_do_indent = False
1535 self.rl_do_indent = False
1530
1536
1531 if not self.readline_use or not readline.have_readline:
1537 if not self.readline_use or not readline.have_readline:
1532 self.has_readline = False
1538 self.has_readline = False
1533 self.readline = None
1539 self.readline = None
1534 # Set a number of methods that depend on readline to be no-op
1540 # Set a number of methods that depend on readline to be no-op
1535 self.savehist = no_op
1541 self.savehist = no_op
1536 self.reloadhist = no_op
1542 self.reloadhist = no_op
1537 self.set_readline_completer = no_op
1543 self.set_readline_completer = no_op
1538 self.set_custom_completer = no_op
1544 self.set_custom_completer = no_op
1539 self.set_completer_frame = no_op
1545 self.set_completer_frame = no_op
1540 warn('Readline services not available or not loaded.')
1546 warn('Readline services not available or not loaded.')
1541 else:
1547 else:
1542 self.has_readline = True
1548 self.has_readline = True
1543 self.readline = readline
1549 self.readline = readline
1544 sys.modules['readline'] = readline
1550 sys.modules['readline'] = readline
1545
1551
1546 # Platform-specific configuration
1552 # Platform-specific configuration
1547 if os.name == 'nt':
1553 if os.name == 'nt':
1548 # FIXME - check with Frederick to see if we can harmonize
1554 # FIXME - check with Frederick to see if we can harmonize
1549 # naming conventions with pyreadline to avoid this
1555 # naming conventions with pyreadline to avoid this
1550 # platform-dependent check
1556 # platform-dependent check
1551 self.readline_startup_hook = readline.set_pre_input_hook
1557 self.readline_startup_hook = readline.set_pre_input_hook
1552 else:
1558 else:
1553 self.readline_startup_hook = readline.set_startup_hook
1559 self.readline_startup_hook = readline.set_startup_hook
1554
1560
1555 # Load user's initrc file (readline config)
1561 # Load user's initrc file (readline config)
1556 # Or if libedit is used, load editrc.
1562 # Or if libedit is used, load editrc.
1557 inputrc_name = os.environ.get('INPUTRC')
1563 inputrc_name = os.environ.get('INPUTRC')
1558 if inputrc_name is None:
1564 if inputrc_name is None:
1559 home_dir = get_home_dir()
1565 home_dir = get_home_dir()
1560 if home_dir is not None:
1566 if home_dir is not None:
1561 inputrc_name = '.inputrc'
1567 inputrc_name = '.inputrc'
1562 if readline.uses_libedit:
1568 if readline.uses_libedit:
1563 inputrc_name = '.editrc'
1569 inputrc_name = '.editrc'
1564 inputrc_name = os.path.join(home_dir, inputrc_name)
1570 inputrc_name = os.path.join(home_dir, inputrc_name)
1565 if os.path.isfile(inputrc_name):
1571 if os.path.isfile(inputrc_name):
1566 try:
1572 try:
1567 readline.read_init_file(inputrc_name)
1573 readline.read_init_file(inputrc_name)
1568 except:
1574 except:
1569 warn('Problems reading readline initialization file <%s>'
1575 warn('Problems reading readline initialization file <%s>'
1570 % inputrc_name)
1576 % inputrc_name)
1571
1577
1572 # Configure readline according to user's prefs
1578 # Configure readline according to user's prefs
1573 # This is only done if GNU readline is being used. If libedit
1579 # This is only done if GNU readline is being used. If libedit
1574 # is being used (as on Leopard) the readline config is
1580 # is being used (as on Leopard) the readline config is
1575 # not run as the syntax for libedit is different.
1581 # not run as the syntax for libedit is different.
1576 if not readline.uses_libedit:
1582 if not readline.uses_libedit:
1577 for rlcommand in self.readline_parse_and_bind:
1583 for rlcommand in self.readline_parse_and_bind:
1578 #print "loading rl:",rlcommand # dbg
1584 #print "loading rl:",rlcommand # dbg
1579 readline.parse_and_bind(rlcommand)
1585 readline.parse_and_bind(rlcommand)
1580
1586
1581 # Remove some chars from the delimiters list. If we encounter
1587 # Remove some chars from the delimiters list. If we encounter
1582 # unicode chars, discard them.
1588 # unicode chars, discard them.
1583 delims = readline.get_completer_delims().encode("ascii", "ignore")
1589 delims = readline.get_completer_delims().encode("ascii", "ignore")
1584 delims = delims.translate(string._idmap,
1590 delims = delims.translate(string._idmap,
1585 self.readline_remove_delims)
1591 self.readline_remove_delims)
1586 delims = delims.replace(ESC_MAGIC, '')
1592 delims = delims.replace(ESC_MAGIC, '')
1587 readline.set_completer_delims(delims)
1593 readline.set_completer_delims(delims)
1588 # otherwise we end up with a monster history after a while:
1594 # otherwise we end up with a monster history after a while:
1589 readline.set_history_length(1000)
1595 readline.set_history_length(1000)
1590 try:
1596 try:
1591 #print '*** Reading readline history' # dbg
1597 #print '*** Reading readline history' # dbg
1592 readline.read_history_file(self.histfile)
1598 readline.read_history_file(self.histfile)
1593 except IOError:
1599 except IOError:
1594 pass # It doesn't exist yet.
1600 pass # It doesn't exist yet.
1595
1601
1596 # If we have readline, we want our history saved upon ipython
1602 # If we have readline, we want our history saved upon ipython
1597 # exiting.
1603 # exiting.
1598 atexit.register(self.savehist)
1604 atexit.register(self.savehist)
1599
1605
1600 # Configure auto-indent for all platforms
1606 # Configure auto-indent for all platforms
1601 self.set_autoindent(self.autoindent)
1607 self.set_autoindent(self.autoindent)
1602
1608
1603 def set_next_input(self, s):
1609 def set_next_input(self, s):
1604 """ Sets the 'default' input string for the next command line.
1610 """ Sets the 'default' input string for the next command line.
1605
1611
1606 Requires readline.
1612 Requires readline.
1607
1613
1608 Example:
1614 Example:
1609
1615
1610 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1616 [D:\ipython]|1> _ip.set_next_input("Hello Word")
1611 [D:\ipython]|2> Hello Word_ # cursor is here
1617 [D:\ipython]|2> Hello Word_ # cursor is here
1612 """
1618 """
1613
1619
1614 self.rl_next_input = s
1620 self.rl_next_input = s
1615
1621
1616 # Maybe move this to the terminal subclass?
1622 # Maybe move this to the terminal subclass?
1617 def pre_readline(self):
1623 def pre_readline(self):
1618 """readline hook to be used at the start of each line.
1624 """readline hook to be used at the start of each line.
1619
1625
1620 Currently it handles auto-indent only."""
1626 Currently it handles auto-indent only."""
1621
1627
1622 if self.rl_do_indent:
1628 if self.rl_do_indent:
1623 self.readline.insert_text(self._indent_current_str())
1629 self.readline.insert_text(self._indent_current_str())
1624 if self.rl_next_input is not None:
1630 if self.rl_next_input is not None:
1625 self.readline.insert_text(self.rl_next_input)
1631 self.readline.insert_text(self.rl_next_input)
1626 self.rl_next_input = None
1632 self.rl_next_input = None
1627
1633
1628 def _indent_current_str(self):
1634 def _indent_current_str(self):
1629 """return the current level of indentation as a string"""
1635 """return the current level of indentation as a string"""
1630 return self.indent_current_nsp * ' '
1636 return self.indent_current_nsp * ' '
1631
1637
1632 #-------------------------------------------------------------------------
1638 #-------------------------------------------------------------------------
1633 # Things related to text completion
1639 # Things related to text completion
1634 #-------------------------------------------------------------------------
1640 #-------------------------------------------------------------------------
1635
1641
1636 def init_completer(self):
1642 def init_completer(self):
1637 """Initialize the completion machinery.
1643 """Initialize the completion machinery.
1638
1644
1639 This creates completion machinery that can be used by client code,
1645 This creates completion machinery that can be used by client code,
1640 either interactively in-process (typically triggered by the readline
1646 either interactively in-process (typically triggered by the readline
1641 library), programatically (such as in test suites) or out-of-prcess
1647 library), programatically (such as in test suites) or out-of-prcess
1642 (typically over the network by remote frontends).
1648 (typically over the network by remote frontends).
1643 """
1649 """
1644 from IPython.core.completer import IPCompleter
1650 from IPython.core.completer import IPCompleter
1645 from IPython.core.completerlib import (module_completer,
1651 from IPython.core.completerlib import (module_completer,
1646 magic_run_completer, cd_completer)
1652 magic_run_completer, cd_completer)
1647
1653
1648 self.Completer = IPCompleter(self,
1654 self.Completer = IPCompleter(self,
1649 self.user_ns,
1655 self.user_ns,
1650 self.user_global_ns,
1656 self.user_global_ns,
1651 self.readline_omit__names,
1657 self.readline_omit__names,
1652 self.alias_manager.alias_table,
1658 self.alias_manager.alias_table,
1653 self.has_readline)
1659 self.has_readline)
1654
1660
1655 # Add custom completers to the basic ones built into IPCompleter
1661 # Add custom completers to the basic ones built into IPCompleter
1656 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1662 sdisp = self.strdispatchers.get('complete_command', StrDispatch())
1657 self.strdispatchers['complete_command'] = sdisp
1663 self.strdispatchers['complete_command'] = sdisp
1658 self.Completer.custom_completers = sdisp
1664 self.Completer.custom_completers = sdisp
1659
1665
1660 self.set_hook('complete_command', module_completer, str_key = 'import')
1666 self.set_hook('complete_command', module_completer, str_key = 'import')
1661 self.set_hook('complete_command', module_completer, str_key = 'from')
1667 self.set_hook('complete_command', module_completer, str_key = 'from')
1662 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1668 self.set_hook('complete_command', magic_run_completer, str_key = '%run')
1663 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1669 self.set_hook('complete_command', cd_completer, str_key = '%cd')
1664
1670
1665 # Only configure readline if we truly are using readline. IPython can
1671 # Only configure readline if we truly are using readline. IPython can
1666 # do tab-completion over the network, in GUIs, etc, where readline
1672 # do tab-completion over the network, in GUIs, etc, where readline
1667 # itself may be absent
1673 # itself may be absent
1668 if self.has_readline:
1674 if self.has_readline:
1669 self.set_readline_completer()
1675 self.set_readline_completer()
1670
1676
1671 def complete(self, text, line=None, cursor_pos=None):
1677 def complete(self, text, line=None, cursor_pos=None):
1672 """Return the completed text and a list of completions.
1678 """Return the completed text and a list of completions.
1673
1679
1674 Parameters
1680 Parameters
1675 ----------
1681 ----------
1676
1682
1677 text : string
1683 text : string
1678 A string of text to be completed on. It can be given as empty and
1684 A string of text to be completed on. It can be given as empty and
1679 instead a line/position pair are given. In this case, the
1685 instead a line/position pair are given. In this case, the
1680 completer itself will split the line like readline does.
1686 completer itself will split the line like readline does.
1681
1687
1682 line : string, optional
1688 line : string, optional
1683 The complete line that text is part of.
1689 The complete line that text is part of.
1684
1690
1685 cursor_pos : int, optional
1691 cursor_pos : int, optional
1686 The position of the cursor on the input line.
1692 The position of the cursor on the input line.
1687
1693
1688 Returns
1694 Returns
1689 -------
1695 -------
1690 text : string
1696 text : string
1691 The actual text that was completed.
1697 The actual text that was completed.
1692
1698
1693 matches : list
1699 matches : list
1694 A sorted list with all possible completions.
1700 A sorted list with all possible completions.
1695
1701
1696 The optional arguments allow the completion to take more context into
1702 The optional arguments allow the completion to take more context into
1697 account, and are part of the low-level completion API.
1703 account, and are part of the low-level completion API.
1698
1704
1699 This is a wrapper around the completion mechanism, similar to what
1705 This is a wrapper around the completion mechanism, similar to what
1700 readline does at the command line when the TAB key is hit. By
1706 readline does at the command line when the TAB key is hit. By
1701 exposing it as a method, it can be used by other non-readline
1707 exposing it as a method, it can be used by other non-readline
1702 environments (such as GUIs) for text completion.
1708 environments (such as GUIs) for text completion.
1703
1709
1704 Simple usage example:
1710 Simple usage example:
1705
1711
1706 In [1]: x = 'hello'
1712 In [1]: x = 'hello'
1707
1713
1708 In [2]: _ip.complete('x.l')
1714 In [2]: _ip.complete('x.l')
1709 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1715 Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
1710 """
1716 """
1711
1717
1712 # Inject names into __builtin__ so we can complete on the added names.
1718 # Inject names into __builtin__ so we can complete on the added names.
1713 with self.builtin_trap:
1719 with self.builtin_trap:
1714 return self.Completer.complete(text, line, cursor_pos)
1720 return self.Completer.complete(text, line, cursor_pos)
1715
1721
1716 def set_custom_completer(self, completer, pos=0):
1722 def set_custom_completer(self, completer, pos=0):
1717 """Adds a new custom completer function.
1723 """Adds a new custom completer function.
1718
1724
1719 The position argument (defaults to 0) is the index in the completers
1725 The position argument (defaults to 0) is the index in the completers
1720 list where you want the completer to be inserted."""
1726 list where you want the completer to be inserted."""
1721
1727
1722 newcomp = new.instancemethod(completer,self.Completer,
1728 newcomp = new.instancemethod(completer,self.Completer,
1723 self.Completer.__class__)
1729 self.Completer.__class__)
1724 self.Completer.matchers.insert(pos,newcomp)
1730 self.Completer.matchers.insert(pos,newcomp)
1725
1731
1726 def set_readline_completer(self):
1732 def set_readline_completer(self):
1727 """Reset readline's completer to be our own."""
1733 """Reset readline's completer to be our own."""
1728 self.readline.set_completer(self.Completer.rlcomplete)
1734 self.readline.set_completer(self.Completer.rlcomplete)
1729
1735
1730 def set_completer_frame(self, frame=None):
1736 def set_completer_frame(self, frame=None):
1731 """Set the frame of the completer."""
1737 """Set the frame of the completer."""
1732 if frame:
1738 if frame:
1733 self.Completer.namespace = frame.f_locals
1739 self.Completer.namespace = frame.f_locals
1734 self.Completer.global_namespace = frame.f_globals
1740 self.Completer.global_namespace = frame.f_globals
1735 else:
1741 else:
1736 self.Completer.namespace = self.user_ns
1742 self.Completer.namespace = self.user_ns
1737 self.Completer.global_namespace = self.user_global_ns
1743 self.Completer.global_namespace = self.user_global_ns
1738
1744
1739 #-------------------------------------------------------------------------
1745 #-------------------------------------------------------------------------
1740 # Things related to magics
1746 # Things related to magics
1741 #-------------------------------------------------------------------------
1747 #-------------------------------------------------------------------------
1742
1748
1743 def init_magics(self):
1749 def init_magics(self):
1744 # FIXME: Move the color initialization to the DisplayHook, which
1750 # FIXME: Move the color initialization to the DisplayHook, which
1745 # should be split into a prompt manager and displayhook. We probably
1751 # should be split into a prompt manager and displayhook. We probably
1746 # even need a centralize colors management object.
1752 # even need a centralize colors management object.
1747 self.magic_colors(self.colors)
1753 self.magic_colors(self.colors)
1748 # History was moved to a separate module
1754 # History was moved to a separate module
1749 from . import history
1755 from . import history
1750 history.init_ipython(self)
1756 history.init_ipython(self)
1751
1757
1752 def magic(self,arg_s):
1758 def magic(self,arg_s):
1753 """Call a magic function by name.
1759 """Call a magic function by name.
1754
1760
1755 Input: a string containing the name of the magic function to call and
1761 Input: a string containing the name of the magic function to call and
1756 any additional arguments to be passed to the magic.
1762 any additional arguments to be passed to the magic.
1757
1763
1758 magic('name -opt foo bar') is equivalent to typing at the ipython
1764 magic('name -opt foo bar') is equivalent to typing at the ipython
1759 prompt:
1765 prompt:
1760
1766
1761 In[1]: %name -opt foo bar
1767 In[1]: %name -opt foo bar
1762
1768
1763 To call a magic without arguments, simply use magic('name').
1769 To call a magic without arguments, simply use magic('name').
1764
1770
1765 This provides a proper Python function to call IPython's magics in any
1771 This provides a proper Python function to call IPython's magics in any
1766 valid Python code you can type at the interpreter, including loops and
1772 valid Python code you can type at the interpreter, including loops and
1767 compound statements.
1773 compound statements.
1768 """
1774 """
1769 args = arg_s.split(' ',1)
1775 args = arg_s.split(' ',1)
1770 magic_name = args[0]
1776 magic_name = args[0]
1771 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1777 magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
1772
1778
1773 try:
1779 try:
1774 magic_args = args[1]
1780 magic_args = args[1]
1775 except IndexError:
1781 except IndexError:
1776 magic_args = ''
1782 magic_args = ''
1777 fn = getattr(self,'magic_'+magic_name,None)
1783 fn = getattr(self,'magic_'+magic_name,None)
1778 if fn is None:
1784 if fn is None:
1779 error("Magic function `%s` not found." % magic_name)
1785 error("Magic function `%s` not found." % magic_name)
1780 else:
1786 else:
1781 magic_args = self.var_expand(magic_args,1)
1787 magic_args = self.var_expand(magic_args,1)
1782 with nested(self.builtin_trap,):
1788 with nested(self.builtin_trap,):
1783 result = fn(magic_args)
1789 result = fn(magic_args)
1784 return result
1790 return result
1785
1791
1786 def define_magic(self, magicname, func):
1792 def define_magic(self, magicname, func):
1787 """Expose own function as magic function for ipython
1793 """Expose own function as magic function for ipython
1788
1794
1789 def foo_impl(self,parameter_s=''):
1795 def foo_impl(self,parameter_s=''):
1790 'My very own magic!. (Use docstrings, IPython reads them).'
1796 'My very own magic!. (Use docstrings, IPython reads them).'
1791 print 'Magic function. Passed parameter is between < >:'
1797 print 'Magic function. Passed parameter is between < >:'
1792 print '<%s>' % parameter_s
1798 print '<%s>' % parameter_s
1793 print 'The self object is:',self
1799 print 'The self object is:',self
1794
1800
1795 self.define_magic('foo',foo_impl)
1801 self.define_magic('foo',foo_impl)
1796 """
1802 """
1797
1803
1798 import new
1804 import new
1799 im = new.instancemethod(func,self, self.__class__)
1805 im = new.instancemethod(func,self, self.__class__)
1800 old = getattr(self, "magic_" + magicname, None)
1806 old = getattr(self, "magic_" + magicname, None)
1801 setattr(self, "magic_" + magicname, im)
1807 setattr(self, "magic_" + magicname, im)
1802 return old
1808 return old
1803
1809
1804 #-------------------------------------------------------------------------
1810 #-------------------------------------------------------------------------
1805 # Things related to macros
1811 # Things related to macros
1806 #-------------------------------------------------------------------------
1812 #-------------------------------------------------------------------------
1807
1813
1808 def define_macro(self, name, themacro):
1814 def define_macro(self, name, themacro):
1809 """Define a new macro
1815 """Define a new macro
1810
1816
1811 Parameters
1817 Parameters
1812 ----------
1818 ----------
1813 name : str
1819 name : str
1814 The name of the macro.
1820 The name of the macro.
1815 themacro : str or Macro
1821 themacro : str or Macro
1816 The action to do upon invoking the macro. If a string, a new
1822 The action to do upon invoking the macro. If a string, a new
1817 Macro object is created by passing the string to it.
1823 Macro object is created by passing the string to it.
1818 """
1824 """
1819
1825
1820 from IPython.core import macro
1826 from IPython.core import macro
1821
1827
1822 if isinstance(themacro, basestring):
1828 if isinstance(themacro, basestring):
1823 themacro = macro.Macro(themacro)
1829 themacro = macro.Macro(themacro)
1824 if not isinstance(themacro, macro.Macro):
1830 if not isinstance(themacro, macro.Macro):
1825 raise ValueError('A macro must be a string or a Macro instance.')
1831 raise ValueError('A macro must be a string or a Macro instance.')
1826 self.user_ns[name] = themacro
1832 self.user_ns[name] = themacro
1827
1833
1828 #-------------------------------------------------------------------------
1834 #-------------------------------------------------------------------------
1829 # Things related to the running of system commands
1835 # Things related to the running of system commands
1830 #-------------------------------------------------------------------------
1836 #-------------------------------------------------------------------------
1831
1837
1832 def system(self, cmd):
1838 def system(self, cmd):
1833 """Call the given cmd in a subprocess."""
1839 """Call the given cmd in a subprocess."""
1834 # We do not support backgrounding processes because we either use
1840 # We do not support backgrounding processes because we either use
1835 # pexpect or pipes to read from. Users can always just call
1841 # pexpect or pipes to read from. Users can always just call
1836 # os.system() if they really want a background process.
1842 # os.system() if they really want a background process.
1837 if cmd.endswith('&'):
1843 if cmd.endswith('&'):
1838 raise OSError("Background processes not supported.")
1844 raise OSError("Background processes not supported.")
1839
1845
1840 return system(self.var_expand(cmd, depth=2))
1846 return system(self.var_expand(cmd, depth=2))
1841
1847
1842 def getoutput(self, cmd):
1848 def getoutput(self, cmd):
1843 """Get output (possibly including stderr) from a subprocess."""
1849 """Get output (possibly including stderr) from a subprocess."""
1844 if cmd.endswith('&'):
1850 if cmd.endswith('&'):
1845 raise OSError("Background processes not supported.")
1851 raise OSError("Background processes not supported.")
1846 return getoutput(self.var_expand(cmd, depth=2))
1852 return getoutput(self.var_expand(cmd, depth=2))
1847
1853
1848 #-------------------------------------------------------------------------
1854 #-------------------------------------------------------------------------
1849 # Things related to aliases
1855 # Things related to aliases
1850 #-------------------------------------------------------------------------
1856 #-------------------------------------------------------------------------
1851
1857
1852 def init_alias(self):
1858 def init_alias(self):
1853 self.alias_manager = AliasManager(shell=self, config=self.config)
1859 self.alias_manager = AliasManager(shell=self, config=self.config)
1854 self.ns_table['alias'] = self.alias_manager.alias_table,
1860 self.ns_table['alias'] = self.alias_manager.alias_table,
1855
1861
1856 #-------------------------------------------------------------------------
1862 #-------------------------------------------------------------------------
1857 # Things related to extensions and plugins
1863 # Things related to extensions and plugins
1858 #-------------------------------------------------------------------------
1864 #-------------------------------------------------------------------------
1859
1865
1860 def init_extension_manager(self):
1866 def init_extension_manager(self):
1861 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1867 self.extension_manager = ExtensionManager(shell=self, config=self.config)
1862
1868
1863 def init_plugin_manager(self):
1869 def init_plugin_manager(self):
1864 self.plugin_manager = PluginManager(config=self.config)
1870 self.plugin_manager = PluginManager(config=self.config)
1865
1871
1866 #-------------------------------------------------------------------------
1872 #-------------------------------------------------------------------------
1867 # Things related to payloads
1873 # Things related to payloads
1868 #-------------------------------------------------------------------------
1874 #-------------------------------------------------------------------------
1869
1875
1870 def init_payload(self):
1876 def init_payload(self):
1871 self.payload_manager = PayloadManager(config=self.config)
1877 self.payload_manager = PayloadManager(config=self.config)
1872
1878
1873 #-------------------------------------------------------------------------
1879 #-------------------------------------------------------------------------
1874 # Things related to the prefilter
1880 # Things related to the prefilter
1875 #-------------------------------------------------------------------------
1881 #-------------------------------------------------------------------------
1876
1882
1877 def init_prefilter(self):
1883 def init_prefilter(self):
1878 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1884 self.prefilter_manager = PrefilterManager(shell=self, config=self.config)
1879 # Ultimately this will be refactored in the new interpreter code, but
1885 # Ultimately this will be refactored in the new interpreter code, but
1880 # for now, we should expose the main prefilter method (there's legacy
1886 # for now, we should expose the main prefilter method (there's legacy
1881 # code out there that may rely on this).
1887 # code out there that may rely on this).
1882 self.prefilter = self.prefilter_manager.prefilter_lines
1888 self.prefilter = self.prefilter_manager.prefilter_lines
1883
1889
1884
1890
1885 def auto_rewrite_input(self, cmd):
1891 def auto_rewrite_input(self, cmd):
1886 """Print to the screen the rewritten form of the user's command.
1892 """Print to the screen the rewritten form of the user's command.
1887
1893
1888 This shows visual feedback by rewriting input lines that cause
1894 This shows visual feedback by rewriting input lines that cause
1889 automatic calling to kick in, like::
1895 automatic calling to kick in, like::
1890
1896
1891 /f x
1897 /f x
1892
1898
1893 into::
1899 into::
1894
1900
1895 ------> f(x)
1901 ------> f(x)
1896
1902
1897 after the user's input prompt. This helps the user understand that the
1903 after the user's input prompt. This helps the user understand that the
1898 input line was transformed automatically by IPython.
1904 input line was transformed automatically by IPython.
1899 """
1905 """
1900 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1906 rw = self.displayhook.prompt1.auto_rewrite() + cmd
1901
1907
1902 try:
1908 try:
1903 # plain ascii works better w/ pyreadline, on some machines, so
1909 # plain ascii works better w/ pyreadline, on some machines, so
1904 # we use it and only print uncolored rewrite if we have unicode
1910 # we use it and only print uncolored rewrite if we have unicode
1905 rw = str(rw)
1911 rw = str(rw)
1906 print >> IPython.utils.io.Term.cout, rw
1912 print >> IPython.utils.io.Term.cout, rw
1907 except UnicodeEncodeError:
1913 except UnicodeEncodeError:
1908 print "------> " + cmd
1914 print "------> " + cmd
1909
1915
1910 #-------------------------------------------------------------------------
1916 #-------------------------------------------------------------------------
1911 # Things related to extracting values/expressions from kernel and user_ns
1917 # Things related to extracting values/expressions from kernel and user_ns
1912 #-------------------------------------------------------------------------
1918 #-------------------------------------------------------------------------
1913
1919
1914 def _simple_error(self):
1920 def _simple_error(self):
1915 etype, value = sys.exc_info()[:2]
1921 etype, value = sys.exc_info()[:2]
1916 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1922 return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value)
1917
1923
1918 def get_user_variables(self, names):
1924 def get_user_variables(self, names):
1919 """Get a list of variable names from the user's namespace.
1925 """Get a list of variable names from the user's namespace.
1920
1926
1921 The return value is a dict with the repr() of each value.
1927 The return value is a dict with the repr() of each value.
1922 """
1928 """
1923 out = {}
1929 out = {}
1924 user_ns = self.user_ns
1930 user_ns = self.user_ns
1925 for varname in names:
1931 for varname in names:
1926 try:
1932 try:
1927 value = repr(user_ns[varname])
1933 value = repr(user_ns[varname])
1928 except:
1934 except:
1929 value = self._simple_error()
1935 value = self._simple_error()
1930 out[varname] = value
1936 out[varname] = value
1931 return out
1937 return out
1932
1938
1933 def eval_expressions(self, expressions):
1939 def eval_expressions(self, expressions):
1934 """Evaluate a dict of expressions in the user's namespace.
1940 """Evaluate a dict of expressions in the user's namespace.
1935
1941
1936 The return value is a dict with the repr() of each value.
1942 The return value is a dict with the repr() of each value.
1937 """
1943 """
1938 out = {}
1944 out = {}
1939 user_ns = self.user_ns
1945 user_ns = self.user_ns
1940 global_ns = self.user_global_ns
1946 global_ns = self.user_global_ns
1941 for key, expr in expressions.iteritems():
1947 for key, expr in expressions.iteritems():
1942 try:
1948 try:
1943 value = repr(eval(expr, global_ns, user_ns))
1949 value = repr(eval(expr, global_ns, user_ns))
1944 except:
1950 except:
1945 value = self._simple_error()
1951 value = self._simple_error()
1946 out[key] = value
1952 out[key] = value
1947 return out
1953 return out
1948
1954
1949 #-------------------------------------------------------------------------
1955 #-------------------------------------------------------------------------
1950 # Things related to the running of code
1956 # Things related to the running of code
1951 #-------------------------------------------------------------------------
1957 #-------------------------------------------------------------------------
1952
1958
1953 def ex(self, cmd):
1959 def ex(self, cmd):
1954 """Execute a normal python statement in user namespace."""
1960 """Execute a normal python statement in user namespace."""
1955 with nested(self.builtin_trap,):
1961 with nested(self.builtin_trap,):
1956 exec cmd in self.user_global_ns, self.user_ns
1962 exec cmd in self.user_global_ns, self.user_ns
1957
1963
1958 def ev(self, expr):
1964 def ev(self, expr):
1959 """Evaluate python expression expr in user namespace.
1965 """Evaluate python expression expr in user namespace.
1960
1966
1961 Returns the result of evaluation
1967 Returns the result of evaluation
1962 """
1968 """
1963 with nested(self.builtin_trap,):
1969 with nested(self.builtin_trap,):
1964 return eval(expr, self.user_global_ns, self.user_ns)
1970 return eval(expr, self.user_global_ns, self.user_ns)
1965
1971
1966 def safe_execfile(self, fname, *where, **kw):
1972 def safe_execfile(self, fname, *where, **kw):
1967 """A safe version of the builtin execfile().
1973 """A safe version of the builtin execfile().
1968
1974
1969 This version will never throw an exception, but instead print
1975 This version will never throw an exception, but instead print
1970 helpful error messages to the screen. This only works on pure
1976 helpful error messages to the screen. This only works on pure
1971 Python files with the .py extension.
1977 Python files with the .py extension.
1972
1978
1973 Parameters
1979 Parameters
1974 ----------
1980 ----------
1975 fname : string
1981 fname : string
1976 The name of the file to be executed.
1982 The name of the file to be executed.
1977 where : tuple
1983 where : tuple
1978 One or two namespaces, passed to execfile() as (globals,locals).
1984 One or two namespaces, passed to execfile() as (globals,locals).
1979 If only one is given, it is passed as both.
1985 If only one is given, it is passed as both.
1980 exit_ignore : bool (False)
1986 exit_ignore : bool (False)
1981 If True, then silence SystemExit for non-zero status (it is always
1987 If True, then silence SystemExit for non-zero status (it is always
1982 silenced for zero status, as it is so common).
1988 silenced for zero status, as it is so common).
1983 """
1989 """
1984 kw.setdefault('exit_ignore', False)
1990 kw.setdefault('exit_ignore', False)
1985
1991
1986 fname = os.path.abspath(os.path.expanduser(fname))
1992 fname = os.path.abspath(os.path.expanduser(fname))
1987
1993
1988 # Make sure we have a .py file
1994 # Make sure we have a .py file
1989 if not fname.endswith('.py'):
1995 if not fname.endswith('.py'):
1990 warn('File must end with .py to be run using execfile: <%s>' % fname)
1996 warn('File must end with .py to be run using execfile: <%s>' % fname)
1991
1997
1992 # Make sure we can open the file
1998 # Make sure we can open the file
1993 try:
1999 try:
1994 with open(fname) as thefile:
2000 with open(fname) as thefile:
1995 pass
2001 pass
1996 except:
2002 except:
1997 warn('Could not open file <%s> for safe execution.' % fname)
2003 warn('Could not open file <%s> for safe execution.' % fname)
1998 return
2004 return
1999
2005
2000 # Find things also in current directory. This is needed to mimic the
2006 # Find things also in current directory. This is needed to mimic the
2001 # behavior of running a script from the system command line, where
2007 # behavior of running a script from the system command line, where
2002 # Python inserts the script's directory into sys.path
2008 # Python inserts the script's directory into sys.path
2003 dname = os.path.dirname(fname)
2009 dname = os.path.dirname(fname)
2004
2010
2005 with prepended_to_syspath(dname):
2011 with prepended_to_syspath(dname):
2006 try:
2012 try:
2007 execfile(fname,*where)
2013 execfile(fname,*where)
2008 except SystemExit, status:
2014 except SystemExit, status:
2009 # If the call was made with 0 or None exit status (sys.exit(0)
2015 # If the call was made with 0 or None exit status (sys.exit(0)
2010 # or sys.exit() ), don't bother showing a traceback, as both of
2016 # or sys.exit() ), don't bother showing a traceback, as both of
2011 # these are considered normal by the OS:
2017 # these are considered normal by the OS:
2012 # > python -c'import sys;sys.exit(0)'; echo $?
2018 # > python -c'import sys;sys.exit(0)'; echo $?
2013 # 0
2019 # 0
2014 # > python -c'import sys;sys.exit()'; echo $?
2020 # > python -c'import sys;sys.exit()'; echo $?
2015 # 0
2021 # 0
2016 # For other exit status, we show the exception unless
2022 # For other exit status, we show the exception unless
2017 # explicitly silenced, but only in short form.
2023 # explicitly silenced, but only in short form.
2018 if status.code not in (0, None) and not kw['exit_ignore']:
2024 if status.code not in (0, None) and not kw['exit_ignore']:
2019 self.showtraceback(exception_only=True)
2025 self.showtraceback(exception_only=True)
2020 except:
2026 except:
2021 self.showtraceback()
2027 self.showtraceback()
2022
2028
2023 def safe_execfile_ipy(self, fname):
2029 def safe_execfile_ipy(self, fname):
2024 """Like safe_execfile, but for .ipy files with IPython syntax.
2030 """Like safe_execfile, but for .ipy files with IPython syntax.
2025
2031
2026 Parameters
2032 Parameters
2027 ----------
2033 ----------
2028 fname : str
2034 fname : str
2029 The name of the file to execute. The filename must have a
2035 The name of the file to execute. The filename must have a
2030 .ipy extension.
2036 .ipy extension.
2031 """
2037 """
2032 fname = os.path.abspath(os.path.expanduser(fname))
2038 fname = os.path.abspath(os.path.expanduser(fname))
2033
2039
2034 # Make sure we have a .py file
2040 # Make sure we have a .py file
2035 if not fname.endswith('.ipy'):
2041 if not fname.endswith('.ipy'):
2036 warn('File must end with .py to be run using execfile: <%s>' % fname)
2042 warn('File must end with .py to be run using execfile: <%s>' % fname)
2037
2043
2038 # Make sure we can open the file
2044 # Make sure we can open the file
2039 try:
2045 try:
2040 with open(fname) as thefile:
2046 with open(fname) as thefile:
2041 pass
2047 pass
2042 except:
2048 except:
2043 warn('Could not open file <%s> for safe execution.' % fname)
2049 warn('Could not open file <%s> for safe execution.' % fname)
2044 return
2050 return
2045
2051
2046 # Find things also in current directory. This is needed to mimic the
2052 # Find things also in current directory. This is needed to mimic the
2047 # behavior of running a script from the system command line, where
2053 # behavior of running a script from the system command line, where
2048 # Python inserts the script's directory into sys.path
2054 # Python inserts the script's directory into sys.path
2049 dname = os.path.dirname(fname)
2055 dname = os.path.dirname(fname)
2050
2056
2051 with prepended_to_syspath(dname):
2057 with prepended_to_syspath(dname):
2052 try:
2058 try:
2053 with open(fname) as thefile:
2059 with open(fname) as thefile:
2054 script = thefile.read()
2060 script = thefile.read()
2055 # self.runlines currently captures all exceptions
2061 # self.runlines currently captures all exceptions
2056 # raise in user code. It would be nice if there were
2062 # raise in user code. It would be nice if there were
2057 # versions of runlines, execfile that did raise, so
2063 # versions of runlines, execfile that did raise, so
2058 # we could catch the errors.
2064 # we could catch the errors.
2059 self.runlines(script, clean=True)
2065 self.runlines(script, clean=True)
2060 except:
2066 except:
2061 self.showtraceback()
2067 self.showtraceback()
2062 warn('Unknown failure executing file: <%s>' % fname)
2068 warn('Unknown failure executing file: <%s>' % fname)
2063
2069
2070 def run_cell(self, cell):
2071 """Run the contents of an entire multiline 'cell' of code.
2072
2073 The cell is split into separate blocks which can be executed
2074 individually. Then, based on how many blocks there are, they are
2075 executed as follows:
2076
2077 - A single block: 'single' mode.
2078
2079 If there's more than one block, it depends:
2080
2081 - if the last one is a single line long, run all but the last in
2082 'exec' mode and the very last one in 'single' mode. This makes it
2083 easy to type simple expressions at the end to see computed values.
2084 - otherwise (last one is also multiline), run all in 'exec' mode
2085
2086 When code is executed in 'single' mode, :func:`sys.displayhook` fires,
2087 results are displayed and output prompts are computed. In 'exec' mode,
2088 no results are displayed unless :func:`print` is called explicitly;
2089 this mode is more akin to running a script.
2090
2091 Parameters
2092 ----------
2093 cell : str
2094 A single or multiline string.
2095 """
2096 blocks = self.input_splitter.split_blocks(cell)
2097 if not blocks:
2098 return
2099
2100 if len(blocks) == 1:
2101 self.runlines(blocks[0])
2102
2103 last = blocks[-1]
2104 if len(last.splitlines()) < 2:
2105 map(self.runcode, blocks[:-1])
2106 self.runlines(last)
2107 else:
2108 map(self.runcode, blocks)
2109
2064 def runlines(self, lines, clean=False):
2110 def runlines(self, lines, clean=False):
2065 """Run a string of one or more lines of source.
2111 """Run a string of one or more lines of source.
2066
2112
2067 This method is capable of running a string containing multiple source
2113 This method is capable of running a string containing multiple source
2068 lines, as if they had been entered at the IPython prompt. Since it
2114 lines, as if they had been entered at the IPython prompt. Since it
2069 exposes IPython's processing machinery, the given strings can contain
2115 exposes IPython's processing machinery, the given strings can contain
2070 magic calls (%magic), special shell access (!cmd), etc.
2116 magic calls (%magic), special shell access (!cmd), etc.
2071 """
2117 """
2072
2118
2073 if isinstance(lines, (list, tuple)):
2119 if isinstance(lines, (list, tuple)):
2074 lines = '\n'.join(lines)
2120 lines = '\n'.join(lines)
2075
2121
2076 if clean:
2122 if clean:
2077 lines = self._cleanup_ipy_script(lines)
2123 lines = self._cleanup_ipy_script(lines)
2078
2124
2079 # We must start with a clean buffer, in case this is run from an
2125 # We must start with a clean buffer, in case this is run from an
2080 # interactive IPython session (via a magic, for example).
2126 # interactive IPython session (via a magic, for example).
2081 self.resetbuffer()
2127 self.resetbuffer()
2082 lines = lines.splitlines()
2128 lines = lines.splitlines()
2083 more = 0
2129 more = 0
2084 with nested(self.builtin_trap, self.display_trap):
2130 with nested(self.builtin_trap, self.display_trap):
2085 for line in lines:
2131 for line in lines:
2086 # skip blank lines so we don't mess up the prompt counter, but
2132 # skip blank lines so we don't mess up the prompt counter, but
2087 # do NOT skip even a blank line if we are in a code block (more
2133 # do NOT skip even a blank line if we are in a code block (more
2088 # is true)
2134 # is true)
2089
2135
2090 if line or more:
2136 if line or more:
2091 # push to raw history, so hist line numbers stay in sync
2137 # push to raw history, so hist line numbers stay in sync
2092 self.input_hist_raw.append(line + '\n')
2138 self.input_hist_raw.append(line + '\n')
2093 prefiltered = self.prefilter_manager.prefilter_lines(line,
2139 prefiltered = self.prefilter_manager.prefilter_lines(line,
2094 more)
2140 more)
2095 more = self.push_line(prefiltered)
2141 more = self.push_line(prefiltered)
2096 # IPython's runsource returns None if there was an error
2142 # IPython's runsource returns None if there was an error
2097 # compiling the code. This allows us to stop processing
2143 # compiling the code. This allows us to stop processing
2098 # right away, so the user gets the error message at the
2144 # right away, so the user gets the error message at the
2099 # right place.
2145 # right place.
2100 if more is None:
2146 if more is None:
2101 break
2147 break
2102 else:
2148 else:
2103 self.input_hist_raw.append("\n")
2149 self.input_hist_raw.append("\n")
2104 # final newline in case the input didn't have it, so that the code
2150 # final newline in case the input didn't have it, so that the code
2105 # actually does get executed
2151 # actually does get executed
2106 if more:
2152 if more:
2107 self.push_line('\n')
2153 self.push_line('\n')
2108
2154
2109 def runsource(self, source, filename='<input>', symbol='single'):
2155 def runsource(self, source, filename='<input>', symbol='single'):
2110 """Compile and run some source in the interpreter.
2156 """Compile and run some source in the interpreter.
2111
2157
2112 Arguments are as for compile_command().
2158 Arguments are as for compile_command().
2113
2159
2114 One several things can happen:
2160 One several things can happen:
2115
2161
2116 1) The input is incorrect; compile_command() raised an
2162 1) The input is incorrect; compile_command() raised an
2117 exception (SyntaxError or OverflowError). A syntax traceback
2163 exception (SyntaxError or OverflowError). A syntax traceback
2118 will be printed by calling the showsyntaxerror() method.
2164 will be printed by calling the showsyntaxerror() method.
2119
2165
2120 2) The input is incomplete, and more input is required;
2166 2) The input is incomplete, and more input is required;
2121 compile_command() returned None. Nothing happens.
2167 compile_command() returned None. Nothing happens.
2122
2168
2123 3) The input is complete; compile_command() returned a code
2169 3) The input is complete; compile_command() returned a code
2124 object. The code is executed by calling self.runcode() (which
2170 object. The code is executed by calling self.runcode() (which
2125 also handles run-time exceptions, except for SystemExit).
2171 also handles run-time exceptions, except for SystemExit).
2126
2172
2127 The return value is:
2173 The return value is:
2128
2174
2129 - True in case 2
2175 - True in case 2
2130
2176
2131 - False in the other cases, unless an exception is raised, where
2177 - False in the other cases, unless an exception is raised, where
2132 None is returned instead. This can be used by external callers to
2178 None is returned instead. This can be used by external callers to
2133 know whether to continue feeding input or not.
2179 know whether to continue feeding input or not.
2134
2180
2135 The return value can be used to decide whether to use sys.ps1 or
2181 The return value can be used to decide whether to use sys.ps1 or
2136 sys.ps2 to prompt the next line."""
2182 sys.ps2 to prompt the next line."""
2137
2183
2138 # if the source code has leading blanks, add 'if 1:\n' to it
2184 # if the source code has leading blanks, add 'if 1:\n' to it
2139 # this allows execution of indented pasted code. It is tempting
2185 # this allows execution of indented pasted code. It is tempting
2140 # to add '\n' at the end of source to run commands like ' a=1'
2186 # to add '\n' at the end of source to run commands like ' a=1'
2141 # directly, but this fails for more complicated scenarios
2187 # directly, but this fails for more complicated scenarios
2142 source=source.encode(self.stdin_encoding)
2188 source=source.encode(self.stdin_encoding)
2143 if source[:1] in [' ', '\t']:
2189 if source[:1] in [' ', '\t']:
2144 source = 'if 1:\n%s' % source
2190 source = 'if 1:\n%s' % source
2145
2191
2146 try:
2192 try:
2147 code = self.compile(source,filename,symbol)
2193 code = self.compile(source,filename,symbol)
2148 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2194 except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError):
2149 # Case 1
2195 # Case 1
2150 self.showsyntaxerror(filename)
2196 self.showsyntaxerror(filename)
2151 return None
2197 return None
2152
2198
2153 if code is None:
2199 if code is None:
2154 # Case 2
2200 # Case 2
2155 return True
2201 return True
2156
2202
2157 # Case 3
2203 # Case 3
2158 # We store the code object so that threaded shells and
2204 # We store the code object so that threaded shells and
2159 # custom exception handlers can access all this info if needed.
2205 # custom exception handlers can access all this info if needed.
2160 # The source corresponding to this can be obtained from the
2206 # The source corresponding to this can be obtained from the
2161 # buffer attribute as '\n'.join(self.buffer).
2207 # buffer attribute as '\n'.join(self.buffer).
2162 self.code_to_run = code
2208 self.code_to_run = code
2163 # now actually execute the code object
2209 # now actually execute the code object
2164 if self.runcode(code) == 0:
2210 if self.runcode(code) == 0:
2165 return False
2211 return False
2166 else:
2212 else:
2167 return None
2213 return None
2168
2214
2169 def runcode(self,code_obj):
2215 def runcode(self, code_obj):
2170 """Execute a code object.
2216 """Execute a code object.
2171
2217
2172 When an exception occurs, self.showtraceback() is called to display a
2218 When an exception occurs, self.showtraceback() is called to display a
2173 traceback.
2219 traceback.
2174
2220
2175 Return value: a flag indicating whether the code to be run completed
2221 Return value: a flag indicating whether the code to be run completed
2176 successfully:
2222 successfully:
2177
2223
2178 - 0: successful execution.
2224 - 0: successful execution.
2179 - 1: an error occurred.
2225 - 1: an error occurred.
2180 """
2226 """
2181
2227
2182 # Set our own excepthook in case the user code tries to call it
2228 # Set our own excepthook in case the user code tries to call it
2183 # directly, so that the IPython crash handler doesn't get triggered
2229 # directly, so that the IPython crash handler doesn't get triggered
2184 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2230 old_excepthook,sys.excepthook = sys.excepthook, self.excepthook
2185
2231
2186 # we save the original sys.excepthook in the instance, in case config
2232 # we save the original sys.excepthook in the instance, in case config
2187 # code (such as magics) needs access to it.
2233 # code (such as magics) needs access to it.
2188 self.sys_excepthook = old_excepthook
2234 self.sys_excepthook = old_excepthook
2189 outflag = 1 # happens in more places, so it's easier as default
2235 outflag = 1 # happens in more places, so it's easier as default
2190 try:
2236 try:
2191 try:
2237 try:
2192 self.hooks.pre_runcode_hook()
2238 self.hooks.pre_runcode_hook()
2193 #rprint('Running code') # dbg
2239 #rprint('Running code') # dbg
2194 exec code_obj in self.user_global_ns, self.user_ns
2240 exec code_obj in self.user_global_ns, self.user_ns
2195 finally:
2241 finally:
2196 # Reset our crash handler in place
2242 # Reset our crash handler in place
2197 sys.excepthook = old_excepthook
2243 sys.excepthook = old_excepthook
2198 except SystemExit:
2244 except SystemExit:
2199 self.resetbuffer()
2245 self.resetbuffer()
2200 self.showtraceback(exception_only=True)
2246 self.showtraceback(exception_only=True)
2201 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2247 warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1)
2202 except self.custom_exceptions:
2248 except self.custom_exceptions:
2203 etype,value,tb = sys.exc_info()
2249 etype,value,tb = sys.exc_info()
2204 self.CustomTB(etype,value,tb)
2250 self.CustomTB(etype,value,tb)
2205 except:
2251 except:
2206 self.showtraceback()
2252 self.showtraceback()
2207 else:
2253 else:
2208 outflag = 0
2254 outflag = 0
2209 if softspace(sys.stdout, 0):
2255 if softspace(sys.stdout, 0):
2210 print
2256 print
2211 # Flush out code object which has been run (and source)
2257 # Flush out code object which has been run (and source)
2212 self.code_to_run = None
2258 self.code_to_run = None
2213 return outflag
2259 return outflag
2214
2260
2215 def push_line(self, line):
2261 def push_line(self, line):
2216 """Push a line to the interpreter.
2262 """Push a line to the interpreter.
2217
2263
2218 The line should not have a trailing newline; it may have
2264 The line should not have a trailing newline; it may have
2219 internal newlines. The line is appended to a buffer and the
2265 internal newlines. The line is appended to a buffer and the
2220 interpreter's runsource() method is called with the
2266 interpreter's runsource() method is called with the
2221 concatenated contents of the buffer as source. If this
2267 concatenated contents of the buffer as source. If this
2222 indicates that the command was executed or invalid, the buffer
2268 indicates that the command was executed or invalid, the buffer
2223 is reset; otherwise, the command is incomplete, and the buffer
2269 is reset; otherwise, the command is incomplete, and the buffer
2224 is left as it was after the line was appended. The return
2270 is left as it was after the line was appended. The return
2225 value is 1 if more input is required, 0 if the line was dealt
2271 value is 1 if more input is required, 0 if the line was dealt
2226 with in some way (this is the same as runsource()).
2272 with in some way (this is the same as runsource()).
2227 """
2273 """
2228
2274
2229 # autoindent management should be done here, and not in the
2275 # autoindent management should be done here, and not in the
2230 # interactive loop, since that one is only seen by keyboard input. We
2276 # interactive loop, since that one is only seen by keyboard input. We
2231 # need this done correctly even for code run via runlines (which uses
2277 # need this done correctly even for code run via runlines (which uses
2232 # push).
2278 # push).
2233
2279
2234 #print 'push line: <%s>' % line # dbg
2280 #print 'push line: <%s>' % line # dbg
2235 for subline in line.splitlines():
2281 for subline in line.splitlines():
2236 self._autoindent_update(subline)
2282 self._autoindent_update(subline)
2237 self.buffer.append(line)
2283 self.buffer.append(line)
2238 more = self.runsource('\n'.join(self.buffer), self.filename)
2284 more = self.runsource('\n'.join(self.buffer), self.filename)
2239 if not more:
2285 if not more:
2240 self.resetbuffer()
2286 self.resetbuffer()
2241 return more
2287 return more
2242
2288
2243 def resetbuffer(self):
2289 def resetbuffer(self):
2244 """Reset the input buffer."""
2290 """Reset the input buffer."""
2245 self.buffer[:] = []
2291 self.buffer[:] = []
2246
2292
2247 def _is_secondary_block_start(self, s):
2293 def _is_secondary_block_start(self, s):
2248 if not s.endswith(':'):
2294 if not s.endswith(':'):
2249 return False
2295 return False
2250 if (s.startswith('elif') or
2296 if (s.startswith('elif') or
2251 s.startswith('else') or
2297 s.startswith('else') or
2252 s.startswith('except') or
2298 s.startswith('except') or
2253 s.startswith('finally')):
2299 s.startswith('finally')):
2254 return True
2300 return True
2255
2301
2256 def _cleanup_ipy_script(self, script):
2302 def _cleanup_ipy_script(self, script):
2257 """Make a script safe for self.runlines()
2303 """Make a script safe for self.runlines()
2258
2304
2259 Currently, IPython is lines based, with blocks being detected by
2305 Currently, IPython is lines based, with blocks being detected by
2260 empty lines. This is a problem for block based scripts that may
2306 empty lines. This is a problem for block based scripts that may
2261 not have empty lines after blocks. This script adds those empty
2307 not have empty lines after blocks. This script adds those empty
2262 lines to make scripts safe for running in the current line based
2308 lines to make scripts safe for running in the current line based
2263 IPython.
2309 IPython.
2264 """
2310 """
2265 res = []
2311 res = []
2266 lines = script.splitlines()
2312 lines = script.splitlines()
2267 level = 0
2313 level = 0
2268
2314
2269 for l in lines:
2315 for l in lines:
2270 lstripped = l.lstrip()
2316 lstripped = l.lstrip()
2271 stripped = l.strip()
2317 stripped = l.strip()
2272 if not stripped:
2318 if not stripped:
2273 continue
2319 continue
2274 newlevel = len(l) - len(lstripped)
2320 newlevel = len(l) - len(lstripped)
2275 if level > 0 and newlevel == 0 and \
2321 if level > 0 and newlevel == 0 and \
2276 not self._is_secondary_block_start(stripped):
2322 not self._is_secondary_block_start(stripped):
2277 # add empty line
2323 # add empty line
2278 res.append('')
2324 res.append('')
2279 res.append(l)
2325 res.append(l)
2280 level = newlevel
2326 level = newlevel
2281
2327
2282 return '\n'.join(res) + '\n'
2328 return '\n'.join(res) + '\n'
2283
2329
2284 def _autoindent_update(self,line):
2330 def _autoindent_update(self,line):
2285 """Keep track of the indent level."""
2331 """Keep track of the indent level."""
2286
2332
2287 #debugx('line')
2333 #debugx('line')
2288 #debugx('self.indent_current_nsp')
2334 #debugx('self.indent_current_nsp')
2289 if self.autoindent:
2335 if self.autoindent:
2290 if line:
2336 if line:
2291 inisp = num_ini_spaces(line)
2337 inisp = num_ini_spaces(line)
2292 if inisp < self.indent_current_nsp:
2338 if inisp < self.indent_current_nsp:
2293 self.indent_current_nsp = inisp
2339 self.indent_current_nsp = inisp
2294
2340
2295 if line[-1] == ':':
2341 if line[-1] == ':':
2296 self.indent_current_nsp += 4
2342 self.indent_current_nsp += 4
2297 elif dedent_re.match(line):
2343 elif dedent_re.match(line):
2298 self.indent_current_nsp -= 4
2344 self.indent_current_nsp -= 4
2299 else:
2345 else:
2300 self.indent_current_nsp = 0
2346 self.indent_current_nsp = 0
2301
2347
2302 #-------------------------------------------------------------------------
2348 #-------------------------------------------------------------------------
2303 # Things related to GUI support and pylab
2349 # Things related to GUI support and pylab
2304 #-------------------------------------------------------------------------
2350 #-------------------------------------------------------------------------
2305
2351
2306 def enable_pylab(self, gui=None):
2352 def enable_pylab(self, gui=None):
2307 raise NotImplementedError('Implement enable_pylab in a subclass')
2353 raise NotImplementedError('Implement enable_pylab in a subclass')
2308
2354
2309 #-------------------------------------------------------------------------
2355 #-------------------------------------------------------------------------
2310 # Utilities
2356 # Utilities
2311 #-------------------------------------------------------------------------
2357 #-------------------------------------------------------------------------
2312
2358
2313 def var_expand(self,cmd,depth=0):
2359 def var_expand(self,cmd,depth=0):
2314 """Expand python variables in a string.
2360 """Expand python variables in a string.
2315
2361
2316 The depth argument indicates how many frames above the caller should
2362 The depth argument indicates how many frames above the caller should
2317 be walked to look for the local namespace where to expand variables.
2363 be walked to look for the local namespace where to expand variables.
2318
2364
2319 The global namespace for expansion is always the user's interactive
2365 The global namespace for expansion is always the user's interactive
2320 namespace.
2366 namespace.
2321 """
2367 """
2322
2368
2323 return str(ItplNS(cmd,
2369 return str(ItplNS(cmd,
2324 self.user_ns, # globals
2370 self.user_ns, # globals
2325 # Skip our own frame in searching for locals:
2371 # Skip our own frame in searching for locals:
2326 sys._getframe(depth+1).f_locals # locals
2372 sys._getframe(depth+1).f_locals # locals
2327 ))
2373 ))
2328
2374
2329 def mktempfile(self,data=None):
2375 def mktempfile(self,data=None):
2330 """Make a new tempfile and return its filename.
2376 """Make a new tempfile and return its filename.
2331
2377
2332 This makes a call to tempfile.mktemp, but it registers the created
2378 This makes a call to tempfile.mktemp, but it registers the created
2333 filename internally so ipython cleans it up at exit time.
2379 filename internally so ipython cleans it up at exit time.
2334
2380
2335 Optional inputs:
2381 Optional inputs:
2336
2382
2337 - data(None): if data is given, it gets written out to the temp file
2383 - data(None): if data is given, it gets written out to the temp file
2338 immediately, and the file is closed again."""
2384 immediately, and the file is closed again."""
2339
2385
2340 filename = tempfile.mktemp('.py','ipython_edit_')
2386 filename = tempfile.mktemp('.py','ipython_edit_')
2341 self.tempfiles.append(filename)
2387 self.tempfiles.append(filename)
2342
2388
2343 if data:
2389 if data:
2344 tmp_file = open(filename,'w')
2390 tmp_file = open(filename,'w')
2345 tmp_file.write(data)
2391 tmp_file.write(data)
2346 tmp_file.close()
2392 tmp_file.close()
2347 return filename
2393 return filename
2348
2394
2349 # TODO: This should be removed when Term is refactored.
2395 # TODO: This should be removed when Term is refactored.
2350 def write(self,data):
2396 def write(self,data):
2351 """Write a string to the default output"""
2397 """Write a string to the default output"""
2352 io.Term.cout.write(data)
2398 io.Term.cout.write(data)
2353
2399
2354 # TODO: This should be removed when Term is refactored.
2400 # TODO: This should be removed when Term is refactored.
2355 def write_err(self,data):
2401 def write_err(self,data):
2356 """Write a string to the default error output"""
2402 """Write a string to the default error output"""
2357 io.Term.cerr.write(data)
2403 io.Term.cerr.write(data)
2358
2404
2359 def ask_yes_no(self,prompt,default=True):
2405 def ask_yes_no(self,prompt,default=True):
2360 if self.quiet:
2406 if self.quiet:
2361 return True
2407 return True
2362 return ask_yes_no(prompt,default)
2408 return ask_yes_no(prompt,default)
2363
2409
2364 def show_usage(self):
2410 def show_usage(self):
2365 """Show a usage message"""
2411 """Show a usage message"""
2366 page.page(IPython.core.usage.interactive_usage)
2412 page.page(IPython.core.usage.interactive_usage)
2367
2413
2368 #-------------------------------------------------------------------------
2414 #-------------------------------------------------------------------------
2369 # Things related to IPython exiting
2415 # Things related to IPython exiting
2370 #-------------------------------------------------------------------------
2416 #-------------------------------------------------------------------------
2371 def atexit_operations(self):
2417 def atexit_operations(self):
2372 """This will be executed at the time of exit.
2418 """This will be executed at the time of exit.
2373
2419
2374 Cleanup operations and saving of persistent data that is done
2420 Cleanup operations and saving of persistent data that is done
2375 unconditionally by IPython should be performed here.
2421 unconditionally by IPython should be performed here.
2376
2422
2377 For things that may depend on startup flags or platform specifics (such
2423 For things that may depend on startup flags or platform specifics (such
2378 as having readline or not), register a separate atexit function in the
2424 as having readline or not), register a separate atexit function in the
2379 code that has the appropriate information, rather than trying to
2425 code that has the appropriate information, rather than trying to
2380 clutter
2426 clutter
2381 """
2427 """
2382 # Cleanup all tempfiles left around
2428 # Cleanup all tempfiles left around
2383 for tfile in self.tempfiles:
2429 for tfile in self.tempfiles:
2384 try:
2430 try:
2385 os.unlink(tfile)
2431 os.unlink(tfile)
2386 except OSError:
2432 except OSError:
2387 pass
2433 pass
2388
2434
2389 # Clear all user namespaces to release all references cleanly.
2435 # Clear all user namespaces to release all references cleanly.
2390 self.reset()
2436 self.reset()
2391
2437
2392 # Run user hooks
2438 # Run user hooks
2393 self.hooks.shutdown_hook()
2439 self.hooks.shutdown_hook()
2394
2440
2395 def cleanup(self):
2441 def cleanup(self):
2396 self.restore_sys_module_state()
2442 self.restore_sys_module_state()
2397
2443
2398
2444
2399 class InteractiveShellABC(object):
2445 class InteractiveShellABC(object):
2400 """An abstract base class for InteractiveShell."""
2446 """An abstract base class for InteractiveShell."""
2401 __metaclass__ = abc.ABCMeta
2447 __metaclass__ = abc.ABCMeta
2402
2448
2403 InteractiveShellABC.register(InteractiveShell)
2449 InteractiveShellABC.register(InteractiveShell)
@@ -1,649 +1,649 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) 2010 The IPython Development Team
5 # Copyright (C) 2010 The IPython Development Team
6 #
6 #
7 # Distributed under the terms of the BSD License. The full license is in
7 # Distributed under the terms of the BSD License. The full license is in
8 # the file COPYING, distributed as part of this software.
8 # the file COPYING, distributed as part of this software.
9 #-----------------------------------------------------------------------------
9 #-----------------------------------------------------------------------------
10
10
11 #-----------------------------------------------------------------------------
11 #-----------------------------------------------------------------------------
12 # Imports
12 # Imports
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # stdlib
14 # stdlib
15 import unittest
15 import unittest
16 import sys
16 import sys
17
17
18 # Third party
18 # Third party
19 import nose.tools as nt
19 import nose.tools as nt
20
20
21 # Our own
21 # Our own
22 from IPython.core import inputsplitter as isp
22 from IPython.core import inputsplitter as isp
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Semi-complete examples (also used as tests)
25 # Semi-complete examples (also used as tests)
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 # Note: at the bottom, there's a slightly more complete version of this that
28 # Note: at the bottom, there's a slightly more complete version of this that
29 # can be useful during development of code here.
29 # can be useful during development of code here.
30
30
31 def mini_interactive_loop(raw_input):
31 def mini_interactive_loop(raw_input):
32 """Minimal example of the logic of an interactive interpreter loop.
32 """Minimal example of the logic of an interactive interpreter loop.
33
33
34 This serves as an example, and it is used by the test system with a fake
34 This serves as an example, and it is used by the test system with a fake
35 raw_input that simulates interactive input."""
35 raw_input that simulates interactive input."""
36
36
37 from IPython.core.inputsplitter import InputSplitter
37 from IPython.core.inputsplitter import InputSplitter
38
38
39 isp = InputSplitter()
39 isp = InputSplitter()
40 # In practice, this input loop would be wrapped in an outside loop to read
40 # In practice, this input loop would be wrapped in an outside loop to read
41 # input indefinitely, until some exit/quit command was issued. Here we
41 # input indefinitely, until some exit/quit command was issued. Here we
42 # only illustrate the basic inner loop.
42 # only illustrate the basic inner loop.
43 while isp.push_accepts_more():
43 while isp.push_accepts_more():
44 indent = ' '*isp.indent_spaces
44 indent = ' '*isp.indent_spaces
45 prompt = '>>> ' + indent
45 prompt = '>>> ' + indent
46 line = indent + raw_input(prompt)
46 line = indent + raw_input(prompt)
47 isp.push(line)
47 isp.push(line)
48
48
49 # Here we just return input so we can use it in a test suite, but a real
49 # Here we just return input so we can use it in a test suite, but a real
50 # interpreter would instead send it for execution somewhere.
50 # interpreter would instead send it for execution somewhere.
51 src = isp.source_reset()
51 src = isp.source_reset()
52 #print 'Input source was:\n', src # dbg
52 #print 'Input source was:\n', src # dbg
53 return src
53 return src
54
54
55 #-----------------------------------------------------------------------------
55 #-----------------------------------------------------------------------------
56 # Test utilities, just for local use
56 # Test utilities, just for local use
57 #-----------------------------------------------------------------------------
57 #-----------------------------------------------------------------------------
58
58
59 def assemble(block):
59 def assemble(block):
60 """Assemble a block into multi-line sub-blocks."""
60 """Assemble a block into multi-line sub-blocks."""
61 return ['\n'.join(sub_block)+'\n' for sub_block in block]
61 return ['\n'.join(sub_block)+'\n' for sub_block in block]
62
62
63
63
64 def pseudo_input(lines):
64 def pseudo_input(lines):
65 """Return a function that acts like raw_input but feeds the input list."""
65 """Return a function that acts like raw_input but feeds the input list."""
66 ilines = iter(lines)
66 ilines = iter(lines)
67 def raw_in(prompt):
67 def raw_in(prompt):
68 try:
68 try:
69 return next(ilines)
69 return next(ilines)
70 except StopIteration:
70 except StopIteration:
71 return ''
71 return ''
72 return raw_in
72 return raw_in
73
73
74 #-----------------------------------------------------------------------------
74 #-----------------------------------------------------------------------------
75 # Tests
75 # Tests
76 #-----------------------------------------------------------------------------
76 #-----------------------------------------------------------------------------
77 def test_spaces():
77 def test_spaces():
78 tests = [('', 0),
78 tests = [('', 0),
79 (' ', 1),
79 (' ', 1),
80 ('\n', 0),
80 ('\n', 0),
81 (' \n', 1),
81 (' \n', 1),
82 ('x', 0),
82 ('x', 0),
83 (' x', 1),
83 (' x', 1),
84 (' x',2),
84 (' x',2),
85 (' x',4),
85 (' x',4),
86 # Note: tabs are counted as a single whitespace!
86 # Note: tabs are counted as a single whitespace!
87 ('\tx', 1),
87 ('\tx', 1),
88 ('\t x', 2),
88 ('\t x', 2),
89 ]
89 ]
90
90
91 for s, nsp in tests:
91 for s, nsp in tests:
92 nt.assert_equal(isp.num_ini_spaces(s), nsp)
92 nt.assert_equal(isp.num_ini_spaces(s), nsp)
93
93
94
94
95 def test_remove_comments():
95 def test_remove_comments():
96 tests = [('text', 'text'),
96 tests = [('text', 'text'),
97 ('text # comment', 'text '),
97 ('text # comment', 'text '),
98 ('text # comment\n', 'text \n'),
98 ('text # comment\n', 'text \n'),
99 ('text # comment \n', 'text \n'),
99 ('text # comment \n', 'text \n'),
100 ('line # c \nline\n','line \nline\n'),
100 ('line # c \nline\n','line \nline\n'),
101 ('line # c \nline#c2 \nline\nline #c\n\n',
101 ('line # c \nline#c2 \nline\nline #c\n\n',
102 'line \nline\nline\nline \n\n'),
102 'line \nline\nline\nline \n\n'),
103 ]
103 ]
104
104
105 for inp, out in tests:
105 for inp, out in tests:
106 nt.assert_equal(isp.remove_comments(inp), out)
106 nt.assert_equal(isp.remove_comments(inp), out)
107
107
108
108
109 def test_get_input_encoding():
109 def test_get_input_encoding():
110 encoding = isp.get_input_encoding()
110 encoding = isp.get_input_encoding()
111 nt.assert_true(isinstance(encoding, basestring))
111 nt.assert_true(isinstance(encoding, basestring))
112 # simple-minded check that at least encoding a simple string works with the
112 # simple-minded check that at least encoding a simple string works with the
113 # encoding we got.
113 # encoding we got.
114 nt.assert_equal('test'.encode(encoding), 'test')
114 nt.assert_equal('test'.encode(encoding), 'test')
115
115
116
116
117 class NoInputEncodingTestCase(unittest.TestCase):
117 class NoInputEncodingTestCase(unittest.TestCase):
118 def setUp(self):
118 def setUp(self):
119 self.old_stdin = sys.stdin
119 self.old_stdin = sys.stdin
120 class X: pass
120 class X: pass
121 fake_stdin = X()
121 fake_stdin = X()
122 sys.stdin = fake_stdin
122 sys.stdin = fake_stdin
123
123
124 def test(self):
124 def test(self):
125 # Verify that if sys.stdin has no 'encoding' attribute we do the right
125 # Verify that if sys.stdin has no 'encoding' attribute we do the right
126 # thing
126 # thing
127 enc = isp.get_input_encoding()
127 enc = isp.get_input_encoding()
128 self.assertEqual(enc, 'ascii')
128 self.assertEqual(enc, 'ascii')
129
129
130 def tearDown(self):
130 def tearDown(self):
131 sys.stdin = self.old_stdin
131 sys.stdin = self.old_stdin
132
132
133
133
134 class InputSplitterTestCase(unittest.TestCase):
134 class InputSplitterTestCase(unittest.TestCase):
135 def setUp(self):
135 def setUp(self):
136 self.isp = isp.InputSplitter()
136 self.isp = isp.InputSplitter()
137
137
138 def test_reset(self):
138 def test_reset(self):
139 isp = self.isp
139 isp = self.isp
140 isp.push('x=1')
140 isp.push('x=1')
141 isp.reset()
141 isp.reset()
142 self.assertEqual(isp._buffer, [])
142 self.assertEqual(isp._buffer, [])
143 self.assertEqual(isp.indent_spaces, 0)
143 self.assertEqual(isp.indent_spaces, 0)
144 self.assertEqual(isp.source, '')
144 self.assertEqual(isp.source, '')
145 self.assertEqual(isp.code, None)
145 self.assertEqual(isp.code, None)
146 self.assertEqual(isp._is_complete, False)
146 self.assertEqual(isp._is_complete, False)
147
147
148 def test_source(self):
148 def test_source(self):
149 self.isp._store('1')
149 self.isp._store('1')
150 self.isp._store('2')
150 self.isp._store('2')
151 self.assertEqual(self.isp.source, '1\n2\n')
151 self.assertEqual(self.isp.source, '1\n2\n')
152 self.assertTrue(len(self.isp._buffer)>0)
152 self.assertTrue(len(self.isp._buffer)>0)
153 self.assertEqual(self.isp.source_reset(), '1\n2\n')
153 self.assertEqual(self.isp.source_reset(), '1\n2\n')
154 self.assertEqual(self.isp._buffer, [])
154 self.assertEqual(self.isp._buffer, [])
155 self.assertEqual(self.isp.source, '')
155 self.assertEqual(self.isp.source, '')
156
156
157 def test_indent(self):
157 def test_indent(self):
158 isp = self.isp # shorthand
158 isp = self.isp # shorthand
159 isp.push('x=1')
159 isp.push('x=1')
160 self.assertEqual(isp.indent_spaces, 0)
160 self.assertEqual(isp.indent_spaces, 0)
161 isp.push('if 1:\n x=1')
161 isp.push('if 1:\n x=1')
162 self.assertEqual(isp.indent_spaces, 4)
162 self.assertEqual(isp.indent_spaces, 4)
163 isp.push('y=2\n')
163 isp.push('y=2\n')
164 self.assertEqual(isp.indent_spaces, 0)
164 self.assertEqual(isp.indent_spaces, 0)
165 isp.push('if 1:')
165 isp.push('if 1:')
166 self.assertEqual(isp.indent_spaces, 4)
166 self.assertEqual(isp.indent_spaces, 4)
167 isp.push(' x=1')
167 isp.push(' x=1')
168 self.assertEqual(isp.indent_spaces, 4)
168 self.assertEqual(isp.indent_spaces, 4)
169 # Blank lines shouldn't change the indent level
169 # Blank lines shouldn't change the indent level
170 isp.push(' '*2)
170 isp.push(' '*2)
171 self.assertEqual(isp.indent_spaces, 4)
171 self.assertEqual(isp.indent_spaces, 4)
172
172
173 def test_indent2(self):
173 def test_indent2(self):
174 isp = self.isp
174 isp = self.isp
175 # When a multiline statement contains parens or multiline strings, we
175 # When a multiline statement contains parens or multiline strings, we
176 # shouldn't get confused.
176 # shouldn't get confused.
177 isp.push("if 1:")
177 isp.push("if 1:")
178 isp.push(" x = (1+\n 2)")
178 isp.push(" x = (1+\n 2)")
179 self.assertEqual(isp.indent_spaces, 4)
179 self.assertEqual(isp.indent_spaces, 4)
180
180
181 def test_dedent(self):
181 def test_dedent(self):
182 isp = self.isp # shorthand
182 isp = self.isp # shorthand
183 isp.push('if 1:')
183 isp.push('if 1:')
184 self.assertEqual(isp.indent_spaces, 4)
184 self.assertEqual(isp.indent_spaces, 4)
185 isp.push(' pass')
185 isp.push(' pass')
186 self.assertEqual(isp.indent_spaces, 0)
186 self.assertEqual(isp.indent_spaces, 0)
187
187
188 def test_push(self):
188 def test_push(self):
189 isp = self.isp
189 isp = self.isp
190 self.assertTrue(isp.push('x=1'))
190 self.assertTrue(isp.push('x=1'))
191
191
192 def test_push2(self):
192 def test_push2(self):
193 isp = self.isp
193 isp = self.isp
194 self.assertFalse(isp.push('if 1:'))
194 self.assertFalse(isp.push('if 1:'))
195 for line in [' x=1', '# a comment', ' y=2']:
195 for line in [' x=1', '# a comment', ' y=2']:
196 self.assertTrue(isp.push(line))
196 self.assertTrue(isp.push(line))
197
197
198 def test_push3(self):
198 def test_push3(self):
199 """Test input with leading whitespace"""
199 """Test input with leading whitespace"""
200 isp = self.isp
200 isp = self.isp
201 isp.push(' x=1')
201 isp.push(' x=1')
202 isp.push(' y=2')
202 isp.push(' y=2')
203 self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n')
203 self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n')
204
204
205 def test_replace_mode(self):
205 def test_replace_mode(self):
206 isp = self.isp
206 isp = self.isp
207 isp.input_mode = 'block'
207 isp.input_mode = 'block'
208 isp.push('x=1')
208 isp.push('x=1')
209 self.assertEqual(isp.source, 'x=1\n')
209 self.assertEqual(isp.source, 'x=1\n')
210 isp.push('x=2')
210 isp.push('x=2')
211 self.assertEqual(isp.source, 'x=2\n')
211 self.assertEqual(isp.source, 'x=2\n')
212
212
213 def test_push_accepts_more(self):
213 def test_push_accepts_more(self):
214 isp = self.isp
214 isp = self.isp
215 isp.push('x=1')
215 isp.push('x=1')
216 self.assertFalse(isp.push_accepts_more())
216 self.assertFalse(isp.push_accepts_more())
217
217
218 def test_push_accepts_more2(self):
218 def test_push_accepts_more2(self):
219 isp = self.isp
219 isp = self.isp
220 isp.push('if 1:')
220 isp.push('if 1:')
221 self.assertTrue(isp.push_accepts_more())
221 self.assertTrue(isp.push_accepts_more())
222 isp.push(' x=1')
222 isp.push(' x=1')
223 self.assertTrue(isp.push_accepts_more())
223 self.assertTrue(isp.push_accepts_more())
224 isp.push('')
224 isp.push('')
225 self.assertFalse(isp.push_accepts_more())
225 self.assertFalse(isp.push_accepts_more())
226
226
227 def test_push_accepts_more3(self):
227 def test_push_accepts_more3(self):
228 isp = self.isp
228 isp = self.isp
229 isp.push("x = (2+\n3)")
229 isp.push("x = (2+\n3)")
230 self.assertFalse(isp.push_accepts_more())
230 self.assertFalse(isp.push_accepts_more())
231
231
232 def test_push_accepts_more4(self):
232 def test_push_accepts_more4(self):
233 isp = self.isp
233 isp = self.isp
234 # When a multiline statement contains parens or multiline strings, we
234 # When a multiline statement contains parens or multiline strings, we
235 # shouldn't get confused.
235 # shouldn't get confused.
236 # FIXME: we should be able to better handle de-dents in statements like
236 # FIXME: we should be able to better handle de-dents in statements like
237 # multiline strings and multiline expressions (continued with \ or
237 # multiline strings and multiline expressions (continued with \ or
238 # parens). Right now we aren't handling the indentation tracking quite
238 # parens). Right now we aren't handling the indentation tracking quite
239 # correctly with this, though in practice it may not be too much of a
239 # correctly with this, though in practice it may not be too much of a
240 # problem. We'll need to see.
240 # problem. We'll need to see.
241 isp.push("if 1:")
241 isp.push("if 1:")
242 isp.push(" x = (2+")
242 isp.push(" x = (2+")
243 isp.push(" 3)")
243 isp.push(" 3)")
244 self.assertTrue(isp.push_accepts_more())
244 self.assertTrue(isp.push_accepts_more())
245 isp.push(" y = 3")
245 isp.push(" y = 3")
246 self.assertTrue(isp.push_accepts_more())
246 self.assertTrue(isp.push_accepts_more())
247 isp.push('')
247 isp.push('')
248 self.assertFalse(isp.push_accepts_more())
248 self.assertFalse(isp.push_accepts_more())
249
249
250 def test_syntax_error(self):
250 def test_syntax_error(self):
251 isp = self.isp
251 isp = self.isp
252 # Syntax errors immediately produce a 'ready' block, so the invalid
252 # Syntax errors immediately produce a 'ready' block, so the invalid
253 # Python can be sent to the kernel for evaluation with possible ipython
253 # Python can be sent to the kernel for evaluation with possible ipython
254 # special-syntax conversion.
254 # special-syntax conversion.
255 isp.push('run foo')
255 isp.push('run foo')
256 self.assertFalse(isp.push_accepts_more())
256 self.assertFalse(isp.push_accepts_more())
257
257
258 def check_split(self, block_lines, compile=True):
258 def check_split(self, block_lines, compile=True):
259 blocks = assemble(block_lines)
259 blocks = assemble(block_lines)
260 lines = ''.join(blocks)
260 lines = ''.join(blocks)
261 oblock = self.isp.split_blocks(lines)
261 oblock = self.isp.split_blocks(lines)
262 self.assertEqual(oblock, blocks)
262 self.assertEqual(oblock, blocks)
263 if compile:
263 if compile:
264 for block in blocks:
264 for block in blocks:
265 self.isp._compile(block)
265 self.isp._compile(block)
266
266
267 def test_split(self):
267 def test_split(self):
268 # All blocks of input we want to test in a list. The format for each
268 # All blocks of input we want to test in a list. The format for each
269 # block is a list of lists, with each inner lists consisting of all the
269 # block is a list of lists, with each inner lists consisting of all the
270 # lines (as single-lines) that should make up a sub-block.
270 # lines (as single-lines) that should make up a sub-block.
271
271
272 # Note: do NOT put here sub-blocks that don't compile, as the
272 # Note: do NOT put here sub-blocks that don't compile, as the
273 # check_split() routine makes a final verification pass to check that
273 # check_split() routine makes a final verification pass to check that
274 # each sub_block, as returned by split_blocks(), does compile
274 # each sub_block, as returned by split_blocks(), does compile
275 # correctly.
275 # correctly.
276 all_blocks = [ [['x=1']],
276 all_blocks = [ [['x=1']],
277
277
278 [['x=1'],
278 [['x=1'],
279 ['y=2']],
279 ['y=2']],
280
280
281 [['x=1'],
281 [['x=1',
282 ['# a comment'],
282 '# a comment'],
283 ['y=11']],
283 ['y=11']],
284
284
285 [['if 1:',
285 [['if 1:',
286 ' x=1'],
286 ' x=1'],
287 ['y=3']],
287 ['y=3']],
288
288
289 [['def f(x):',
289 [['def f(x):',
290 ' return x'],
290 ' return x'],
291 ['x=1']],
291 ['x=1']],
292
292
293 [['def f(x):',
293 [['def f(x):',
294 ' x+=1',
294 ' x+=1',
295 ' ',
295 ' ',
296 ' return x'],
296 ' return x'],
297 ['x=1']],
297 ['x=1']],
298
298
299 [['def f(x):',
299 [['def f(x):',
300 ' if x>0:',
300 ' if x>0:',
301 ' y=1',
301 ' y=1',
302 ' # a comment',
302 ' # a comment',
303 ' else:',
303 ' else:',
304 ' y=4',
304 ' y=4',
305 ' ',
305 ' ',
306 ' return y'],
306 ' return y'],
307 ['x=1'],
307 ['x=1'],
308 ['if 1:',
308 ['if 1:',
309 ' y=11'] ],
309 ' y=11'] ],
310
310
311 [['for i in range(10):'
311 [['for i in range(10):'
312 ' x=i**2']],
312 ' x=i**2']],
313
313
314 [['for i in range(10):'
314 [['for i in range(10):'
315 ' x=i**2'],
315 ' x=i**2'],
316 ['z = 1']],
316 ['z = 1']],
317 ]
317 ]
318 for block_lines in all_blocks:
318 for block_lines in all_blocks:
319 self.check_split(block_lines)
319 self.check_split(block_lines)
320
320
321 def test_split_syntax_errors(self):
321 def test_split_syntax_errors(self):
322 # Block splitting with invalid syntax
322 # Block splitting with invalid syntax
323 all_blocks = [ [['a syntax error']],
323 all_blocks = [ [['a syntax error']],
324
324
325 [['x=1'],
325 [['x=1',
326 ['a syntax error']],
326 'another syntax error']],
327
327
328 [['for i in range(10):'
328 [['for i in range(10):'
329 ' an error']],
329 ' yet another error']],
330
330
331 ]
331 ]
332 for block_lines in all_blocks:
332 for block_lines in all_blocks:
333 self.check_split(block_lines, compile=False)
333 self.check_split(block_lines, compile=False)
334
334
335
335
336 class InteractiveLoopTestCase(unittest.TestCase):
336 class InteractiveLoopTestCase(unittest.TestCase):
337 """Tests for an interactive loop like a python shell.
337 """Tests for an interactive loop like a python shell.
338 """
338 """
339 def check_ns(self, lines, ns):
339 def check_ns(self, lines, ns):
340 """Validate that the given input lines produce the resulting namespace.
340 """Validate that the given input lines produce the resulting namespace.
341
341
342 Note: the input lines are given exactly as they would be typed in an
342 Note: the input lines are given exactly as they would be typed in an
343 auto-indenting environment, as mini_interactive_loop above already does
343 auto-indenting environment, as mini_interactive_loop above already does
344 auto-indenting and prepends spaces to the input.
344 auto-indenting and prepends spaces to the input.
345 """
345 """
346 src = mini_interactive_loop(pseudo_input(lines))
346 src = mini_interactive_loop(pseudo_input(lines))
347 test_ns = {}
347 test_ns = {}
348 exec src in test_ns
348 exec src in test_ns
349 # We can't check that the provided ns is identical to the test_ns,
349 # We can't check that the provided ns is identical to the test_ns,
350 # because Python fills test_ns with extra keys (copyright, etc). But
350 # because Python fills test_ns with extra keys (copyright, etc). But
351 # we can check that the given dict is *contained* in test_ns
351 # we can check that the given dict is *contained* in test_ns
352 for k,v in ns.items():
352 for k,v in ns.items():
353 self.assertEqual(test_ns[k], v)
353 self.assertEqual(test_ns[k], v)
354
354
355 def test_simple(self):
355 def test_simple(self):
356 self.check_ns(['x=1'], dict(x=1))
356 self.check_ns(['x=1'], dict(x=1))
357
357
358 def test_simple2(self):
358 def test_simple2(self):
359 self.check_ns(['if 1:', 'x=2'], dict(x=2))
359 self.check_ns(['if 1:', 'x=2'], dict(x=2))
360
360
361 def test_xy(self):
361 def test_xy(self):
362 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
362 self.check_ns(['x=1; y=2'], dict(x=1, y=2))
363
363
364 def test_abc(self):
364 def test_abc(self):
365 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
365 self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3))
366
366
367 def test_multi(self):
367 def test_multi(self):
368 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
368 self.check_ns(['x =(1+','1+','2)'], dict(x=4))
369
369
370
370
371 def test_LineInfo():
371 def test_LineInfo():
372 """Simple test for LineInfo construction and str()"""
372 """Simple test for LineInfo construction and str()"""
373 linfo = isp.LineInfo(' %cd /home')
373 linfo = isp.LineInfo(' %cd /home')
374 nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]')
374 nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]')
375
375
376
376
377 def test_split_user_input():
377 def test_split_user_input():
378 """Unicode test - split_user_input already has good doctests"""
378 """Unicode test - split_user_input already has good doctests"""
379 line = u"PΓ©rez Fernando"
379 line = u"PΓ©rez Fernando"
380 parts = isp.split_user_input(line)
380 parts = isp.split_user_input(line)
381 parts_expected = (u'', u'', u'', line)
381 parts_expected = (u'', u'', u'', line)
382 nt.assert_equal(parts, parts_expected)
382 nt.assert_equal(parts, parts_expected)
383
383
384
384
385 # Transformer tests
385 # Transformer tests
386 def transform_checker(tests, func):
386 def transform_checker(tests, func):
387 """Utility to loop over test inputs"""
387 """Utility to loop over test inputs"""
388 for inp, tr in tests:
388 for inp, tr in tests:
389 nt.assert_equals(func(inp), tr)
389 nt.assert_equals(func(inp), tr)
390
390
391 # Data for all the syntax tests in the form of lists of pairs of
391 # Data for all the syntax tests in the form of lists of pairs of
392 # raw/transformed input. We store it here as a global dict so that we can use
392 # raw/transformed input. We store it here as a global dict so that we can use
393 # it both within single-function tests and also to validate the behavior of the
393 # it both within single-function tests and also to validate the behavior of the
394 # larger objects
394 # larger objects
395
395
396 syntax = \
396 syntax = \
397 dict(assign_system =
397 dict(assign_system =
398 [('a =! ls', 'a = get_ipython().magic("sc -l = ls")'),
398 [('a =! ls', 'a = get_ipython().magic("sc -l = ls")'),
399 ('b = !ls', 'b = get_ipython().magic("sc -l = ls")'),
399 ('b = !ls', 'b = get_ipython().magic("sc -l = ls")'),
400 ('x=1', 'x=1'), # normal input is unmodified
400 ('x=1', 'x=1'), # normal input is unmodified
401 (' ',' '), # blank lines are kept intact
401 (' ',' '), # blank lines are kept intact
402 ],
402 ],
403
403
404 assign_magic =
404 assign_magic =
405 [('a =% who', 'a = get_ipython().magic("who")'),
405 [('a =% who', 'a = get_ipython().magic("who")'),
406 ('b = %who', 'b = get_ipython().magic("who")'),
406 ('b = %who', 'b = get_ipython().magic("who")'),
407 ('x=1', 'x=1'), # normal input is unmodified
407 ('x=1', 'x=1'), # normal input is unmodified
408 (' ',' '), # blank lines are kept intact
408 (' ',' '), # blank lines are kept intact
409 ],
409 ],
410
410
411 classic_prompt =
411 classic_prompt =
412 [('>>> x=1', 'x=1'),
412 [('>>> x=1', 'x=1'),
413 ('x=1', 'x=1'), # normal input is unmodified
413 ('x=1', 'x=1'), # normal input is unmodified
414 (' ', ' '), # blank lines are kept intact
414 (' ', ' '), # blank lines are kept intact
415 ('... ', ''), # continuation prompts
415 ('... ', ''), # continuation prompts
416 ],
416 ],
417
417
418 ipy_prompt =
418 ipy_prompt =
419 [('In [1]: x=1', 'x=1'),
419 [('In [1]: x=1', 'x=1'),
420 ('x=1', 'x=1'), # normal input is unmodified
420 ('x=1', 'x=1'), # normal input is unmodified
421 (' ',' '), # blank lines are kept intact
421 (' ',' '), # blank lines are kept intact
422 (' ....: ', ''), # continuation prompts
422 (' ....: ', ''), # continuation prompts
423 ],
423 ],
424
424
425 # Tests for the escape transformer to leave normal code alone
425 # Tests for the escape transformer to leave normal code alone
426 escaped_noesc =
426 escaped_noesc =
427 [ (' ', ' '),
427 [ (' ', ' '),
428 ('x=1', 'x=1'),
428 ('x=1', 'x=1'),
429 ],
429 ],
430
430
431 # System calls
431 # System calls
432 escaped_shell =
432 escaped_shell =
433 [ ('!ls', 'get_ipython().system("ls")'),
433 [ ('!ls', 'get_ipython().system("ls")'),
434 # Double-escape shell, this means to capture the output of the
434 # Double-escape shell, this means to capture the output of the
435 # subprocess and return it
435 # subprocess and return it
436 ('!!ls', 'get_ipython().getoutput("ls")'),
436 ('!!ls', 'get_ipython().getoutput("ls")'),
437 ],
437 ],
438
438
439 # Help/object info
439 # Help/object info
440 escaped_help =
440 escaped_help =
441 [ ('?', 'get_ipython().show_usage()'),
441 [ ('?', 'get_ipython().show_usage()'),
442 ('?x1', 'get_ipython().magic("pinfo x1")'),
442 ('?x1', 'get_ipython().magic("pinfo x1")'),
443 ('??x2', 'get_ipython().magic("pinfo2 x2")'),
443 ('??x2', 'get_ipython().magic("pinfo2 x2")'),
444 ('x3?', 'get_ipython().magic("pinfo x3")'),
444 ('x3?', 'get_ipython().magic("pinfo x3")'),
445 ('x4??', 'get_ipython().magic("pinfo2 x4")'),
445 ('x4??', 'get_ipython().magic("pinfo2 x4")'),
446 ('%hist?', 'get_ipython().magic("pinfo %hist")'),
446 ('%hist?', 'get_ipython().magic("pinfo %hist")'),
447 ],
447 ],
448
448
449 # Explicit magic calls
449 # Explicit magic calls
450 escaped_magic =
450 escaped_magic =
451 [ ('%cd', 'get_ipython().magic("cd")'),
451 [ ('%cd', 'get_ipython().magic("cd")'),
452 ('%cd /home', 'get_ipython().magic("cd /home")'),
452 ('%cd /home', 'get_ipython().magic("cd /home")'),
453 (' %magic', ' get_ipython().magic("magic")'),
453 (' %magic', ' get_ipython().magic("magic")'),
454 ],
454 ],
455
455
456 # Quoting with separate arguments
456 # Quoting with separate arguments
457 escaped_quote =
457 escaped_quote =
458 [ (',f', 'f("")'),
458 [ (',f', 'f("")'),
459 (',f x', 'f("x")'),
459 (',f x', 'f("x")'),
460 (' ,f y', ' f("y")'),
460 (' ,f y', ' f("y")'),
461 (',f a b', 'f("a", "b")'),
461 (',f a b', 'f("a", "b")'),
462 ],
462 ],
463
463
464 # Quoting with single argument
464 # Quoting with single argument
465 escaped_quote2 =
465 escaped_quote2 =
466 [ (';f', 'f("")'),
466 [ (';f', 'f("")'),
467 (';f x', 'f("x")'),
467 (';f x', 'f("x")'),
468 (' ;f y', ' f("y")'),
468 (' ;f y', ' f("y")'),
469 (';f a b', 'f("a b")'),
469 (';f a b', 'f("a b")'),
470 ],
470 ],
471
471
472 # Simply apply parens
472 # Simply apply parens
473 escaped_paren =
473 escaped_paren =
474 [ ('/f', 'f()'),
474 [ ('/f', 'f()'),
475 ('/f x', 'f(x)'),
475 ('/f x', 'f(x)'),
476 (' /f y', ' f(y)'),
476 (' /f y', ' f(y)'),
477 ('/f a b', 'f(a, b)'),
477 ('/f a b', 'f(a, b)'),
478 ],
478 ],
479
479
480 )
480 )
481
481
482 # multiline syntax examples. Each of these should be a list of lists, with
482 # multiline syntax examples. Each of these should be a list of lists, with
483 # each entry itself having pairs of raw/transformed input. The union (with
483 # each entry itself having pairs of raw/transformed input. The union (with
484 # '\n'.join() of the transformed inputs is what the splitter should produce
484 # '\n'.join() of the transformed inputs is what the splitter should produce
485 # when fed the raw lines one at a time via push.
485 # when fed the raw lines one at a time via push.
486 syntax_ml = \
486 syntax_ml = \
487 dict(classic_prompt =
487 dict(classic_prompt =
488 [ [('>>> for i in range(10):','for i in range(10):'),
488 [ [('>>> for i in range(10):','for i in range(10):'),
489 ('... print i',' print i'),
489 ('... print i',' print i'),
490 ('... ', ''),
490 ('... ', ''),
491 ],
491 ],
492 ],
492 ],
493
493
494 ipy_prompt =
494 ipy_prompt =
495 [ [('In [24]: for i in range(10):','for i in range(10):'),
495 [ [('In [24]: for i in range(10):','for i in range(10):'),
496 (' ....: print i',' print i'),
496 (' ....: print i',' print i'),
497 (' ....: ', ''),
497 (' ....: ', ''),
498 ],
498 ],
499 ],
499 ],
500 )
500 )
501
501
502
502
503 def test_assign_system():
503 def test_assign_system():
504 transform_checker(syntax['assign_system'], isp.transform_assign_system)
504 transform_checker(syntax['assign_system'], isp.transform_assign_system)
505
505
506
506
507 def test_assign_magic():
507 def test_assign_magic():
508 transform_checker(syntax['assign_magic'], isp.transform_assign_magic)
508 transform_checker(syntax['assign_magic'], isp.transform_assign_magic)
509
509
510
510
511 def test_classic_prompt():
511 def test_classic_prompt():
512 transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt)
512 transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt)
513 for example in syntax_ml['classic_prompt']:
513 for example in syntax_ml['classic_prompt']:
514 transform_checker(example, isp.transform_classic_prompt)
514 transform_checker(example, isp.transform_classic_prompt)
515
515
516
516
517 def test_ipy_prompt():
517 def test_ipy_prompt():
518 transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt)
518 transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt)
519 for example in syntax_ml['ipy_prompt']:
519 for example in syntax_ml['ipy_prompt']:
520 transform_checker(example, isp.transform_ipy_prompt)
520 transform_checker(example, isp.transform_ipy_prompt)
521
521
522
522
523 def test_escaped_noesc():
523 def test_escaped_noesc():
524 transform_checker(syntax['escaped_noesc'], isp.transform_escaped)
524 transform_checker(syntax['escaped_noesc'], isp.transform_escaped)
525
525
526
526
527 def test_escaped_shell():
527 def test_escaped_shell():
528 transform_checker(syntax['escaped_shell'], isp.transform_escaped)
528 transform_checker(syntax['escaped_shell'], isp.transform_escaped)
529
529
530
530
531 def test_escaped_help():
531 def test_escaped_help():
532 transform_checker(syntax['escaped_help'], isp.transform_escaped)
532 transform_checker(syntax['escaped_help'], isp.transform_escaped)
533
533
534
534
535 def test_escaped_magic():
535 def test_escaped_magic():
536 transform_checker(syntax['escaped_magic'], isp.transform_escaped)
536 transform_checker(syntax['escaped_magic'], isp.transform_escaped)
537
537
538
538
539 def test_escaped_quote():
539 def test_escaped_quote():
540 transform_checker(syntax['escaped_quote'], isp.transform_escaped)
540 transform_checker(syntax['escaped_quote'], isp.transform_escaped)
541
541
542
542
543 def test_escaped_quote2():
543 def test_escaped_quote2():
544 transform_checker(syntax['escaped_quote2'], isp.transform_escaped)
544 transform_checker(syntax['escaped_quote2'], isp.transform_escaped)
545
545
546
546
547 def test_escaped_paren():
547 def test_escaped_paren():
548 transform_checker(syntax['escaped_paren'], isp.transform_escaped)
548 transform_checker(syntax['escaped_paren'], isp.transform_escaped)
549
549
550
550
551 class IPythonInputTestCase(InputSplitterTestCase):
551 class IPythonInputTestCase(InputSplitterTestCase):
552 """By just creating a new class whose .isp is a different instance, we
552 """By just creating a new class whose .isp is a different instance, we
553 re-run the same test battery on the new input splitter.
553 re-run the same test battery on the new input splitter.
554
554
555 In addition, this runs the tests over the syntax and syntax_ml dicts that
555 In addition, this runs the tests over the syntax and syntax_ml dicts that
556 were tested by individual functions, as part of the OO interface.
556 were tested by individual functions, as part of the OO interface.
557 """
557 """
558
558
559 def setUp(self):
559 def setUp(self):
560 self.isp = isp.IPythonInputSplitter(input_mode='line')
560 self.isp = isp.IPythonInputSplitter(input_mode='line')
561
561
562 def test_syntax(self):
562 def test_syntax(self):
563 """Call all single-line syntax tests from the main object"""
563 """Call all single-line syntax tests from the main object"""
564 isp = self.isp
564 isp = self.isp
565 for example in syntax.itervalues():
565 for example in syntax.itervalues():
566 for raw, out_t in example:
566 for raw, out_t in example:
567 if raw.startswith(' '):
567 if raw.startswith(' '):
568 continue
568 continue
569
569
570 isp.push(raw)
570 isp.push(raw)
571 out = isp.source_reset().rstrip()
571 out = isp.source_reset().rstrip()
572 self.assertEqual(out, out_t)
572 self.assertEqual(out, out_t)
573
573
574 def test_syntax_multiline(self):
574 def test_syntax_multiline(self):
575 isp = self.isp
575 isp = self.isp
576 for example in syntax_ml.itervalues():
576 for example in syntax_ml.itervalues():
577 out_t_parts = []
577 out_t_parts = []
578 for line_pairs in example:
578 for line_pairs in example:
579 for raw, out_t_part in line_pairs:
579 for raw, out_t_part in line_pairs:
580 isp.push(raw)
580 isp.push(raw)
581 out_t_parts.append(out_t_part)
581 out_t_parts.append(out_t_part)
582
582
583 out = isp.source_reset().rstrip()
583 out = isp.source_reset().rstrip()
584 out_t = '\n'.join(out_t_parts).rstrip()
584 out_t = '\n'.join(out_t_parts).rstrip()
585 self.assertEqual(out, out_t)
585 self.assertEqual(out, out_t)
586
586
587
587
588 class BlockIPythonInputTestCase(IPythonInputTestCase):
588 class BlockIPythonInputTestCase(IPythonInputTestCase):
589
589
590 # Deactivate tests that don't make sense for the block mode
590 # Deactivate tests that don't make sense for the block mode
591 test_push3 = test_split = lambda s: None
591 test_push3 = test_split = lambda s: None
592
592
593 def setUp(self):
593 def setUp(self):
594 self.isp = isp.IPythonInputSplitter(input_mode='block')
594 self.isp = isp.IPythonInputSplitter(input_mode='block')
595
595
596 def test_syntax_multiline(self):
596 def test_syntax_multiline(self):
597 isp = self.isp
597 isp = self.isp
598 for example in syntax_ml.itervalues():
598 for example in syntax_ml.itervalues():
599 raw_parts = []
599 raw_parts = []
600 out_t_parts = []
600 out_t_parts = []
601 for line_pairs in example:
601 for line_pairs in example:
602 for raw, out_t_part in line_pairs:
602 for raw, out_t_part in line_pairs:
603 raw_parts.append(raw)
603 raw_parts.append(raw)
604 out_t_parts.append(out_t_part)
604 out_t_parts.append(out_t_part)
605
605
606 raw = '\n'.join(raw_parts)
606 raw = '\n'.join(raw_parts)
607 out_t = '\n'.join(out_t_parts)
607 out_t = '\n'.join(out_t_parts)
608
608
609 isp.push(raw)
609 isp.push(raw)
610 out = isp.source_reset()
610 out = isp.source_reset()
611 # Match ignoring trailing whitespace
611 # Match ignoring trailing whitespace
612 self.assertEqual(out.rstrip(), out_t.rstrip())
612 self.assertEqual(out.rstrip(), out_t.rstrip())
613
613
614
614
615 #-----------------------------------------------------------------------------
615 #-----------------------------------------------------------------------------
616 # Main - use as a script, mostly for developer experiments
616 # Main - use as a script, mostly for developer experiments
617 #-----------------------------------------------------------------------------
617 #-----------------------------------------------------------------------------
618
618
619 if __name__ == '__main__':
619 if __name__ == '__main__':
620 # A simple demo for interactive experimentation. This code will not get
620 # A simple demo for interactive experimentation. This code will not get
621 # picked up by any test suite.
621 # picked up by any test suite.
622 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
622 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
623
623
624 # configure here the syntax to use, prompt and whether to autoindent
624 # configure here the syntax to use, prompt and whether to autoindent
625 #isp, start_prompt = InputSplitter(), '>>> '
625 #isp, start_prompt = InputSplitter(), '>>> '
626 isp, start_prompt = IPythonInputSplitter(), 'In> '
626 isp, start_prompt = IPythonInputSplitter(), 'In> '
627
627
628 autoindent = True
628 autoindent = True
629 #autoindent = False
629 #autoindent = False
630
630
631 try:
631 try:
632 while True:
632 while True:
633 prompt = start_prompt
633 prompt = start_prompt
634 while isp.push_accepts_more():
634 while isp.push_accepts_more():
635 indent = ' '*isp.indent_spaces
635 indent = ' '*isp.indent_spaces
636 if autoindent:
636 if autoindent:
637 line = indent + raw_input(prompt+indent)
637 line = indent + raw_input(prompt+indent)
638 else:
638 else:
639 line = raw_input(prompt)
639 line = raw_input(prompt)
640 isp.push(line)
640 isp.push(line)
641 prompt = '... '
641 prompt = '... '
642
642
643 # Here we just return input so we can use it in a test suite, but a
643 # Here we just return input so we can use it in a test suite, but a
644 # real interpreter would instead send it for execution somewhere.
644 # real interpreter would instead send it for execution somewhere.
645 #src = isp.source; raise EOFError # dbg
645 #src = isp.source; raise EOFError # dbg
646 src = isp.source_reset()
646 src = isp.source_reset()
647 print 'Input source was:\n', src
647 print 'Input source was:\n', src
648 except EOFError:
648 except EOFError:
649 print 'Bye'
649 print 'Bye'
@@ -1,547 +1,552 b''
1 #!/usr/bin/env python
1 #!/usr/bin/env python
2 """A simple interactive kernel that talks to a frontend over 0MQ.
2 """A simple interactive kernel that talks to a frontend over 0MQ.
3
3
4 Things to do:
4 Things to do:
5
5
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
6 * Implement `set_parent` logic. Right before doing exec, the Kernel should
7 call set_parent on all the PUB objects with the message about to be executed.
7 call set_parent on all the PUB objects with the message about to be executed.
8 * Implement random port and security key logic.
8 * Implement random port and security key logic.
9 * Implement control messages.
9 * Implement control messages.
10 * Implement event loop and poll version.
10 * Implement event loop and poll version.
11 """
11 """
12
12
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Standard library imports.
18 # Standard library imports.
19 import __builtin__
19 import __builtin__
20 import sys
20 import sys
21 import time
21 import time
22 import traceback
22 import traceback
23
23
24 # System library imports.
24 # System library imports.
25 import zmq
25 import zmq
26
26
27 # Local imports.
27 # Local imports.
28 from IPython.config.configurable import Configurable
28 from IPython.config.configurable import Configurable
29 from IPython.utils import io
29 from IPython.utils import io
30 from IPython.utils.jsonutil import json_clean
30 from IPython.utils.jsonutil import json_clean
31 from IPython.lib import pylabtools
31 from IPython.lib import pylabtools
32 from IPython.utils.traitlets import Instance, Float
32 from IPython.utils.traitlets import Instance, Float
33 from entry_point import base_launch_kernel, make_argument_parser, make_kernel, \
33 from entry_point import base_launch_kernel, make_argument_parser, make_kernel, \
34 start_kernel
34 start_kernel
35 from iostream import OutStream
35 from iostream import OutStream
36 from session import Session, Message
36 from session import Session, Message
37 from zmqshell import ZMQInteractiveShell
37 from zmqshell import ZMQInteractiveShell
38
38
39
39
40 #-----------------------------------------------------------------------------
40 #-----------------------------------------------------------------------------
41 # Main kernel class
41 # Main kernel class
42 #-----------------------------------------------------------------------------
42 #-----------------------------------------------------------------------------
43
43
44 class Kernel(Configurable):
44 class Kernel(Configurable):
45
45
46 #---------------------------------------------------------------------------
46 #---------------------------------------------------------------------------
47 # Kernel interface
47 # Kernel interface
48 #---------------------------------------------------------------------------
48 #---------------------------------------------------------------------------
49
49
50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
50 shell = Instance('IPython.core.interactiveshell.InteractiveShellABC')
51 session = Instance(Session)
51 session = Instance(Session)
52 reply_socket = Instance('zmq.Socket')
52 reply_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
53 pub_socket = Instance('zmq.Socket')
54 req_socket = Instance('zmq.Socket')
54 req_socket = Instance('zmq.Socket')
55
55
56 # Private interface
56 # Private interface
57
57
58 # Time to sleep after flushing the stdout/err buffers in each execute
58 # Time to sleep after flushing the stdout/err buffers in each execute
59 # cycle. While this introduces a hard limit on the minimal latency of the
59 # cycle. While this introduces a hard limit on the minimal latency of the
60 # execute cycle, it helps prevent output synchronization problems for
60 # execute cycle, it helps prevent output synchronization problems for
61 # clients.
61 # clients.
62 # Units are in seconds. The minimum zmq latency on local host is probably
62 # Units are in seconds. The minimum zmq latency on local host is probably
63 # ~150 microseconds, set this to 500us for now. We may need to increase it
63 # ~150 microseconds, set this to 500us for now. We may need to increase it
64 # a little if it's not enough after more interactive testing.
64 # a little if it's not enough after more interactive testing.
65 _execute_sleep = Float(0.0005, config=True)
65 _execute_sleep = Float(0.0005, config=True)
66
66
67 # Frequency of the kernel's event loop.
67 # Frequency of the kernel's event loop.
68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
68 # Units are in seconds, kernel subclasses for GUI toolkits may need to
69 # adapt to milliseconds.
69 # adapt to milliseconds.
70 _poll_interval = Float(0.05, config=True)
70 _poll_interval = Float(0.05, config=True)
71
71
72 def __init__(self, **kwargs):
72 def __init__(self, **kwargs):
73 super(Kernel, self).__init__(**kwargs)
73 super(Kernel, self).__init__(**kwargs)
74
74
75 # Initialize the InteractiveShell subclass
75 # Initialize the InteractiveShell subclass
76 self.shell = ZMQInteractiveShell.instance()
76 self.shell = ZMQInteractiveShell.instance()
77 self.shell.displayhook.session = self.session
77 self.shell.displayhook.session = self.session
78 self.shell.displayhook.pub_socket = self.pub_socket
78 self.shell.displayhook.pub_socket = self.pub_socket
79
79
80 # TMP - hack while developing
80 # TMP - hack while developing
81 self.shell._reply_content = None
81 self.shell._reply_content = None
82
82
83 # Build dict of handlers for message types
83 # Build dict of handlers for message types
84 msg_types = [ 'execute_request', 'complete_request',
84 msg_types = [ 'execute_request', 'complete_request',
85 'object_info_request', 'history_request' ]
85 'object_info_request', 'history_request' ]
86 self.handlers = {}
86 self.handlers = {}
87 for msg_type in msg_types:
87 for msg_type in msg_types:
88 self.handlers[msg_type] = getattr(self, msg_type)
88 self.handlers[msg_type] = getattr(self, msg_type)
89
89
90 def do_one_iteration(self):
90 def do_one_iteration(self):
91 """Do one iteration of the kernel's evaluation loop.
91 """Do one iteration of the kernel's evaluation loop.
92 """
92 """
93 try:
93 try:
94 ident = self.reply_socket.recv(zmq.NOBLOCK)
94 ident = self.reply_socket.recv(zmq.NOBLOCK)
95 except zmq.ZMQError, e:
95 except zmq.ZMQError, e:
96 if e.errno == zmq.EAGAIN:
96 if e.errno == zmq.EAGAIN:
97 return
97 return
98 else:
98 else:
99 raise
99 raise
100 # FIXME: Bug in pyzmq/zmq?
100 # FIXME: Bug in pyzmq/zmq?
101 # assert self.reply_socket.rcvmore(), "Missing message part."
101 # assert self.reply_socket.rcvmore(), "Missing message part."
102 msg = self.reply_socket.recv_json()
102 msg = self.reply_socket.recv_json()
103
103
104 # Print some info about this message and leave a '--->' marker, so it's
104 # Print some info about this message and leave a '--->' marker, so it's
105 # easier to trace visually the message chain when debugging. Each
105 # easier to trace visually the message chain when debugging. Each
106 # handler prints its message at the end.
106 # handler prints its message at the end.
107 # Eventually we'll move these from stdout to a logger.
107 # Eventually we'll move these from stdout to a logger.
108 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
108 io.raw_print('\n*** MESSAGE TYPE:', msg['msg_type'], '***')
109 io.raw_print(' Content: ', msg['content'],
109 io.raw_print(' Content: ', msg['content'],
110 '\n --->\n ', sep='', end='')
110 '\n --->\n ', sep='', end='')
111
111
112 # Find and call actual handler for message
112 # Find and call actual handler for message
113 handler = self.handlers.get(msg['msg_type'], None)
113 handler = self.handlers.get(msg['msg_type'], None)
114 if handler is None:
114 if handler is None:
115 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
115 io.raw_print_err("UNKNOWN MESSAGE TYPE:", msg)
116 else:
116 else:
117 handler(ident, msg)
117 handler(ident, msg)
118
118
119 # Check whether we should exit, in case the incoming message set the
119 # Check whether we should exit, in case the incoming message set the
120 # exit flag on
120 # exit flag on
121 if self.shell.exit_now:
121 if self.shell.exit_now:
122 io.raw_print('\nExiting IPython kernel...')
122 io.raw_print('\nExiting IPython kernel...')
123 # We do a normal, clean exit, which allows any actions registered
123 # We do a normal, clean exit, which allows any actions registered
124 # via atexit (such as history saving) to take place.
124 # via atexit (such as history saving) to take place.
125 sys.exit(0)
125 sys.exit(0)
126
126
127
127
128 def start(self):
128 def start(self):
129 """ Start the kernel main loop.
129 """ Start the kernel main loop.
130 """
130 """
131 while True:
131 while True:
132 time.sleep(self._poll_interval)
132 time.sleep(self._poll_interval)
133 self.do_one_iteration()
133 self.do_one_iteration()
134
134
135 #---------------------------------------------------------------------------
135 #---------------------------------------------------------------------------
136 # Kernel request handlers
136 # Kernel request handlers
137 #---------------------------------------------------------------------------
137 #---------------------------------------------------------------------------
138
138
139 def _publish_pyin(self, code, parent):
139 def _publish_pyin(self, code, parent):
140 """Publish the code request on the pyin stream."""
140 """Publish the code request on the pyin stream."""
141
141
142 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
142 pyin_msg = self.session.msg(u'pyin',{u'code':code}, parent=parent)
143 self.pub_socket.send_json(pyin_msg)
143 self.pub_socket.send_json(pyin_msg)
144
144
145 def execute_request(self, ident, parent):
145 def execute_request(self, ident, parent):
146 try:
146 try:
147 content = parent[u'content']
147 content = parent[u'content']
148 code = content[u'code']
148 code = content[u'code']
149 silent = content[u'silent']
149 silent = content[u'silent']
150 except:
150 except:
151 io.raw_print_err("Got bad msg: ")
151 io.raw_print_err("Got bad msg: ")
152 io.raw_print_err(Message(parent))
152 io.raw_print_err(Message(parent))
153 return
153 return
154
154
155 shell = self.shell # we'll need this a lot here
155 shell = self.shell # we'll need this a lot here
156
156
157 # Replace raw_input. Note that is not sufficient to replace
157 # Replace raw_input. Note that is not sufficient to replace
158 # raw_input in the user namespace.
158 # raw_input in the user namespace.
159 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
159 raw_input = lambda prompt='': self._raw_input(prompt, ident, parent)
160 __builtin__.raw_input = raw_input
160 __builtin__.raw_input = raw_input
161
161
162 # Set the parent message of the display hook and out streams.
162 # Set the parent message of the display hook and out streams.
163 shell.displayhook.set_parent(parent)
163 shell.displayhook.set_parent(parent)
164 sys.stdout.set_parent(parent)
164 sys.stdout.set_parent(parent)
165 sys.stderr.set_parent(parent)
165 sys.stderr.set_parent(parent)
166
166
167 # Re-broadcast our input for the benefit of listening clients, and
167 # Re-broadcast our input for the benefit of listening clients, and
168 # start computing output
168 # start computing output
169 if not silent:
169 if not silent:
170 self._publish_pyin(code, parent)
170 self._publish_pyin(code, parent)
171
171
172 reply_content = {}
172 reply_content = {}
173 try:
173 try:
174 if silent:
174 if silent:
175 # runcode uses 'exec' mode, so no displayhook will fire, and it
175 # runcode uses 'exec' mode, so no displayhook will fire, and it
176 # doesn't call logging or history manipulations. Print
176 # doesn't call logging or history manipulations. Print
177 # statements in that code will obviously still execute.
177 # statements in that code will obviously still execute.
178 shell.runcode(code)
178 shell.runcode(code)
179 else:
179 else:
180 # FIXME: runlines calls the exception handler itself.
180 # FIXME: runlines calls the exception handler itself.
181 shell._reply_content = None
181 shell._reply_content = None
182 shell.runlines(code)
182
183 # Experimental: cell mode! Test more before turning into
184 # default and removing the hacks around runlines.
185 shell.run_cell(code)
186 # For now leave this here until we're sure we can stop using it
187 #shell.runlines(code)
183 except:
188 except:
184 status = u'error'
189 status = u'error'
185 # FIXME: this code right now isn't being used yet by default,
190 # FIXME: this code right now isn't being used yet by default,
186 # because the runlines() call above directly fires off exception
191 # because the runlines() call above directly fires off exception
187 # reporting. This code, therefore, is only active in the scenario
192 # reporting. This code, therefore, is only active in the scenario
188 # where runlines itself has an unhandled exception. We need to
193 # where runlines itself has an unhandled exception. We need to
189 # uniformize this, for all exception construction to come from a
194 # uniformize this, for all exception construction to come from a
190 # single location in the codbase.
195 # single location in the codbase.
191 etype, evalue, tb = sys.exc_info()
196 etype, evalue, tb = sys.exc_info()
192 tb_list = traceback.format_exception(etype, evalue, tb)
197 tb_list = traceback.format_exception(etype, evalue, tb)
193 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
198 reply_content.update(shell._showtraceback(etype, evalue, tb_list))
194 else:
199 else:
195 status = u'ok'
200 status = u'ok'
196 reply_content[u'payload'] = shell.payload_manager.read_payload()
201 reply_content[u'payload'] = shell.payload_manager.read_payload()
197 # Be agressive about clearing the payload because we don't want
202 # Be agressive about clearing the payload because we don't want
198 # it to sit in memory until the next execute_request comes in.
203 # it to sit in memory until the next execute_request comes in.
199 shell.payload_manager.clear_payload()
204 shell.payload_manager.clear_payload()
200
205
201 reply_content[u'status'] = status
206 reply_content[u'status'] = status
202 # Compute the execution counter so clients can display prompts
207 # Compute the execution counter so clients can display prompts
203 reply_content['execution_count'] = shell.displayhook.prompt_count
208 reply_content['execution_count'] = shell.displayhook.prompt_count
204
209
205 # FIXME - fish exception info out of shell, possibly left there by
210 # FIXME - fish exception info out of shell, possibly left there by
206 # runlines. We'll need to clean up this logic later.
211 # runlines. We'll need to clean up this logic later.
207 if shell._reply_content is not None:
212 if shell._reply_content is not None:
208 reply_content.update(shell._reply_content)
213 reply_content.update(shell._reply_content)
209
214
210 # At this point, we can tell whether the main code execution succeeded
215 # At this point, we can tell whether the main code execution succeeded
211 # or not. If it did, we proceed to evaluate user_variables/expressions
216 # or not. If it did, we proceed to evaluate user_variables/expressions
212 if reply_content['status'] == 'ok':
217 if reply_content['status'] == 'ok':
213 reply_content[u'user_variables'] = \
218 reply_content[u'user_variables'] = \
214 shell.get_user_variables(content[u'user_variables'])
219 shell.get_user_variables(content[u'user_variables'])
215 reply_content[u'user_expressions'] = \
220 reply_content[u'user_expressions'] = \
216 shell.eval_expressions(content[u'user_expressions'])
221 shell.eval_expressions(content[u'user_expressions'])
217 else:
222 else:
218 # If there was an error, don't even try to compute variables or
223 # If there was an error, don't even try to compute variables or
219 # expressions
224 # expressions
220 reply_content[u'user_variables'] = {}
225 reply_content[u'user_variables'] = {}
221 reply_content[u'user_expressions'] = {}
226 reply_content[u'user_expressions'] = {}
222
227
223 # Send the reply.
228 # Send the reply.
224 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
229 reply_msg = self.session.msg(u'execute_reply', reply_content, parent)
225 io.raw_print(reply_msg)
230 io.raw_print(reply_msg)
226
231
227 # Flush output before sending the reply.
232 # Flush output before sending the reply.
228 sys.stdout.flush()
233 sys.stdout.flush()
229 sys.stderr.flush()
234 sys.stderr.flush()
230 # FIXME: on rare occasions, the flush doesn't seem to make it to the
235 # FIXME: on rare occasions, the flush doesn't seem to make it to the
231 # clients... This seems to mitigate the problem, but we definitely need
236 # clients... This seems to mitigate the problem, but we definitely need
232 # to better understand what's going on.
237 # to better understand what's going on.
233 if self._execute_sleep:
238 if self._execute_sleep:
234 time.sleep(self._execute_sleep)
239 time.sleep(self._execute_sleep)
235
240
236 self.reply_socket.send(ident, zmq.SNDMORE)
241 self.reply_socket.send(ident, zmq.SNDMORE)
237 self.reply_socket.send_json(reply_msg)
242 self.reply_socket.send_json(reply_msg)
238 if reply_msg['content']['status'] == u'error':
243 if reply_msg['content']['status'] == u'error':
239 self._abort_queue()
244 self._abort_queue()
240
245
241 def complete_request(self, ident, parent):
246 def complete_request(self, ident, parent):
242 txt, matches = self._complete(parent)
247 txt, matches = self._complete(parent)
243 matches = {'matches' : matches,
248 matches = {'matches' : matches,
244 'matched_text' : txt,
249 'matched_text' : txt,
245 'status' : 'ok'}
250 'status' : 'ok'}
246 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
251 completion_msg = self.session.send(self.reply_socket, 'complete_reply',
247 matches, parent, ident)
252 matches, parent, ident)
248 io.raw_print(completion_msg)
253 io.raw_print(completion_msg)
249
254
250 def object_info_request(self, ident, parent):
255 def object_info_request(self, ident, parent):
251 object_info = self.shell.object_inspect(parent['content']['oname'])
256 object_info = self.shell.object_inspect(parent['content']['oname'])
252 # Before we send this object over, we turn it into a dict and we scrub
257 # Before we send this object over, we turn it into a dict and we scrub
253 # it for JSON usage
258 # it for JSON usage
254 oinfo = json_clean(object_info._asdict())
259 oinfo = json_clean(object_info._asdict())
255 msg = self.session.send(self.reply_socket, 'object_info_reply',
260 msg = self.session.send(self.reply_socket, 'object_info_reply',
256 oinfo, parent, ident)
261 oinfo, parent, ident)
257 io.raw_print(msg)
262 io.raw_print(msg)
258
263
259 def history_request(self, ident, parent):
264 def history_request(self, ident, parent):
260 output = parent['content']['output']
265 output = parent['content']['output']
261 index = parent['content']['index']
266 index = parent['content']['index']
262 raw = parent['content']['raw']
267 raw = parent['content']['raw']
263 hist = self.shell.get_history(index=index, raw=raw, output=output)
268 hist = self.shell.get_history(index=index, raw=raw, output=output)
264 content = {'history' : hist}
269 content = {'history' : hist}
265 msg = self.session.send(self.reply_socket, 'history_reply',
270 msg = self.session.send(self.reply_socket, 'history_reply',
266 content, parent, ident)
271 content, parent, ident)
267 io.raw_print(msg)
272 io.raw_print(msg)
268
273
269 #---------------------------------------------------------------------------
274 #---------------------------------------------------------------------------
270 # Protected interface
275 # Protected interface
271 #---------------------------------------------------------------------------
276 #---------------------------------------------------------------------------
272
277
273 def _abort_queue(self):
278 def _abort_queue(self):
274 while True:
279 while True:
275 try:
280 try:
276 ident = self.reply_socket.recv(zmq.NOBLOCK)
281 ident = self.reply_socket.recv(zmq.NOBLOCK)
277 except zmq.ZMQError, e:
282 except zmq.ZMQError, e:
278 if e.errno == zmq.EAGAIN:
283 if e.errno == zmq.EAGAIN:
279 break
284 break
280 else:
285 else:
281 assert self.reply_socket.rcvmore(), \
286 assert self.reply_socket.rcvmore(), \
282 "Unexpected missing message part."
287 "Unexpected missing message part."
283 msg = self.reply_socket.recv_json()
288 msg = self.reply_socket.recv_json()
284 io.raw_print("Aborting:\n", Message(msg))
289 io.raw_print("Aborting:\n", Message(msg))
285 msg_type = msg['msg_type']
290 msg_type = msg['msg_type']
286 reply_type = msg_type.split('_')[0] + '_reply'
291 reply_type = msg_type.split('_')[0] + '_reply'
287 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
292 reply_msg = self.session.msg(reply_type, {'status' : 'aborted'}, msg)
288 io.raw_print(reply_msg)
293 io.raw_print(reply_msg)
289 self.reply_socket.send(ident,zmq.SNDMORE)
294 self.reply_socket.send(ident,zmq.SNDMORE)
290 self.reply_socket.send_json(reply_msg)
295 self.reply_socket.send_json(reply_msg)
291 # We need to wait a bit for requests to come in. This can probably
296 # We need to wait a bit for requests to come in. This can probably
292 # be set shorter for true asynchronous clients.
297 # be set shorter for true asynchronous clients.
293 time.sleep(0.1)
298 time.sleep(0.1)
294
299
295 def _raw_input(self, prompt, ident, parent):
300 def _raw_input(self, prompt, ident, parent):
296 # Flush output before making the request.
301 # Flush output before making the request.
297 sys.stderr.flush()
302 sys.stderr.flush()
298 sys.stdout.flush()
303 sys.stdout.flush()
299
304
300 # Send the input request.
305 # Send the input request.
301 content = dict(prompt=prompt)
306 content = dict(prompt=prompt)
302 msg = self.session.msg(u'input_request', content, parent)
307 msg = self.session.msg(u'input_request', content, parent)
303 self.req_socket.send_json(msg)
308 self.req_socket.send_json(msg)
304
309
305 # Await a response.
310 # Await a response.
306 reply = self.req_socket.recv_json()
311 reply = self.req_socket.recv_json()
307 try:
312 try:
308 value = reply['content']['value']
313 value = reply['content']['value']
309 except:
314 except:
310 io.raw_print_err("Got bad raw_input reply: ")
315 io.raw_print_err("Got bad raw_input reply: ")
311 io.raw_print_err(Message(parent))
316 io.raw_print_err(Message(parent))
312 value = ''
317 value = ''
313 return value
318 return value
314
319
315 def _complete(self, msg):
320 def _complete(self, msg):
316 c = msg['content']
321 c = msg['content']
317 try:
322 try:
318 cpos = int(c['cursor_pos'])
323 cpos = int(c['cursor_pos'])
319 except:
324 except:
320 # If we don't get something that we can convert to an integer, at
325 # If we don't get something that we can convert to an integer, at
321 # least attempt the completion guessing the cursor is at the end of
326 # least attempt the completion guessing the cursor is at the end of
322 # the text, if there's any, and otherwise of the line
327 # the text, if there's any, and otherwise of the line
323 cpos = len(c['text'])
328 cpos = len(c['text'])
324 if cpos==0:
329 if cpos==0:
325 cpos = len(c['line'])
330 cpos = len(c['line'])
326 return self.shell.complete(c['text'], c['line'], cpos)
331 return self.shell.complete(c['text'], c['line'], cpos)
327
332
328 def _object_info(self, context):
333 def _object_info(self, context):
329 symbol, leftover = self._symbol_from_context(context)
334 symbol, leftover = self._symbol_from_context(context)
330 if symbol is not None and not leftover:
335 if symbol is not None and not leftover:
331 doc = getattr(symbol, '__doc__', '')
336 doc = getattr(symbol, '__doc__', '')
332 else:
337 else:
333 doc = ''
338 doc = ''
334 object_info = dict(docstring = doc)
339 object_info = dict(docstring = doc)
335 return object_info
340 return object_info
336
341
337 def _symbol_from_context(self, context):
342 def _symbol_from_context(self, context):
338 if not context:
343 if not context:
339 return None, context
344 return None, context
340
345
341 base_symbol_string = context[0]
346 base_symbol_string = context[0]
342 symbol = self.shell.user_ns.get(base_symbol_string, None)
347 symbol = self.shell.user_ns.get(base_symbol_string, None)
343 if symbol is None:
348 if symbol is None:
344 symbol = __builtin__.__dict__.get(base_symbol_string, None)
349 symbol = __builtin__.__dict__.get(base_symbol_string, None)
345 if symbol is None:
350 if symbol is None:
346 return None, context
351 return None, context
347
352
348 context = context[1:]
353 context = context[1:]
349 for i, name in enumerate(context):
354 for i, name in enumerate(context):
350 new_symbol = getattr(symbol, name, None)
355 new_symbol = getattr(symbol, name, None)
351 if new_symbol is None:
356 if new_symbol is None:
352 return symbol, context[i:]
357 return symbol, context[i:]
353 else:
358 else:
354 symbol = new_symbol
359 symbol = new_symbol
355
360
356 return symbol, []
361 return symbol, []
357
362
358
363
359 class QtKernel(Kernel):
364 class QtKernel(Kernel):
360 """A Kernel subclass with Qt support."""
365 """A Kernel subclass with Qt support."""
361
366
362 def start(self):
367 def start(self):
363 """Start a kernel with QtPy4 event loop integration."""
368 """Start a kernel with QtPy4 event loop integration."""
364
369
365 from PyQt4 import QtGui, QtCore
370 from PyQt4 import QtGui, QtCore
366 from IPython.lib.guisupport import (
371 from IPython.lib.guisupport import (
367 get_app_qt4, start_event_loop_qt4
372 get_app_qt4, start_event_loop_qt4
368 )
373 )
369 self.app = get_app_qt4([" "])
374 self.app = get_app_qt4([" "])
370 self.app.setQuitOnLastWindowClosed(False)
375 self.app.setQuitOnLastWindowClosed(False)
371 self.timer = QtCore.QTimer()
376 self.timer = QtCore.QTimer()
372 self.timer.timeout.connect(self.do_one_iteration)
377 self.timer.timeout.connect(self.do_one_iteration)
373 # Units for the timer are in milliseconds
378 # Units for the timer are in milliseconds
374 self.timer.start(1000*self._poll_interval)
379 self.timer.start(1000*self._poll_interval)
375 start_event_loop_qt4(self.app)
380 start_event_loop_qt4(self.app)
376
381
377
382
378 class WxKernel(Kernel):
383 class WxKernel(Kernel):
379 """A Kernel subclass with Wx support."""
384 """A Kernel subclass with Wx support."""
380
385
381 def start(self):
386 def start(self):
382 """Start a kernel with wx event loop support."""
387 """Start a kernel with wx event loop support."""
383
388
384 import wx
389 import wx
385 from IPython.lib.guisupport import start_event_loop_wx
390 from IPython.lib.guisupport import start_event_loop_wx
386 doi = self.do_one_iteration
391 doi = self.do_one_iteration
387 # Wx uses milliseconds
392 # Wx uses milliseconds
388 poll_interval = int(1000*self._poll_interval)
393 poll_interval = int(1000*self._poll_interval)
389
394
390 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
395 # We have to put the wx.Timer in a wx.Frame for it to fire properly.
391 # We make the Frame hidden when we create it in the main app below.
396 # We make the Frame hidden when we create it in the main app below.
392 class TimerFrame(wx.Frame):
397 class TimerFrame(wx.Frame):
393 def __init__(self, func):
398 def __init__(self, func):
394 wx.Frame.__init__(self, None, -1)
399 wx.Frame.__init__(self, None, -1)
395 self.timer = wx.Timer(self)
400 self.timer = wx.Timer(self)
396 # Units for the timer are in milliseconds
401 # Units for the timer are in milliseconds
397 self.timer.Start(poll_interval)
402 self.timer.Start(poll_interval)
398 self.Bind(wx.EVT_TIMER, self.on_timer)
403 self.Bind(wx.EVT_TIMER, self.on_timer)
399 self.func = func
404 self.func = func
400
405
401 def on_timer(self, event):
406 def on_timer(self, event):
402 self.func()
407 self.func()
403
408
404 # We need a custom wx.App to create our Frame subclass that has the
409 # We need a custom wx.App to create our Frame subclass that has the
405 # wx.Timer to drive the ZMQ event loop.
410 # wx.Timer to drive the ZMQ event loop.
406 class IPWxApp(wx.App):
411 class IPWxApp(wx.App):
407 def OnInit(self):
412 def OnInit(self):
408 self.frame = TimerFrame(doi)
413 self.frame = TimerFrame(doi)
409 self.frame.Show(False)
414 self.frame.Show(False)
410 return True
415 return True
411
416
412 # The redirect=False here makes sure that wx doesn't replace
417 # The redirect=False here makes sure that wx doesn't replace
413 # sys.stdout/stderr with its own classes.
418 # sys.stdout/stderr with its own classes.
414 self.app = IPWxApp(redirect=False)
419 self.app = IPWxApp(redirect=False)
415 start_event_loop_wx(self.app)
420 start_event_loop_wx(self.app)
416
421
417
422
418 class TkKernel(Kernel):
423 class TkKernel(Kernel):
419 """A Kernel subclass with Tk support."""
424 """A Kernel subclass with Tk support."""
420
425
421 def start(self):
426 def start(self):
422 """Start a Tk enabled event loop."""
427 """Start a Tk enabled event loop."""
423
428
424 import Tkinter
429 import Tkinter
425 doi = self.do_one_iteration
430 doi = self.do_one_iteration
426 # Tk uses milliseconds
431 # Tk uses milliseconds
427 poll_interval = int(1000*self._poll_interval)
432 poll_interval = int(1000*self._poll_interval)
428 # For Tkinter, we create a Tk object and call its withdraw method.
433 # For Tkinter, we create a Tk object and call its withdraw method.
429 class Timer(object):
434 class Timer(object):
430 def __init__(self, func):
435 def __init__(self, func):
431 self.app = Tkinter.Tk()
436 self.app = Tkinter.Tk()
432 self.app.withdraw()
437 self.app.withdraw()
433 self.func = func
438 self.func = func
434
439
435 def on_timer(self):
440 def on_timer(self):
436 self.func()
441 self.func()
437 self.app.after(poll_interval, self.on_timer)
442 self.app.after(poll_interval, self.on_timer)
438
443
439 def start(self):
444 def start(self):
440 self.on_timer() # Call it once to get things going.
445 self.on_timer() # Call it once to get things going.
441 self.app.mainloop()
446 self.app.mainloop()
442
447
443 self.timer = Timer(doi)
448 self.timer = Timer(doi)
444 self.timer.start()
449 self.timer.start()
445
450
446
451
447 class GTKKernel(Kernel):
452 class GTKKernel(Kernel):
448 """A Kernel subclass with GTK support."""
453 """A Kernel subclass with GTK support."""
449
454
450 def start(self):
455 def start(self):
451 """Start the kernel, coordinating with the GTK event loop"""
456 """Start the kernel, coordinating with the GTK event loop"""
452 from .gui.gtkembed import GTKEmbed
457 from .gui.gtkembed import GTKEmbed
453
458
454 gtk_kernel = GTKEmbed(self)
459 gtk_kernel = GTKEmbed(self)
455 gtk_kernel.start()
460 gtk_kernel.start()
456
461
457
462
458 #-----------------------------------------------------------------------------
463 #-----------------------------------------------------------------------------
459 # Kernel main and launch functions
464 # Kernel main and launch functions
460 #-----------------------------------------------------------------------------
465 #-----------------------------------------------------------------------------
461
466
462 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0,
467 def launch_kernel(xrep_port=0, pub_port=0, req_port=0, hb_port=0,
463 independent=False, pylab=False):
468 independent=False, pylab=False):
464 """Launches a localhost kernel, binding to the specified ports.
469 """Launches a localhost kernel, binding to the specified ports.
465
470
466 Parameters
471 Parameters
467 ----------
472 ----------
468 xrep_port : int, optional
473 xrep_port : int, optional
469 The port to use for XREP channel.
474 The port to use for XREP channel.
470
475
471 pub_port : int, optional
476 pub_port : int, optional
472 The port to use for the SUB channel.
477 The port to use for the SUB channel.
473
478
474 req_port : int, optional
479 req_port : int, optional
475 The port to use for the REQ (raw input) channel.
480 The port to use for the REQ (raw input) channel.
476
481
477 hb_port : int, optional
482 hb_port : int, optional
478 The port to use for the hearbeat REP channel.
483 The port to use for the hearbeat REP channel.
479
484
480 independent : bool, optional (default False)
485 independent : bool, optional (default False)
481 If set, the kernel process is guaranteed to survive if this process
486 If set, the kernel process is guaranteed to survive if this process
482 dies. If not set, an effort is made to ensure that the kernel is killed
487 dies. If not set, an effort is made to ensure that the kernel is killed
483 when this process dies. Note that in this case it is still good practice
488 when this process dies. Note that in this case it is still good practice
484 to kill kernels manually before exiting.
489 to kill kernels manually before exiting.
485
490
486 pylab : bool or string, optional (default False)
491 pylab : bool or string, optional (default False)
487 If not False, the kernel will be launched with pylab enabled. If a
492 If not False, the kernel will be launched with pylab enabled. If a
488 string is passed, matplotlib will use the specified backend. Otherwise,
493 string is passed, matplotlib will use the specified backend. Otherwise,
489 matplotlib's default backend will be used.
494 matplotlib's default backend will be used.
490
495
491 Returns
496 Returns
492 -------
497 -------
493 A tuple of form:
498 A tuple of form:
494 (kernel_process, xrep_port, pub_port, req_port)
499 (kernel_process, xrep_port, pub_port, req_port)
495 where kernel_process is a Popen object and the ports are integers.
500 where kernel_process is a Popen object and the ports are integers.
496 """
501 """
497 extra_arguments = []
502 extra_arguments = []
498 if pylab:
503 if pylab:
499 extra_arguments.append('--pylab')
504 extra_arguments.append('--pylab')
500 if isinstance(pylab, basestring):
505 if isinstance(pylab, basestring):
501 extra_arguments.append(pylab)
506 extra_arguments.append(pylab)
502 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
507 return base_launch_kernel('from IPython.zmq.ipkernel import main; main()',
503 xrep_port, pub_port, req_port, hb_port,
508 xrep_port, pub_port, req_port, hb_port,
504 independent, extra_arguments)
509 independent, extra_arguments)
505
510
506
511
507 def main():
512 def main():
508 """ The IPython kernel main entry point.
513 """ The IPython kernel main entry point.
509 """
514 """
510 parser = make_argument_parser()
515 parser = make_argument_parser()
511 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
516 parser.add_argument('--pylab', type=str, metavar='GUI', nargs='?',
512 const='auto', help = \
517 const='auto', help = \
513 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
518 "Pre-load matplotlib and numpy for interactive use. If GUI is not \
514 given, the GUI backend is matplotlib's, otherwise use one of: \
519 given, the GUI backend is matplotlib's, otherwise use one of: \
515 ['tk', 'gtk', 'qt', 'wx', 'payload-svg'].")
520 ['tk', 'gtk', 'qt', 'wx', 'payload-svg'].")
516 namespace = parser.parse_args()
521 namespace = parser.parse_args()
517
522
518 kernel_class = Kernel
523 kernel_class = Kernel
519
524
520 kernel_classes = {
525 kernel_classes = {
521 'qt' : QtKernel,
526 'qt' : QtKernel,
522 'qt4': QtKernel,
527 'qt4': QtKernel,
523 'payload-svg': Kernel,
528 'payload-svg': Kernel,
524 'wx' : WxKernel,
529 'wx' : WxKernel,
525 'tk' : TkKernel,
530 'tk' : TkKernel,
526 'gtk': GTKKernel,
531 'gtk': GTKKernel,
527 }
532 }
528 if namespace.pylab:
533 if namespace.pylab:
529 if namespace.pylab == 'auto':
534 if namespace.pylab == 'auto':
530 gui, backend = pylabtools.find_gui_and_backend()
535 gui, backend = pylabtools.find_gui_and_backend()
531 else:
536 else:
532 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
537 gui, backend = pylabtools.find_gui_and_backend(namespace.pylab)
533 kernel_class = kernel_classes.get(gui)
538 kernel_class = kernel_classes.get(gui)
534 if kernel_class is None:
539 if kernel_class is None:
535 raise ValueError('GUI is not supported: %r' % gui)
540 raise ValueError('GUI is not supported: %r' % gui)
536 pylabtools.activate_matplotlib(backend)
541 pylabtools.activate_matplotlib(backend)
537
542
538 kernel = make_kernel(namespace, kernel_class, OutStream)
543 kernel = make_kernel(namespace, kernel_class, OutStream)
539
544
540 if namespace.pylab:
545 if namespace.pylab:
541 pylabtools.import_pylab(kernel.shell.user_ns)
546 pylabtools.import_pylab(kernel.shell.user_ns)
542
547
543 start_kernel(namespace, kernel)
548 start_kernel(namespace, kernel)
544
549
545
550
546 if __name__ == '__main__':
551 if __name__ == '__main__':
547 main()
552 main()
@@ -1,485 +1,485 b''
1 """A ZMQ-based subclass of InteractiveShell.
1 """A ZMQ-based subclass of InteractiveShell.
2
2
3 This code is meant to ease the refactoring of the base InteractiveShell into
3 This code is meant to ease the refactoring of the base InteractiveShell into
4 something with a cleaner architecture for 2-process use, without actually
4 something with a cleaner architecture for 2-process use, without actually
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
5 breaking InteractiveShell itself. So we're doing something a bit ugly, where
6 we subclass and override what we want to fix. Once this is working well, we
6 we subclass and override what we want to fix. Once this is working well, we
7 can go back to the base class and refactor the code for a cleaner inheritance
7 can go back to the base class and refactor the code for a cleaner inheritance
8 implementation that doesn't rely on so much monkeypatching.
8 implementation that doesn't rely on so much monkeypatching.
9
9
10 But this lets us maintain a fully working IPython as we develop the new
10 But this lets us maintain a fully working IPython as we develop the new
11 machinery. This should thus be thought of as scaffolding.
11 machinery. This should thus be thought of as scaffolding.
12 """
12 """
13 #-----------------------------------------------------------------------------
13 #-----------------------------------------------------------------------------
14 # Imports
14 # Imports
15 #-----------------------------------------------------------------------------
15 #-----------------------------------------------------------------------------
16 from __future__ import print_function
16 from __future__ import print_function
17
17
18 # Stdlib
18 # Stdlib
19 import inspect
19 import inspect
20 import os
20 import os
21 import re
21 import re
22
22
23 # Our own
23 # Our own
24 from IPython.core.interactiveshell import (
24 from IPython.core.interactiveshell import (
25 InteractiveShell, InteractiveShellABC
25 InteractiveShell, InteractiveShellABC
26 )
26 )
27 from IPython.core.displayhook import DisplayHook
27 from IPython.core.displayhook import DisplayHook
28 from IPython.core.macro import Macro
28 from IPython.core.macro import Macro
29 from IPython.core.payloadpage import install_payload_page
29 from IPython.utils.path import get_py_filename
30 from IPython.utils.path import get_py_filename
30 from IPython.utils.text import StringTypes
31 from IPython.utils.text import StringTypes
31 from IPython.utils.traitlets import Instance, Type, Dict
32 from IPython.utils.traitlets import Instance, Type, Dict
32 from IPython.utils.warn import warn
33 from IPython.utils.warn import warn
33 from IPython.zmq.session import extract_header
34 from IPython.zmq.session import extract_header
34 from IPython.core.payloadpage import install_payload_page
35 from session import Session
35 from session import Session
36
36
37 #-----------------------------------------------------------------------------
37 #-----------------------------------------------------------------------------
38 # Globals and side-effects
38 # Globals and side-effects
39 #-----------------------------------------------------------------------------
39 #-----------------------------------------------------------------------------
40
40
41 # Install the payload version of page.
41 # Install the payload version of page.
42 install_payload_page()
42 install_payload_page()
43
43
44 #-----------------------------------------------------------------------------
44 #-----------------------------------------------------------------------------
45 # Functions and classes
45 # Functions and classes
46 #-----------------------------------------------------------------------------
46 #-----------------------------------------------------------------------------
47
47
48 class ZMQDisplayHook(DisplayHook):
48 class ZMQDisplayHook(DisplayHook):
49
49
50 session = Instance(Session)
50 session = Instance(Session)
51 pub_socket = Instance('zmq.Socket')
51 pub_socket = Instance('zmq.Socket')
52 parent_header = Dict({})
52 parent_header = Dict({})
53
53
54 def set_parent(self, parent):
54 def set_parent(self, parent):
55 """Set the parent for outbound messages."""
55 """Set the parent for outbound messages."""
56 self.parent_header = extract_header(parent)
56 self.parent_header = extract_header(parent)
57
57
58 def start_displayhook(self):
58 def start_displayhook(self):
59 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
59 self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header)
60
60
61 def write_output_prompt(self):
61 def write_output_prompt(self):
62 """Write the output prompt."""
62 """Write the output prompt."""
63 if self.do_full_cache:
63 if self.do_full_cache:
64 self.msg['content']['execution_count'] = self.prompt_count
64 self.msg['content']['execution_count'] = self.prompt_count
65
65
66 def write_result_repr(self, result_repr):
66 def write_result_repr(self, result_repr):
67 self.msg['content']['data'] = result_repr
67 self.msg['content']['data'] = result_repr
68
68
69 def finish_displayhook(self):
69 def finish_displayhook(self):
70 """Finish up all displayhook activities."""
70 """Finish up all displayhook activities."""
71 self.pub_socket.send_json(self.msg)
71 self.pub_socket.send_json(self.msg)
72 self.msg = None
72 self.msg = None
73
73
74
74
75 class ZMQInteractiveShell(InteractiveShell):
75 class ZMQInteractiveShell(InteractiveShell):
76 """A subclass of InteractiveShell for ZMQ."""
76 """A subclass of InteractiveShell for ZMQ."""
77
77
78 displayhook_class = Type(ZMQDisplayHook)
78 displayhook_class = Type(ZMQDisplayHook)
79
79
80 def init_io(self):
80 def init_io(self):
81 # This will just use sys.stdout and sys.stderr. If you want to
81 # This will just use sys.stdout and sys.stderr. If you want to
82 # override sys.stdout and sys.stderr themselves, you need to do that
82 # override sys.stdout and sys.stderr themselves, you need to do that
83 # *before* instantiating this class, because Term holds onto
83 # *before* instantiating this class, because Term holds onto
84 # references to the underlying streams.
84 # references to the underlying streams.
85 import IPython.utils.io
85 import IPython.utils.io
86 Term = IPython.utils.io.IOTerm()
86 Term = IPython.utils.io.IOTerm()
87 IPython.utils.io.Term = Term
87 IPython.utils.io.Term = Term
88
88
89 def magic_doctest_mode(self,parameter_s=''):
89 def magic_doctest_mode(self,parameter_s=''):
90 """Toggle doctest mode on and off.
90 """Toggle doctest mode on and off.
91
91
92 This mode is intended to make IPython behave as much as possible like a
92 This mode is intended to make IPython behave as much as possible like a
93 plain Python shell, from the perspective of how its prompts, exceptions
93 plain Python shell, from the perspective of how its prompts, exceptions
94 and output look. This makes it easy to copy and paste parts of a
94 and output look. This makes it easy to copy and paste parts of a
95 session into doctests. It does so by:
95 session into doctests. It does so by:
96
96
97 - Changing the prompts to the classic ``>>>`` ones.
97 - Changing the prompts to the classic ``>>>`` ones.
98 - Changing the exception reporting mode to 'Plain'.
98 - Changing the exception reporting mode to 'Plain'.
99 - Disabling pretty-printing of output.
99 - Disabling pretty-printing of output.
100
100
101 Note that IPython also supports the pasting of code snippets that have
101 Note that IPython also supports the pasting of code snippets that have
102 leading '>>>' and '...' prompts in them. This means that you can paste
102 leading '>>>' and '...' prompts in them. This means that you can paste
103 doctests from files or docstrings (even if they have leading
103 doctests from files or docstrings (even if they have leading
104 whitespace), and the code will execute correctly. You can then use
104 whitespace), and the code will execute correctly. You can then use
105 '%history -t' to see the translated history; this will give you the
105 '%history -t' to see the translated history; this will give you the
106 input after removal of all the leading prompts and whitespace, which
106 input after removal of all the leading prompts and whitespace, which
107 can be pasted back into an editor.
107 can be pasted back into an editor.
108
108
109 With these features, you can switch into this mode easily whenever you
109 With these features, you can switch into this mode easily whenever you
110 need to do testing and changes to doctests, without having to leave
110 need to do testing and changes to doctests, without having to leave
111 your existing IPython session.
111 your existing IPython session.
112 """
112 """
113
113
114 from IPython.utils.ipstruct import Struct
114 from IPython.utils.ipstruct import Struct
115
115
116 # Shorthands
116 # Shorthands
117 shell = self.shell
117 shell = self.shell
118 # dstore is a data store kept in the instance metadata bag to track any
118 # dstore is a data store kept in the instance metadata bag to track any
119 # changes we make, so we can undo them later.
119 # changes we make, so we can undo them later.
120 dstore = shell.meta.setdefault('doctest_mode', Struct())
120 dstore = shell.meta.setdefault('doctest_mode', Struct())
121 save_dstore = dstore.setdefault
121 save_dstore = dstore.setdefault
122
122
123 # save a few values we'll need to recover later
123 # save a few values we'll need to recover later
124 mode = save_dstore('mode', False)
124 mode = save_dstore('mode', False)
125 save_dstore('rc_pprint', shell.pprint)
125 save_dstore('rc_pprint', shell.pprint)
126 save_dstore('xmode', shell.InteractiveTB.mode)
126 save_dstore('xmode', shell.InteractiveTB.mode)
127
127
128 if mode == False:
128 if mode == False:
129 # turn on
129 # turn on
130 shell.pprint = False
130 shell.pprint = False
131 shell.magic_xmode('Plain')
131 shell.magic_xmode('Plain')
132 else:
132 else:
133 # turn off
133 # turn off
134 shell.pprint = dstore.rc_pprint
134 shell.pprint = dstore.rc_pprint
135 shell.magic_xmode(dstore.xmode)
135 shell.magic_xmode(dstore.xmode)
136
136
137 # Store new mode and inform on console
137 # Store new mode and inform on console
138 dstore.mode = bool(1-int(mode))
138 dstore.mode = bool(1-int(mode))
139 mode_label = ['OFF','ON'][dstore.mode]
139 mode_label = ['OFF','ON'][dstore.mode]
140 print('Doctest mode is:', mode_label)
140 print('Doctest mode is:', mode_label)
141
141
142 # Send the payload back so that clients can modify their prompt display
142 # Send the payload back so that clients can modify their prompt display
143 payload = dict(
143 payload = dict(
144 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
144 source='IPython.zmq.zmqshell.ZMQInteractiveShell.magic_doctest_mode',
145 mode=dstore.mode)
145 mode=dstore.mode)
146 self.payload_manager.write_payload(payload)
146 self.payload_manager.write_payload(payload)
147
147
148 def magic_edit(self,parameter_s='',last_call=['','']):
148 def magic_edit(self,parameter_s='',last_call=['','']):
149 """Bring up an editor and execute the resulting code.
149 """Bring up an editor and execute the resulting code.
150
150
151 Usage:
151 Usage:
152 %edit [options] [args]
152 %edit [options] [args]
153
153
154 %edit runs IPython's editor hook. The default version of this hook is
154 %edit runs IPython's editor hook. The default version of this hook is
155 set to call the __IPYTHON__.rc.editor command. This is read from your
155 set to call the __IPYTHON__.rc.editor command. This is read from your
156 environment variable $EDITOR. If this isn't found, it will default to
156 environment variable $EDITOR. If this isn't found, it will default to
157 vi under Linux/Unix and to notepad under Windows. See the end of this
157 vi under Linux/Unix and to notepad under Windows. See the end of this
158 docstring for how to change the editor hook.
158 docstring for how to change the editor hook.
159
159
160 You can also set the value of this editor via the command line option
160 You can also set the value of this editor via the command line option
161 '-editor' or in your ipythonrc file. This is useful if you wish to use
161 '-editor' or in your ipythonrc file. This is useful if you wish to use
162 specifically for IPython an editor different from your typical default
162 specifically for IPython an editor different from your typical default
163 (and for Windows users who typically don't set environment variables).
163 (and for Windows users who typically don't set environment variables).
164
164
165 This command allows you to conveniently edit multi-line code right in
165 This command allows you to conveniently edit multi-line code right in
166 your IPython session.
166 your IPython session.
167
167
168 If called without arguments, %edit opens up an empty editor with a
168 If called without arguments, %edit opens up an empty editor with a
169 temporary file and will execute the contents of this file when you
169 temporary file and will execute the contents of this file when you
170 close it (don't forget to save it!).
170 close it (don't forget to save it!).
171
171
172
172
173 Options:
173 Options:
174
174
175 -n <number>: open the editor at a specified line number. By default,
175 -n <number>: open the editor at a specified line number. By default,
176 the IPython editor hook uses the unix syntax 'editor +N filename', but
176 the IPython editor hook uses the unix syntax 'editor +N filename', but
177 you can configure this by providing your own modified hook if your
177 you can configure this by providing your own modified hook if your
178 favorite editor supports line-number specifications with a different
178 favorite editor supports line-number specifications with a different
179 syntax.
179 syntax.
180
180
181 -p: this will call the editor with the same data as the previous time
181 -p: this will call the editor with the same data as the previous time
182 it was used, regardless of how long ago (in your current session) it
182 it was used, regardless of how long ago (in your current session) it
183 was.
183 was.
184
184
185 -r: use 'raw' input. This option only applies to input taken from the
185 -r: use 'raw' input. This option only applies to input taken from the
186 user's history. By default, the 'processed' history is used, so that
186 user's history. By default, the 'processed' history is used, so that
187 magics are loaded in their transformed version to valid Python. If
187 magics are loaded in their transformed version to valid Python. If
188 this option is given, the raw input as typed as the command line is
188 this option is given, the raw input as typed as the command line is
189 used instead. When you exit the editor, it will be executed by
189 used instead. When you exit the editor, it will be executed by
190 IPython's own processor.
190 IPython's own processor.
191
191
192 -x: do not execute the edited code immediately upon exit. This is
192 -x: do not execute the edited code immediately upon exit. This is
193 mainly useful if you are editing programs which need to be called with
193 mainly useful if you are editing programs which need to be called with
194 command line arguments, which you can then do using %run.
194 command line arguments, which you can then do using %run.
195
195
196
196
197 Arguments:
197 Arguments:
198
198
199 If arguments are given, the following possibilites exist:
199 If arguments are given, the following possibilites exist:
200
200
201 - The arguments are numbers or pairs of colon-separated numbers (like
201 - The arguments are numbers or pairs of colon-separated numbers (like
202 1 4:8 9). These are interpreted as lines of previous input to be
202 1 4:8 9). These are interpreted as lines of previous input to be
203 loaded into the editor. The syntax is the same of the %macro command.
203 loaded into the editor. The syntax is the same of the %macro command.
204
204
205 - If the argument doesn't start with a number, it is evaluated as a
205 - If the argument doesn't start with a number, it is evaluated as a
206 variable and its contents loaded into the editor. You can thus edit
206 variable and its contents loaded into the editor. You can thus edit
207 any string which contains python code (including the result of
207 any string which contains python code (including the result of
208 previous edits).
208 previous edits).
209
209
210 - If the argument is the name of an object (other than a string),
210 - If the argument is the name of an object (other than a string),
211 IPython will try to locate the file where it was defined and open the
211 IPython will try to locate the file where it was defined and open the
212 editor at the point where it is defined. You can use `%edit function`
212 editor at the point where it is defined. You can use `%edit function`
213 to load an editor exactly at the point where 'function' is defined,
213 to load an editor exactly at the point where 'function' is defined,
214 edit it and have the file be executed automatically.
214 edit it and have the file be executed automatically.
215
215
216 If the object is a macro (see %macro for details), this opens up your
216 If the object is a macro (see %macro for details), this opens up your
217 specified editor with a temporary file containing the macro's data.
217 specified editor with a temporary file containing the macro's data.
218 Upon exit, the macro is reloaded with the contents of the file.
218 Upon exit, the macro is reloaded with the contents of the file.
219
219
220 Note: opening at an exact line is only supported under Unix, and some
220 Note: opening at an exact line is only supported under Unix, and some
221 editors (like kedit and gedit up to Gnome 2.8) do not understand the
221 editors (like kedit and gedit up to Gnome 2.8) do not understand the
222 '+NUMBER' parameter necessary for this feature. Good editors like
222 '+NUMBER' parameter necessary for this feature. Good editors like
223 (X)Emacs, vi, jed, pico and joe all do.
223 (X)Emacs, vi, jed, pico and joe all do.
224
224
225 - If the argument is not found as a variable, IPython will look for a
225 - If the argument is not found as a variable, IPython will look for a
226 file with that name (adding .py if necessary) and load it into the
226 file with that name (adding .py if necessary) and load it into the
227 editor. It will execute its contents with execfile() when you exit,
227 editor. It will execute its contents with execfile() when you exit,
228 loading any code in the file into your interactive namespace.
228 loading any code in the file into your interactive namespace.
229
229
230 After executing your code, %edit will return as output the code you
230 After executing your code, %edit will return as output the code you
231 typed in the editor (except when it was an existing file). This way
231 typed in the editor (except when it was an existing file). This way
232 you can reload the code in further invocations of %edit as a variable,
232 you can reload the code in further invocations of %edit as a variable,
233 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
233 via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of
234 the output.
234 the output.
235
235
236 Note that %edit is also available through the alias %ed.
236 Note that %edit is also available through the alias %ed.
237
237
238 This is an example of creating a simple function inside the editor and
238 This is an example of creating a simple function inside the editor and
239 then modifying it. First, start up the editor:
239 then modifying it. First, start up the editor:
240
240
241 In [1]: ed
241 In [1]: ed
242 Editing... done. Executing edited code...
242 Editing... done. Executing edited code...
243 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
243 Out[1]: 'def foo():n print "foo() was defined in an editing session"n'
244
244
245 We can then call the function foo():
245 We can then call the function foo():
246
246
247 In [2]: foo()
247 In [2]: foo()
248 foo() was defined in an editing session
248 foo() was defined in an editing session
249
249
250 Now we edit foo. IPython automatically loads the editor with the
250 Now we edit foo. IPython automatically loads the editor with the
251 (temporary) file where foo() was previously defined:
251 (temporary) file where foo() was previously defined:
252
252
253 In [3]: ed foo
253 In [3]: ed foo
254 Editing... done. Executing edited code...
254 Editing... done. Executing edited code...
255
255
256 And if we call foo() again we get the modified version:
256 And if we call foo() again we get the modified version:
257
257
258 In [4]: foo()
258 In [4]: foo()
259 foo() has now been changed!
259 foo() has now been changed!
260
260
261 Here is an example of how to edit a code snippet successive
261 Here is an example of how to edit a code snippet successive
262 times. First we call the editor:
262 times. First we call the editor:
263
263
264 In [5]: ed
264 In [5]: ed
265 Editing... done. Executing edited code...
265 Editing... done. Executing edited code...
266 hello
266 hello
267 Out[5]: "print 'hello'n"
267 Out[5]: "print 'hello'n"
268
268
269 Now we call it again with the previous output (stored in _):
269 Now we call it again with the previous output (stored in _):
270
270
271 In [6]: ed _
271 In [6]: ed _
272 Editing... done. Executing edited code...
272 Editing... done. Executing edited code...
273 hello world
273 hello world
274 Out[6]: "print 'hello world'n"
274 Out[6]: "print 'hello world'n"
275
275
276 Now we call it with the output #8 (stored in _8, also as Out[8]):
276 Now we call it with the output #8 (stored in _8, also as Out[8]):
277
277
278 In [7]: ed _8
278 In [7]: ed _8
279 Editing... done. Executing edited code...
279 Editing... done. Executing edited code...
280 hello again
280 hello again
281 Out[7]: "print 'hello again'n"
281 Out[7]: "print 'hello again'n"
282
282
283
283
284 Changing the default editor hook:
284 Changing the default editor hook:
285
285
286 If you wish to write your own editor hook, you can put it in a
286 If you wish to write your own editor hook, you can put it in a
287 configuration file which you load at startup time. The default hook
287 configuration file which you load at startup time. The default hook
288 is defined in the IPython.core.hooks module, and you can use that as a
288 is defined in the IPython.core.hooks module, and you can use that as a
289 starting example for further modifications. That file also has
289 starting example for further modifications. That file also has
290 general instructions on how to set a new hook for use once you've
290 general instructions on how to set a new hook for use once you've
291 defined it."""
291 defined it."""
292
292
293 # FIXME: This function has become a convoluted mess. It needs a
293 # FIXME: This function has become a convoluted mess. It needs a
294 # ground-up rewrite with clean, simple logic.
294 # ground-up rewrite with clean, simple logic.
295
295
296 def make_filename(arg):
296 def make_filename(arg):
297 "Make a filename from the given args"
297 "Make a filename from the given args"
298 try:
298 try:
299 filename = get_py_filename(arg)
299 filename = get_py_filename(arg)
300 except IOError:
300 except IOError:
301 if args.endswith('.py'):
301 if args.endswith('.py'):
302 filename = arg
302 filename = arg
303 else:
303 else:
304 filename = None
304 filename = None
305 return filename
305 return filename
306
306
307 # custom exceptions
307 # custom exceptions
308 class DataIsObject(Exception): pass
308 class DataIsObject(Exception): pass
309
309
310 opts,args = self.parse_options(parameter_s,'prn:')
310 opts,args = self.parse_options(parameter_s,'prn:')
311 # Set a few locals from the options for convenience:
311 # Set a few locals from the options for convenience:
312 opts_p = opts.has_key('p')
312 opts_p = opts.has_key('p')
313 opts_r = opts.has_key('r')
313 opts_r = opts.has_key('r')
314
314
315 # Default line number value
315 # Default line number value
316 lineno = opts.get('n',None)
316 lineno = opts.get('n',None)
317 if lineno is not None:
317 if lineno is not None:
318 try:
318 try:
319 lineno = int(lineno)
319 lineno = int(lineno)
320 except:
320 except:
321 warn("The -n argument must be an integer.")
321 warn("The -n argument must be an integer.")
322 return
322 return
323
323
324 if opts_p:
324 if opts_p:
325 args = '_%s' % last_call[0]
325 args = '_%s' % last_call[0]
326 if not self.shell.user_ns.has_key(args):
326 if not self.shell.user_ns.has_key(args):
327 args = last_call[1]
327 args = last_call[1]
328
328
329 # use last_call to remember the state of the previous call, but don't
329 # use last_call to remember the state of the previous call, but don't
330 # let it be clobbered by successive '-p' calls.
330 # let it be clobbered by successive '-p' calls.
331 try:
331 try:
332 last_call[0] = self.shell.displayhook.prompt_count
332 last_call[0] = self.shell.displayhook.prompt_count
333 if not opts_p:
333 if not opts_p:
334 last_call[1] = parameter_s
334 last_call[1] = parameter_s
335 except:
335 except:
336 pass
336 pass
337
337
338 # by default this is done with temp files, except when the given
338 # by default this is done with temp files, except when the given
339 # arg is a filename
339 # arg is a filename
340 use_temp = 1
340 use_temp = 1
341
341
342 if re.match(r'\d',args):
342 if re.match(r'\d',args):
343 # Mode where user specifies ranges of lines, like in %macro.
343 # Mode where user specifies ranges of lines, like in %macro.
344 # This means that you can't edit files whose names begin with
344 # This means that you can't edit files whose names begin with
345 # numbers this way. Tough.
345 # numbers this way. Tough.
346 ranges = args.split()
346 ranges = args.split()
347 data = ''.join(self.extract_input_slices(ranges,opts_r))
347 data = ''.join(self.extract_input_slices(ranges,opts_r))
348 elif args.endswith('.py'):
348 elif args.endswith('.py'):
349 filename = make_filename(args)
349 filename = make_filename(args)
350 data = ''
350 data = ''
351 use_temp = 0
351 use_temp = 0
352 elif args:
352 elif args:
353 try:
353 try:
354 # Load the parameter given as a variable. If not a string,
354 # Load the parameter given as a variable. If not a string,
355 # process it as an object instead (below)
355 # process it as an object instead (below)
356
356
357 #print '*** args',args,'type',type(args) # dbg
357 #print '*** args',args,'type',type(args) # dbg
358 data = eval(args,self.shell.user_ns)
358 data = eval(args,self.shell.user_ns)
359 if not type(data) in StringTypes:
359 if not type(data) in StringTypes:
360 raise DataIsObject
360 raise DataIsObject
361
361
362 except (NameError,SyntaxError):
362 except (NameError,SyntaxError):
363 # given argument is not a variable, try as a filename
363 # given argument is not a variable, try as a filename
364 filename = make_filename(args)
364 filename = make_filename(args)
365 if filename is None:
365 if filename is None:
366 warn("Argument given (%s) can't be found as a variable "
366 warn("Argument given (%s) can't be found as a variable "
367 "or as a filename." % args)
367 "or as a filename." % args)
368 return
368 return
369
369
370 data = ''
370 data = ''
371 use_temp = 0
371 use_temp = 0
372 except DataIsObject:
372 except DataIsObject:
373
373
374 # macros have a special edit function
374 # macros have a special edit function
375 if isinstance(data,Macro):
375 if isinstance(data,Macro):
376 self._edit_macro(args,data)
376 self._edit_macro(args,data)
377 return
377 return
378
378
379 # For objects, try to edit the file where they are defined
379 # For objects, try to edit the file where they are defined
380 try:
380 try:
381 filename = inspect.getabsfile(data)
381 filename = inspect.getabsfile(data)
382 if 'fakemodule' in filename.lower() and inspect.isclass(data):
382 if 'fakemodule' in filename.lower() and inspect.isclass(data):
383 # class created by %edit? Try to find source
383 # class created by %edit? Try to find source
384 # by looking for method definitions instead, the
384 # by looking for method definitions instead, the
385 # __module__ in those classes is FakeModule.
385 # __module__ in those classes is FakeModule.
386 attrs = [getattr(data, aname) for aname in dir(data)]
386 attrs = [getattr(data, aname) for aname in dir(data)]
387 for attr in attrs:
387 for attr in attrs:
388 if not inspect.ismethod(attr):
388 if not inspect.ismethod(attr):
389 continue
389 continue
390 filename = inspect.getabsfile(attr)
390 filename = inspect.getabsfile(attr)
391 if filename and 'fakemodule' not in filename.lower():
391 if filename and 'fakemodule' not in filename.lower():
392 # change the attribute to be the edit target instead
392 # change the attribute to be the edit target instead
393 data = attr
393 data = attr
394 break
394 break
395
395
396 datafile = 1
396 datafile = 1
397 except TypeError:
397 except TypeError:
398 filename = make_filename(args)
398 filename = make_filename(args)
399 datafile = 1
399 datafile = 1
400 warn('Could not find file where `%s` is defined.\n'
400 warn('Could not find file where `%s` is defined.\n'
401 'Opening a file named `%s`' % (args,filename))
401 'Opening a file named `%s`' % (args,filename))
402 # Now, make sure we can actually read the source (if it was in
402 # Now, make sure we can actually read the source (if it was in
403 # a temp file it's gone by now).
403 # a temp file it's gone by now).
404 if datafile:
404 if datafile:
405 try:
405 try:
406 if lineno is None:
406 if lineno is None:
407 lineno = inspect.getsourcelines(data)[1]
407 lineno = inspect.getsourcelines(data)[1]
408 except IOError:
408 except IOError:
409 filename = make_filename(args)
409 filename = make_filename(args)
410 if filename is None:
410 if filename is None:
411 warn('The file `%s` where `%s` was defined cannot '
411 warn('The file `%s` where `%s` was defined cannot '
412 'be read.' % (filename,data))
412 'be read.' % (filename,data))
413 return
413 return
414 use_temp = 0
414 use_temp = 0
415 else:
415 else:
416 data = ''
416 data = ''
417
417
418 if use_temp:
418 if use_temp:
419 filename = self.shell.mktempfile(data)
419 filename = self.shell.mktempfile(data)
420 print('IPython will make a temporary file named:', filename)
420 print('IPython will make a temporary file named:', filename)
421
421
422 # Make sure we send to the client an absolute path, in case the working
422 # Make sure we send to the client an absolute path, in case the working
423 # directory of client and kernel don't match
423 # directory of client and kernel don't match
424 filename = os.path.abspath(filename)
424 filename = os.path.abspath(filename)
425
425
426 payload = {
426 payload = {
427 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
427 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic',
428 'filename' : filename,
428 'filename' : filename,
429 'line_number' : lineno
429 'line_number' : lineno
430 }
430 }
431 self.payload_manager.write_payload(payload)
431 self.payload_manager.write_payload(payload)
432
432
433 def magic_gui(self, *args, **kwargs):
433 def magic_gui(self, *args, **kwargs):
434 raise NotImplementedError('GUI support must be enabled in command line options.')
434 raise NotImplementedError('GUI support must be enabled in command line options.')
435
435
436 def magic_pylab(self, *args, **kwargs):
436 def magic_pylab(self, *args, **kwargs):
437 raise NotImplementedError('pylab support must be enabled in commandl in options.')
437 raise NotImplementedError('pylab support must be enabled in commandl in options.')
438
438
439 def auto_rewrite_input(self, cmd):
439 def auto_rewrite_input(self, cmd):
440 """Called to show the auto-rewritten input for autocall and friends.
440 """Called to show the auto-rewritten input for autocall and friends.
441
441
442 FIXME: this payload is currently not correctly processed by the
442 FIXME: this payload is currently not correctly processed by the
443 frontend.
443 frontend.
444 """
444 """
445 new = self.displayhook.prompt1.auto_rewrite() + cmd
445 new = self.displayhook.prompt1.auto_rewrite() + cmd
446 payload = dict(
446 payload = dict(
447 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
447 source='IPython.zmq.zmqshell.ZMQInteractiveShell.auto_rewrite_input',
448 transformed_input=new,
448 transformed_input=new,
449 )
449 )
450 self.payload_manager.write_payload(payload)
450 self.payload_manager.write_payload(payload)
451
451
452 def ask_exit(self):
452 def ask_exit(self):
453 """Engage the exit actions."""
453 """Engage the exit actions."""
454 payload = dict(
454 payload = dict(
455 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
455 source='IPython.zmq.zmqshell.ZMQInteractiveShell.ask_exit',
456 exit=True,
456 exit=True,
457 )
457 )
458 self.payload_manager.write_payload(payload)
458 self.payload_manager.write_payload(payload)
459
459
460 def _showtraceback(self, etype, evalue, stb):
460 def _showtraceback(self, etype, evalue, stb):
461
461
462 exc_content = {
462 exc_content = {
463 u'traceback' : stb,
463 u'traceback' : stb,
464 u'ename' : unicode(etype.__name__),
464 u'ename' : unicode(etype.__name__),
465 u'evalue' : unicode(evalue)
465 u'evalue' : unicode(evalue)
466 }
466 }
467
467
468 dh = self.displayhook
468 dh = self.displayhook
469 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
469 exc_msg = dh.session.msg(u'pyerr', exc_content, dh.parent_header)
470 # Send exception info over pub socket for other clients than the caller
470 # Send exception info over pub socket for other clients than the caller
471 # to pick up
471 # to pick up
472 dh.pub_socket.send_json(exc_msg)
472 dh.pub_socket.send_json(exc_msg)
473
473
474 # FIXME - Hack: store exception info in shell object. Right now, the
474 # FIXME - Hack: store exception info in shell object. Right now, the
475 # caller is reading this info after the fact, we need to fix this logic
475 # caller is reading this info after the fact, we need to fix this logic
476 # to remove this hack. Even uglier, we need to store the error status
476 # to remove this hack. Even uglier, we need to store the error status
477 # here, because in the main loop, the logic that sets it is being
477 # here, because in the main loop, the logic that sets it is being
478 # skipped because runlines swallows the exceptions.
478 # skipped because runlines swallows the exceptions.
479 exc_content[u'status'] = u'error'
479 exc_content[u'status'] = u'error'
480 self._reply_content = exc_content
480 self._reply_content = exc_content
481 # /FIXME
481 # /FIXME
482
482
483 return exc_content
483 return exc_content
484
484
485 InteractiveShellABC.register(ZMQInteractiveShell)
485 InteractiveShellABC.register(ZMQInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now