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