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