Show More
@@ -1,960 +1,956 b'' | |||||
1 | """Analysis of text input into executable blocks. |
|
1 | """Analysis of text input into executable blocks. | |
2 |
|
2 | |||
3 | The main class in this module, :class:`InputSplitter`, is designed to break |
|
3 | The main class in this module, :class:`InputSplitter`, is designed to break | |
4 | input from either interactive, line-by-line environments or block-based ones, |
|
4 | input from either interactive, line-by-line environments or block-based ones, | |
5 | into standalone blocks that can be executed by Python as 'single' statements |
|
5 | into standalone blocks that can be executed by Python as 'single' statements | |
6 | (thus triggering sys.displayhook). |
|
6 | (thus triggering sys.displayhook). | |
7 |
|
7 | |||
8 | A companion, :class:`IPythonInputSplitter`, provides the same functionality but |
|
8 | A companion, :class:`IPythonInputSplitter`, provides the same functionality but | |
9 | with full support for the extended IPython syntax (magics, system calls, etc). |
|
9 | with full support for the extended IPython syntax (magics, system calls, etc). | |
10 |
|
10 | |||
11 | For more details, see the class docstring below. |
|
11 | For more details, see the class docstring below. | |
12 |
|
12 | |||
13 | Syntax Transformations |
|
13 | Syntax Transformations | |
14 | ---------------------- |
|
14 | ---------------------- | |
15 |
|
15 | |||
16 | One of the main jobs of the code in this file is to apply all syntax |
|
16 | One of the main jobs of the code in this file is to apply all syntax | |
17 | transformations that make up 'the IPython language', i.e. magics, shell |
|
17 | transformations that make up 'the IPython language', i.e. magics, shell | |
18 | escapes, etc. All transformations should be implemented as *fully stateless* |
|
18 | escapes, etc. All transformations should be implemented as *fully stateless* | |
19 | entities, that simply take one line as their input and return a line. |
|
19 | entities, that simply take one line as their input and return a line. | |
20 | Internally for implementation purposes they may be a normal function or a |
|
20 | Internally for implementation purposes they may be a normal function or a | |
21 | callable object, but the only input they receive will be a single line and they |
|
21 | callable object, but the only input they receive will be a single line and they | |
22 | should only return a line, without holding any data-dependent state between |
|
22 | should only return a line, without holding any data-dependent state between | |
23 | calls. |
|
23 | calls. | |
24 |
|
24 | |||
25 | As an example, the EscapedTransformer is a class so we can more clearly group |
|
25 | As an example, the EscapedTransformer is a class so we can more clearly group | |
26 | together the functionality of dispatching to individual functions based on the |
|
26 | together the functionality of dispatching to individual functions based on the | |
27 | starting escape character, but the only method for public use is its call |
|
27 | starting escape character, but the only method for public use is its call | |
28 | method. |
|
28 | method. | |
29 |
|
29 | |||
30 |
|
30 | |||
31 | ToDo |
|
31 | ToDo | |
32 | ---- |
|
32 | ---- | |
33 |
|
33 | |||
34 | - Should we make push() actually raise an exception once push_accepts_more() |
|
34 | - Should we make push() actually raise an exception once push_accepts_more() | |
35 | returns False? |
|
35 | returns False? | |
36 |
|
36 | |||
37 | - Naming cleanups. The tr_* names aren't the most elegant, though now they are |
|
37 | - Naming cleanups. The tr_* names aren't the most elegant, though now they are | |
38 | at least just attributes of a class so not really very exposed. |
|
38 | at least just attributes of a class so not really very exposed. | |
39 |
|
39 | |||
40 | - Think about the best way to support dynamic things: automagic, autocall, |
|
40 | - Think about the best way to support dynamic things: automagic, autocall, | |
41 | macros, etc. |
|
41 | macros, etc. | |
42 |
|
42 | |||
43 | - Think of a better heuristic for the application of the transforms in |
|
43 | - Think of a better heuristic for the application of the transforms in | |
44 | IPythonInputSplitter.push() than looking at the buffer ending in ':'. Idea: |
|
44 | IPythonInputSplitter.push() than looking at the buffer ending in ':'. Idea: | |
45 | track indentation change events (indent, dedent, nothing) and apply them only |
|
45 | track indentation change events (indent, dedent, nothing) and apply them only | |
46 | if the indentation went up, but not otherwise. |
|
46 | if the indentation went up, but not otherwise. | |
47 |
|
47 | |||
48 | - Think of the cleanest way for supporting user-specified transformations (the |
|
48 | - Think of the cleanest way for supporting user-specified transformations (the | |
49 | user prefilters we had before). |
|
49 | user prefilters we had before). | |
50 |
|
50 | |||
51 | Authors |
|
51 | Authors | |
52 | ------- |
|
52 | ------- | |
53 |
|
53 | |||
54 | * Fernando Perez |
|
54 | * Fernando Perez | |
55 | * Brian Granger |
|
55 | * Brian Granger | |
56 | """ |
|
56 | """ | |
57 | #----------------------------------------------------------------------------- |
|
57 | #----------------------------------------------------------------------------- | |
58 | # Copyright (C) 2010 The IPython Development Team |
|
58 | # Copyright (C) 2010 The IPython Development Team | |
59 | # |
|
59 | # | |
60 | # Distributed under the terms of the BSD License. The full license is in |
|
60 | # Distributed under the terms of the BSD License. The full license is in | |
61 | # the file COPYING, distributed as part of this software. |
|
61 | # the file COPYING, distributed as part of this software. | |
62 | #----------------------------------------------------------------------------- |
|
62 | #----------------------------------------------------------------------------- | |
63 |
|
63 | |||
64 | #----------------------------------------------------------------------------- |
|
64 | #----------------------------------------------------------------------------- | |
65 | # Imports |
|
65 | # Imports | |
66 | #----------------------------------------------------------------------------- |
|
66 | #----------------------------------------------------------------------------- | |
67 | # stdlib |
|
67 | # stdlib | |
68 | import codeop |
|
68 | import codeop | |
69 | import re |
|
69 | import re | |
70 | import sys |
|
70 | import sys | |
71 |
|
71 | |||
72 | # IPython modules |
|
72 | # IPython modules | |
73 | from IPython.utils.text import make_quoted_expr |
|
73 | from IPython.utils.text import make_quoted_expr | |
74 | #----------------------------------------------------------------------------- |
|
74 | #----------------------------------------------------------------------------- | |
75 | # Globals |
|
75 | # Globals | |
76 | #----------------------------------------------------------------------------- |
|
76 | #----------------------------------------------------------------------------- | |
77 |
|
77 | |||
78 | # The escape sequences that define the syntax transformations IPython will |
|
78 | # The escape sequences that define the syntax transformations IPython will | |
79 | # apply to user input. These can NOT be just changed here: many regular |
|
79 | # apply to user input. These can NOT be just changed here: many regular | |
80 | # expressions and other parts of the code may use their hardcoded values, and |
|
80 | # expressions and other parts of the code may use their hardcoded values, and | |
81 | # for all intents and purposes they constitute the 'IPython syntax', so they |
|
81 | # for all intents and purposes they constitute the 'IPython syntax', so they | |
82 | # should be considered fixed. |
|
82 | # should be considered fixed. | |
83 |
|
83 | |||
84 | ESC_SHELL = '!' |
|
84 | ESC_SHELL = '!' | |
85 | ESC_SH_CAP = '!!' |
|
85 | ESC_SH_CAP = '!!' | |
86 | ESC_HELP = '?' |
|
86 | ESC_HELP = '?' | |
87 | ESC_HELP2 = '??' |
|
87 | ESC_HELP2 = '??' | |
88 | ESC_MAGIC = '%' |
|
88 | ESC_MAGIC = '%' | |
89 | ESC_QUOTE = ',' |
|
89 | ESC_QUOTE = ',' | |
90 | ESC_QUOTE2 = ';' |
|
90 | ESC_QUOTE2 = ';' | |
91 | ESC_PAREN = '/' |
|
91 | ESC_PAREN = '/' | |
92 |
|
92 | |||
93 | #----------------------------------------------------------------------------- |
|
93 | #----------------------------------------------------------------------------- | |
94 | # Utilities |
|
94 | # Utilities | |
95 | #----------------------------------------------------------------------------- |
|
95 | #----------------------------------------------------------------------------- | |
96 |
|
96 | |||
97 | # FIXME: These are general-purpose utilities that later can be moved to the |
|
97 | # FIXME: These are general-purpose utilities that later can be moved to the | |
98 | # general ward. Kept here for now because we're being very strict about test |
|
98 | # general ward. Kept here for now because we're being very strict about test | |
99 | # coverage with this code, and this lets us ensure that we keep 100% coverage |
|
99 | # coverage with this code, and this lets us ensure that we keep 100% coverage | |
100 | # while developing. |
|
100 | # while developing. | |
101 |
|
101 | |||
102 | # compiled regexps for autoindent management |
|
102 | # compiled regexps for autoindent management | |
103 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
103 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
104 | ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)') |
|
104 | ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)') | |
105 |
|
105 | |||
106 | # regexp to match pure comment lines so we don't accidentally insert 'if 1:' |
|
106 | # regexp to match pure comment lines so we don't accidentally insert 'if 1:' | |
107 | # before pure comments |
|
107 | # before pure comments | |
108 | comment_line_re = re.compile('^\s*\#') |
|
108 | comment_line_re = re.compile('^\s*\#') | |
109 |
|
109 | |||
110 |
|
110 | |||
111 | def num_ini_spaces(s): |
|
111 | def num_ini_spaces(s): | |
112 | """Return the number of initial spaces in a string. |
|
112 | """Return the number of initial spaces in a string. | |
113 |
|
113 | |||
114 | Note that tabs are counted as a single space. For now, we do *not* support |
|
114 | Note that tabs are counted as a single space. For now, we do *not* support | |
115 | mixing of tabs and spaces in the user's input. |
|
115 | mixing of tabs and spaces in the user's input. | |
116 |
|
116 | |||
117 | Parameters |
|
117 | Parameters | |
118 | ---------- |
|
118 | ---------- | |
119 | s : string |
|
119 | s : string | |
120 |
|
120 | |||
121 | Returns |
|
121 | Returns | |
122 | ------- |
|
122 | ------- | |
123 | n : int |
|
123 | n : int | |
124 | """ |
|
124 | """ | |
125 |
|
125 | |||
126 | ini_spaces = ini_spaces_re.match(s) |
|
126 | ini_spaces = ini_spaces_re.match(s) | |
127 | if ini_spaces: |
|
127 | if ini_spaces: | |
128 | return ini_spaces.end() |
|
128 | return ini_spaces.end() | |
129 | else: |
|
129 | else: | |
130 | return 0 |
|
130 | return 0 | |
131 |
|
131 | |||
132 |
|
132 | |||
133 | def remove_comments(src): |
|
133 | def remove_comments(src): | |
134 | """Remove all comments from input source. |
|
134 | """Remove all comments from input source. | |
135 |
|
135 | |||
136 | Note: comments are NOT recognized inside of strings! |
|
136 | Note: comments are NOT recognized inside of strings! | |
137 |
|
137 | |||
138 | Parameters |
|
138 | Parameters | |
139 | ---------- |
|
139 | ---------- | |
140 | src : string |
|
140 | src : string | |
141 | A single or multiline input string. |
|
141 | A single or multiline input string. | |
142 |
|
142 | |||
143 | Returns |
|
143 | Returns | |
144 | ------- |
|
144 | ------- | |
145 | String with all Python comments removed. |
|
145 | String with all Python comments removed. | |
146 | """ |
|
146 | """ | |
147 |
|
147 | |||
148 | return re.sub('#.*', '', src) |
|
148 | return re.sub('#.*', '', src) | |
149 |
|
149 | |||
150 |
|
150 | |||
151 | def get_input_encoding(): |
|
151 | def get_input_encoding(): | |
152 | """Return the default standard input encoding. |
|
152 | """Return the default standard input encoding. | |
153 |
|
153 | |||
154 | If sys.stdin has no encoding, 'ascii' is returned.""" |
|
154 | If sys.stdin has no encoding, 'ascii' is returned.""" | |
155 | # There are strange environments for which sys.stdin.encoding is None. We |
|
155 | # There are strange environments for which sys.stdin.encoding is None. We | |
156 | # ensure that a valid encoding is returned. |
|
156 | # ensure that a valid encoding is returned. | |
157 | encoding = getattr(sys.stdin, 'encoding', None) |
|
157 | encoding = getattr(sys.stdin, 'encoding', None) | |
158 | if encoding is None: |
|
158 | if encoding is None: | |
159 | encoding = 'ascii' |
|
159 | encoding = 'ascii' | |
160 | return encoding |
|
160 | return encoding | |
161 |
|
161 | |||
162 | #----------------------------------------------------------------------------- |
|
162 | #----------------------------------------------------------------------------- | |
163 | # Classes and functions for normal Python syntax handling |
|
163 | # Classes and functions for normal Python syntax handling | |
164 | #----------------------------------------------------------------------------- |
|
164 | #----------------------------------------------------------------------------- | |
165 |
|
165 | |||
166 | # HACK! This implementation, written by Robert K a while ago using the |
|
166 | # HACK! This implementation, written by Robert K a while ago using the | |
167 | # compiler module, is more robust than the other one below, but it expects its |
|
167 | # compiler module, is more robust than the other one below, but it expects its | |
168 | # input to be pure python (no ipython syntax). For now we're using it as a |
|
168 | # input to be pure python (no ipython syntax). For now we're using it as a | |
169 | # second-pass splitter after the first pass transforms the input to pure |
|
169 | # second-pass splitter after the first pass transforms the input to pure | |
170 | # python. |
|
170 | # python. | |
171 |
|
171 | |||
172 | def split_blocks(python): |
|
172 | def split_blocks(python): | |
173 | """ Split multiple lines of code into discrete commands that can be |
|
173 | """ Split multiple lines of code into discrete commands that can be | |
174 | executed singly. |
|
174 | executed singly. | |
175 |
|
175 | |||
176 | Parameters |
|
176 | Parameters | |
177 | ---------- |
|
177 | ---------- | |
178 | python : str |
|
178 | python : str | |
179 | Pure, exec'able Python code. |
|
179 | Pure, exec'able Python code. | |
180 |
|
180 | |||
181 | Returns |
|
181 | Returns | |
182 | ------- |
|
182 | ------- | |
183 | commands : list of str |
|
183 | commands : list of str | |
184 | Separate commands that can be exec'ed independently. |
|
184 | Separate commands that can be exec'ed independently. | |
185 | """ |
|
185 | """ | |
186 |
|
186 | |||
187 | import compiler |
|
187 | import compiler | |
188 |
|
188 | |||
189 | # compiler.parse treats trailing spaces after a newline as a |
|
189 | # compiler.parse treats trailing spaces after a newline as a | |
190 | # SyntaxError. This is different than codeop.CommandCompiler, which |
|
190 | # SyntaxError. This is different than codeop.CommandCompiler, which | |
191 | # will compile the trailng spaces just fine. We simply strip any |
|
191 | # will compile the trailng spaces just fine. We simply strip any | |
192 | # trailing whitespace off. Passing a string with trailing whitespace |
|
192 | # trailing whitespace off. Passing a string with trailing whitespace | |
193 | # to exec will fail however. There seems to be some inconsistency in |
|
193 | # to exec will fail however. There seems to be some inconsistency in | |
194 | # how trailing whitespace is handled, but this seems to work. |
|
194 | # how trailing whitespace is handled, but this seems to work. | |
195 | python_ori = python # save original in case we bail on error |
|
195 | python_ori = python # save original in case we bail on error | |
196 | python = python.strip() |
|
196 | python = python.strip() | |
197 |
|
197 | |||
198 | # The compiler module does not like unicode. We need to convert |
|
198 | # The compiler module does not like unicode. We need to convert | |
199 | # it encode it: |
|
199 | # it encode it: | |
200 | if isinstance(python, unicode): |
|
200 | if isinstance(python, unicode): | |
201 | # Use the utf-8-sig BOM so the compiler detects this a UTF-8 |
|
201 | # Use the utf-8-sig BOM so the compiler detects this a UTF-8 | |
202 | # encode string. |
|
202 | # encode string. | |
203 | python = '\xef\xbb\xbf' + python.encode('utf-8') |
|
203 | python = '\xef\xbb\xbf' + python.encode('utf-8') | |
204 |
|
204 | |||
205 | # The compiler module will parse the code into an abstract syntax tree. |
|
205 | # The compiler module will parse the code into an abstract syntax tree. | |
206 | # This has a bug with str("a\nb"), but not str("""a\nb""")!!! |
|
206 | # This has a bug with str("a\nb"), but not str("""a\nb""")!!! | |
207 | try: |
|
207 | try: | |
208 | ast = compiler.parse(python) |
|
208 | ast = compiler.parse(python) | |
209 | except: |
|
209 | except: | |
210 | return [python_ori] |
|
210 | return [python_ori] | |
211 |
|
211 | |||
212 | # Uncomment to help debug the ast tree |
|
212 | # Uncomment to help debug the ast tree | |
213 | # for n in ast.node: |
|
213 | # for n in ast.node: | |
214 | # print n.lineno,'->',n |
|
214 | # print n.lineno,'->',n | |
215 |
|
215 | |||
216 | # Each separate command is available by iterating over ast.node. The |
|
216 | # Each separate command is available by iterating over ast.node. The | |
217 | # lineno attribute is the line number (1-indexed) beginning the commands |
|
217 | # lineno attribute is the line number (1-indexed) beginning the commands | |
218 | # suite. |
|
218 | # suite. | |
219 | # lines ending with ";" yield a Discard Node that doesn't have a lineno |
|
219 | # lines ending with ";" yield a Discard Node that doesn't have a lineno | |
220 | # attribute. These nodes can and should be discarded. But there are |
|
220 | # attribute. These nodes can and should be discarded. But there are | |
221 | # other situations that cause Discard nodes that shouldn't be discarded. |
|
221 | # other situations that cause Discard nodes that shouldn't be discarded. | |
222 | # We might eventually discover other cases where lineno is None and have |
|
222 | # We might eventually discover other cases where lineno is None and have | |
223 | # to put in a more sophisticated test. |
|
223 | # to put in a more sophisticated test. | |
224 | linenos = [x.lineno-1 for x in ast.node if x.lineno is not None] |
|
224 | linenos = [x.lineno-1 for x in ast.node if x.lineno is not None] | |
225 |
|
225 | |||
226 | # When we finally get the slices, we will need to slice all the way to |
|
226 | # When we finally get the slices, we will need to slice all the way to | |
227 | # the end even though we don't have a line number for it. Fortunately, |
|
227 | # the end even though we don't have a line number for it. Fortunately, | |
228 | # None does the job nicely. |
|
228 | # None does the job nicely. | |
229 | linenos.append(None) |
|
229 | linenos.append(None) | |
230 |
|
230 | |||
231 | # Same problem at the other end: sometimes the ast tree has its |
|
231 | # Same problem at the other end: sometimes the ast tree has its | |
232 | # first complete statement not starting on line 0. In this case |
|
232 | # first complete statement not starting on line 0. In this case | |
233 | # we might miss part of it. This fixes ticket 266993. Thanks Gael! |
|
233 | # we might miss part of it. This fixes ticket 266993. Thanks Gael! | |
234 | linenos[0] = 0 |
|
234 | linenos[0] = 0 | |
235 |
|
235 | |||
236 | lines = python.splitlines() |
|
236 | lines = python.splitlines() | |
237 |
|
237 | |||
238 | # Create a list of atomic commands. |
|
238 | # Create a list of atomic commands. | |
239 | cmds = [] |
|
239 | cmds = [] | |
240 | for i, j in zip(linenos[:-1], linenos[1:]): |
|
240 | for i, j in zip(linenos[:-1], linenos[1:]): | |
241 | cmd = lines[i:j] |
|
241 | cmd = lines[i:j] | |
242 | if cmd: |
|
242 | if cmd: | |
243 | cmds.append('\n'.join(cmd)+'\n') |
|
243 | cmds.append('\n'.join(cmd)+'\n') | |
244 |
|
244 | |||
245 | return cmds |
|
245 | return cmds | |
246 |
|
246 | |||
247 |
|
247 | |||
248 | class InputSplitter(object): |
|
248 | class InputSplitter(object): | |
249 | """An object that can split Python source input in executable blocks. |
|
249 | """An object that can split Python source input in executable blocks. | |
250 |
|
250 | |||
251 | This object is designed to be used in one of two basic modes: |
|
251 | This object is designed to be used in one of two basic modes: | |
252 |
|
252 | |||
253 | 1. By feeding it python source line-by-line, using :meth:`push`. In this |
|
253 | 1. By feeding it python source line-by-line, using :meth:`push`. In this | |
254 | mode, it will return on each push whether the currently pushed code |
|
254 | mode, it will return on each push whether the currently pushed code | |
255 | could be executed already. In addition, it provides a method called |
|
255 | could be executed already. In addition, it provides a method called | |
256 | :meth:`push_accepts_more` that can be used to query whether more input |
|
256 | :meth:`push_accepts_more` that can be used to query whether more input | |
257 | can be pushed into a single interactive block. |
|
257 | can be pushed into a single interactive block. | |
258 |
|
258 | |||
259 | 2. By calling :meth:`split_blocks` with a single, multiline Python string, |
|
259 | 2. By calling :meth:`split_blocks` with a single, multiline Python string, | |
260 | that is then split into blocks each of which can be executed |
|
260 | that is then split into blocks each of which can be executed | |
261 | interactively as a single statement. |
|
261 | interactively as a single statement. | |
262 |
|
262 | |||
263 | This is a simple example of how an interactive terminal-based client can use |
|
263 | This is a simple example of how an interactive terminal-based client can use | |
264 | this tool:: |
|
264 | this tool:: | |
265 |
|
265 | |||
266 | isp = InputSplitter() |
|
266 | isp = InputSplitter() | |
267 | while isp.push_accepts_more(): |
|
267 | while isp.push_accepts_more(): | |
268 | indent = ' '*isp.indent_spaces |
|
268 | indent = ' '*isp.indent_spaces | |
269 | prompt = '>>> ' + indent |
|
269 | prompt = '>>> ' + indent | |
270 | line = indent + raw_input(prompt) |
|
270 | line = indent + raw_input(prompt) | |
271 | isp.push(line) |
|
271 | isp.push(line) | |
272 | print 'Input source was:\n', isp.source_reset(), |
|
272 | print 'Input source was:\n', isp.source_reset(), | |
273 | """ |
|
273 | """ | |
274 | # Number of spaces of indentation computed from input that has been pushed |
|
274 | # Number of spaces of indentation computed from input that has been pushed | |
275 | # so far. This is the attributes callers should query to get the current |
|
275 | # so far. This is the attributes callers should query to get the current | |
276 | # indentation level, in order to provide auto-indent facilities. |
|
276 | # indentation level, in order to provide auto-indent facilities. | |
277 | indent_spaces = 0 |
|
277 | indent_spaces = 0 | |
278 | # String, indicating the default input encoding. It is computed by default |
|
278 | # String, indicating the default input encoding. It is computed by default | |
279 | # at initialization time via get_input_encoding(), but it can be reset by a |
|
279 | # at initialization time via get_input_encoding(), but it can be reset by a | |
280 | # client with specific knowledge of the encoding. |
|
280 | # client with specific knowledge of the encoding. | |
281 | encoding = '' |
|
281 | encoding = '' | |
282 | # String where the current full source input is stored, properly encoded. |
|
282 | # String where the current full source input is stored, properly encoded. | |
283 | # Reading this attribute is the normal way of querying the currently pushed |
|
283 | # Reading this attribute is the normal way of querying the currently pushed | |
284 | # source code, that has been properly encoded. |
|
284 | # source code, that has been properly encoded. | |
285 | source = '' |
|
285 | source = '' | |
286 | # Code object corresponding to the current source. It is automatically |
|
286 | # Code object corresponding to the current source. It is automatically | |
287 | # synced to the source, so it can be queried at any time to obtain the code |
|
287 | # synced to the source, so it can be queried at any time to obtain the code | |
288 | # object; it will be None if the source doesn't compile to valid Python. |
|
288 | # object; it will be None if the source doesn't compile to valid Python. | |
289 | code = None |
|
289 | code = None | |
290 | # Input mode |
|
290 | # Input mode | |
291 | input_mode = 'line' |
|
291 | input_mode = 'line' | |
292 |
|
292 | |||
293 | # Private attributes |
|
293 | # Private attributes | |
294 |
|
294 | |||
295 | # List with lines of input accumulated so far |
|
295 | # List with lines of input accumulated so far | |
296 | _buffer = None |
|
296 | _buffer = None | |
297 | # Command compiler |
|
297 | # Command compiler | |
298 | _compile = None |
|
298 | _compile = None | |
299 | # Mark when input has changed indentation all the way back to flush-left |
|
299 | # Mark when input has changed indentation all the way back to flush-left | |
300 | _full_dedent = False |
|
300 | _full_dedent = False | |
301 | # Boolean indicating whether the current block is complete |
|
301 | # Boolean indicating whether the current block is complete | |
302 | _is_complete = None |
|
302 | _is_complete = None | |
303 |
|
303 | |||
304 | def __init__(self, input_mode=None): |
|
304 | def __init__(self, input_mode=None): | |
305 | """Create a new InputSplitter instance. |
|
305 | """Create a new InputSplitter instance. | |
306 |
|
306 | |||
307 | Parameters |
|
307 | Parameters | |
308 | ---------- |
|
308 | ---------- | |
309 | input_mode : str |
|
309 | input_mode : str | |
310 |
|
310 | |||
311 | One of ['line', 'block']; default is 'line'. |
|
311 | One of ['line', 'block']; default is 'line'. | |
312 |
|
312 | |||
313 | The input_mode parameter controls how new inputs are used when fed via |
|
313 | The input_mode parameter controls how new inputs are used when fed via | |
314 | the :meth:`push` method: |
|
314 | the :meth:`push` method: | |
315 |
|
315 | |||
316 | - 'line': meant for line-oriented clients, inputs are appended one at a |
|
316 | - 'line': meant for line-oriented clients, inputs are appended one at a | |
317 | time to the internal buffer and the whole buffer is compiled. |
|
317 | time to the internal buffer and the whole buffer is compiled. | |
318 |
|
318 | |||
319 | - 'block': meant for clients that can edit multi-line blocks of text at |
|
319 | - 'block': meant for clients that can edit multi-line blocks of text at | |
320 | a time. Each new input new input completely replaces all prior |
|
320 | a time. Each new input new input completely replaces all prior | |
321 | inputs. Block mode is thus equivalent to prepending a full reset() |
|
321 | inputs. Block mode is thus equivalent to prepending a full reset() | |
322 | to every push() call. |
|
322 | to every push() call. | |
323 | """ |
|
323 | """ | |
324 | self._buffer = [] |
|
324 | self._buffer = [] | |
325 | self._compile = codeop.CommandCompiler() |
|
325 | self._compile = codeop.CommandCompiler() | |
326 | self.encoding = get_input_encoding() |
|
326 | self.encoding = get_input_encoding() | |
327 | self.input_mode = InputSplitter.input_mode if input_mode is None \ |
|
327 | self.input_mode = InputSplitter.input_mode if input_mode is None \ | |
328 | else input_mode |
|
328 | else input_mode | |
329 |
|
329 | |||
330 | def reset(self): |
|
330 | def reset(self): | |
331 | """Reset the input buffer and associated state.""" |
|
331 | """Reset the input buffer and associated state.""" | |
332 | self.indent_spaces = 0 |
|
332 | self.indent_spaces = 0 | |
333 | self._buffer[:] = [] |
|
333 | self._buffer[:] = [] | |
334 | self.source = '' |
|
334 | self.source = '' | |
335 | self.code = None |
|
335 | self.code = None | |
336 | self._is_complete = False |
|
336 | self._is_complete = False | |
337 | self._full_dedent = False |
|
337 | self._full_dedent = False | |
338 |
|
338 | |||
339 | def source_reset(self): |
|
339 | def source_reset(self): | |
340 | """Return the input source and perform a full reset. |
|
340 | """Return the input source and perform a full reset. | |
341 | """ |
|
341 | """ | |
342 | out = self.source |
|
342 | out = self.source | |
343 | self.reset() |
|
343 | self.reset() | |
344 | return out |
|
344 | return out | |
345 |
|
345 | |||
346 | def push(self, lines): |
|
346 | def push(self, lines): | |
347 | """Push one ore more lines of input. |
|
347 | """Push one ore more lines of input. | |
348 |
|
348 | |||
349 | This stores the given lines and returns a status code indicating |
|
349 | This stores the given lines and returns a status code indicating | |
350 | whether the code forms a complete Python block or not. |
|
350 | whether the code forms a complete Python block or not. | |
351 |
|
351 | |||
352 | Any exceptions generated in compilation are swallowed, but if an |
|
352 | Any exceptions generated in compilation are swallowed, but if an | |
353 | exception was produced, the method returns True. |
|
353 | exception was produced, the method returns True. | |
354 |
|
354 | |||
355 | Parameters |
|
355 | Parameters | |
356 | ---------- |
|
356 | ---------- | |
357 | lines : string |
|
357 | lines : string | |
358 | One or more lines of Python input. |
|
358 | One or more lines of Python input. | |
359 |
|
359 | |||
360 | Returns |
|
360 | Returns | |
361 | ------- |
|
361 | ------- | |
362 | is_complete : boolean |
|
362 | is_complete : boolean | |
363 | True if the current input source (the result of the current input |
|
363 | True if the current input source (the result of the current input | |
364 | plus prior inputs) forms a complete Python execution block. Note that |
|
364 | plus prior inputs) forms a complete Python execution block. Note that | |
365 | this value is also stored as a private attribute (_is_complete), so it |
|
365 | this value is also stored as a private attribute (_is_complete), so it | |
366 | can be queried at any time. |
|
366 | can be queried at any time. | |
367 | """ |
|
367 | """ | |
368 | if self.input_mode == 'block': |
|
368 | if self.input_mode == 'block': | |
369 | self.reset() |
|
369 | self.reset() | |
370 |
|
370 | |||
371 | # If the source code has leading blanks, add 'if 1:\n' to it |
|
371 | # If the source code has leading blanks, add 'if 1:\n' to it | |
372 | # this allows execution of indented pasted code. It is tempting |
|
372 | # this allows execution of indented pasted code. It is tempting | |
373 | # to add '\n' at the end of source to run commands like ' a=1' |
|
373 | # to add '\n' at the end of source to run commands like ' a=1' | |
374 | # directly, but this fails for more complicated scenarios |
|
374 | # directly, but this fails for more complicated scenarios | |
375 |
|
375 | |||
376 | if not self._buffer and lines[:1] in [' ', '\t'] and \ |
|
376 | if not self._buffer and lines[:1] in [' ', '\t'] and \ | |
377 | not comment_line_re.match(lines): |
|
377 | not comment_line_re.match(lines): | |
378 | lines = 'if 1:\n%s' % lines |
|
378 | lines = 'if 1:\n%s' % lines | |
379 |
|
379 | |||
380 | self._store(lines) |
|
380 | self._store(lines) | |
381 | source = self.source |
|
381 | source = self.source | |
382 |
|
382 | |||
383 | # Before calling _compile(), reset the code object to None so that if an |
|
383 | # Before calling _compile(), reset the code object to None so that if an | |
384 | # exception is raised in compilation, we don't mislead by having |
|
384 | # exception is raised in compilation, we don't mislead by having | |
385 | # inconsistent code/source attributes. |
|
385 | # inconsistent code/source attributes. | |
386 | self.code, self._is_complete = None, None |
|
386 | self.code, self._is_complete = None, None | |
387 |
|
387 | |||
388 | self._update_indent(lines) |
|
388 | self._update_indent(lines) | |
389 | try: |
|
389 | try: | |
390 | self.code = self._compile(source) |
|
390 | self.code = self._compile(source) | |
391 | # Invalid syntax can produce any of a number of different errors from |
|
391 | # Invalid syntax can produce any of a number of different errors from | |
392 | # inside the compiler, so we have to catch them all. Syntax errors |
|
392 | # inside the compiler, so we have to catch them all. Syntax errors | |
393 | # immediately produce a 'ready' block, so the invalid Python can be |
|
393 | # immediately produce a 'ready' block, so the invalid Python can be | |
394 | # sent to the kernel for evaluation with possible ipython |
|
394 | # sent to the kernel for evaluation with possible ipython | |
395 | # special-syntax conversion. |
|
395 | # special-syntax conversion. | |
396 | except (SyntaxError, OverflowError, ValueError, TypeError, |
|
396 | except (SyntaxError, OverflowError, ValueError, TypeError, | |
397 | MemoryError): |
|
397 | MemoryError): | |
398 | self._is_complete = True |
|
398 | self._is_complete = True | |
399 | else: |
|
399 | else: | |
400 | # Compilation didn't produce any exceptions (though it may not have |
|
400 | # Compilation didn't produce any exceptions (though it may not have | |
401 | # given a complete code object) |
|
401 | # given a complete code object) | |
402 | self._is_complete = self.code is not None |
|
402 | self._is_complete = self.code is not None | |
403 |
|
403 | |||
404 | return self._is_complete |
|
404 | return self._is_complete | |
405 |
|
405 | |||
406 | def push_accepts_more(self): |
|
406 | def push_accepts_more(self): | |
407 | """Return whether a block of interactive input can accept more input. |
|
407 | """Return whether a block of interactive input can accept more input. | |
408 |
|
408 | |||
409 | This method is meant to be used by line-oriented frontends, who need to |
|
409 | This method is meant to be used by line-oriented frontends, who need to | |
410 | guess whether a block is complete or not based solely on prior and |
|
410 | guess whether a block is complete or not based solely on prior and | |
411 | current input lines. The InputSplitter considers it has a complete |
|
411 | current input lines. The InputSplitter considers it has a complete | |
412 | interactive block and will not accept more input only when either a |
|
412 | interactive block and will not accept more input only when either a | |
413 | SyntaxError is raised, or *all* of the following are true: |
|
413 | SyntaxError is raised, or *all* of the following are true: | |
414 |
|
414 | |||
415 | 1. The input compiles to a complete statement. |
|
415 | 1. The input compiles to a complete statement. | |
416 |
|
416 | |||
417 | 2. The indentation level is flush-left (because if we are indented, |
|
417 | 2. The indentation level is flush-left (because if we are indented, | |
418 | like inside a function definition or for loop, we need to keep |
|
418 | like inside a function definition or for loop, we need to keep | |
419 | reading new input). |
|
419 | reading new input). | |
420 |
|
420 | |||
421 | 3. There is one extra line consisting only of whitespace. |
|
421 | 3. There is one extra line consisting only of whitespace. | |
422 |
|
422 | |||
423 | Because of condition #3, this method should be used only by |
|
423 | Because of condition #3, this method should be used only by | |
424 | *line-oriented* frontends, since it means that intermediate blank lines |
|
424 | *line-oriented* frontends, since it means that intermediate blank lines | |
425 | are not allowed in function definitions (or any other indented block). |
|
425 | are not allowed in function definitions (or any other indented block). | |
426 |
|
426 | |||
427 | Block-oriented frontends that have a separate keyboard event to |
|
427 | Block-oriented frontends that have a separate keyboard event to | |
428 | indicate execution should use the :meth:`split_blocks` method instead. |
|
428 | indicate execution should use the :meth:`split_blocks` method instead. | |
429 |
|
429 | |||
430 | If the current input produces a syntax error, this method immediately |
|
430 | If the current input produces a syntax error, this method immediately | |
431 | returns False but does *not* raise the syntax error exception, as |
|
431 | returns False but does *not* raise the syntax error exception, as | |
432 | typically clients will want to send invalid syntax to an execution |
|
432 | typically clients will want to send invalid syntax to an execution | |
433 | backend which might convert the invalid syntax into valid Python via |
|
433 | backend which might convert the invalid syntax into valid Python via | |
434 | one of the dynamic IPython mechanisms. |
|
434 | one of the dynamic IPython mechanisms. | |
435 | """ |
|
435 | """ | |
436 |
|
436 | |||
437 | if not self._is_complete: |
|
437 | if not self._is_complete: | |
438 | return True |
|
438 | return True | |
439 |
|
439 | |||
440 | if self.indent_spaces==0: |
|
440 | if self.indent_spaces==0: | |
441 | return False |
|
441 | return False | |
442 |
|
442 | |||
443 | last_line = self.source.splitlines()[-1] |
|
443 | last_line = self.source.splitlines()[-1] | |
444 | return bool(last_line and not last_line.isspace()) |
|
444 | return bool(last_line and not last_line.isspace()) | |
445 |
|
445 | |||
446 | def split_blocks(self, lines): |
|
446 | def split_blocks(self, lines): | |
447 | """Split a multiline string into multiple input blocks. |
|
447 | """Split a multiline string into multiple input blocks. | |
448 |
|
448 | |||
449 | Note: this method starts by performing a full reset(). |
|
449 | Note: this method starts by performing a full reset(). | |
450 |
|
450 | |||
451 | Parameters |
|
451 | Parameters | |
452 | ---------- |
|
452 | ---------- | |
453 | lines : str |
|
453 | lines : str | |
454 | A possibly multiline string. |
|
454 | A possibly multiline string. | |
455 |
|
455 | |||
456 | Returns |
|
456 | Returns | |
457 | ------- |
|
457 | ------- | |
458 | blocks : list |
|
458 | blocks : list | |
459 | A list of strings, each possibly multiline. Each string corresponds |
|
459 | A list of strings, each possibly multiline. Each string corresponds | |
460 | to a single block that can be compiled in 'single' mode (unless it |
|
460 | to a single block that can be compiled in 'single' mode (unless it | |
461 | has a syntax error).""" |
|
461 | has a syntax error).""" | |
462 |
|
462 | |||
463 | # This code is fairly delicate. If you make any changes here, make |
|
463 | # This code is fairly delicate. If you make any changes here, make | |
464 | # absolutely sure that you do run the full test suite and ALL tests |
|
464 | # absolutely sure that you do run the full test suite and ALL tests | |
465 | # pass. |
|
465 | # pass. | |
466 |
|
466 | |||
467 | self.reset() |
|
467 | self.reset() | |
468 | blocks = [] |
|
468 | blocks = [] | |
469 |
|
469 | |||
470 | # Reversed copy so we can use pop() efficiently and consume the input |
|
470 | # Reversed copy so we can use pop() efficiently and consume the input | |
471 | # as a stack |
|
471 | # as a stack | |
472 | lines = lines.splitlines()[::-1] |
|
472 | lines = lines.splitlines()[::-1] | |
473 | # Outer loop over all input |
|
473 | # Outer loop over all input | |
474 | while lines: |
|
474 | while lines: | |
475 | #print 'Current lines:', lines # dbg |
|
475 | #print 'Current lines:', lines # dbg | |
476 | # Inner loop to build each block |
|
476 | # Inner loop to build each block | |
477 | while True: |
|
477 | while True: | |
478 | # Safety exit from inner loop |
|
478 | # Safety exit from inner loop | |
479 | if not lines: |
|
479 | if not lines: | |
480 | break |
|
480 | break | |
481 | # Grab next line but don't push it yet |
|
481 | # Grab next line but don't push it yet | |
482 | next_line = lines.pop() |
|
482 | next_line = lines.pop() | |
483 | # Blank/empty lines are pushed as-is |
|
483 | # Blank/empty lines are pushed as-is | |
484 | if not next_line or next_line.isspace(): |
|
484 | if not next_line or next_line.isspace(): | |
485 | self.push(next_line) |
|
485 | self.push(next_line) | |
486 | continue |
|
486 | continue | |
487 |
|
487 | |||
488 | # Check indentation changes caused by the *next* line |
|
488 | # Check indentation changes caused by the *next* line | |
489 | indent_spaces, _full_dedent = self._find_indent(next_line) |
|
489 | indent_spaces, _full_dedent = self._find_indent(next_line) | |
490 |
|
490 | |||
491 | # If the next line causes a dedent, it can be for two differnt |
|
491 | # If the next line causes a dedent, it can be for two differnt | |
492 | # reasons: either an explicit de-dent by the user or a |
|
492 | # reasons: either an explicit de-dent by the user or a | |
493 | # return/raise/pass statement. These MUST be handled |
|
493 | # return/raise/pass statement. These MUST be handled | |
494 | # separately: |
|
494 | # separately: | |
495 | # |
|
495 | # | |
496 | # 1. the first case is only detected when the actual explicit |
|
496 | # 1. the first case is only detected when the actual explicit | |
497 | # dedent happens, and that would be the *first* line of a *new* |
|
497 | # dedent happens, and that would be the *first* line of a *new* | |
498 | # block. Thus, we must put the line back into the input buffer |
|
498 | # block. Thus, we must put the line back into the input buffer | |
499 | # so that it starts a new block on the next pass. |
|
499 | # so that it starts a new block on the next pass. | |
500 | # |
|
500 | # | |
501 | # 2. the second case is detected in the line before the actual |
|
501 | # 2. the second case is detected in the line before the actual | |
502 | # dedent happens, so , we consume the line and we can break out |
|
502 | # dedent happens, so , we consume the line and we can break out | |
503 | # to start a new block. |
|
503 | # to start a new block. | |
504 |
|
504 | |||
505 | # Case 1, explicit dedent causes a break. |
|
505 | # Case 1, explicit dedent causes a break. | |
506 | # Note: check that we weren't on the very last line, else we'll |
|
506 | # Note: check that we weren't on the very last line, else we'll | |
507 | # enter an infinite loop adding/removing the last line. |
|
507 | # enter an infinite loop adding/removing the last line. | |
508 | if _full_dedent and lines and not next_line.startswith(' '): |
|
508 | if _full_dedent and lines and not next_line.startswith(' '): | |
509 | lines.append(next_line) |
|
509 | lines.append(next_line) | |
510 | break |
|
510 | break | |
511 |
|
511 | |||
512 | # Otherwise any line is pushed |
|
512 | # Otherwise any line is pushed | |
513 | self.push(next_line) |
|
513 | self.push(next_line) | |
514 |
|
514 | |||
515 | # Case 2, full dedent with full block ready: |
|
515 | # Case 2, full dedent with full block ready: | |
516 | if _full_dedent or \ |
|
516 | if _full_dedent or \ | |
517 | self.indent_spaces==0 and not self.push_accepts_more(): |
|
517 | self.indent_spaces==0 and not self.push_accepts_more(): | |
518 | break |
|
518 | break | |
519 | # Form the new block with the current source input |
|
519 | # Form the new block with the current source input | |
520 | blocks.append(self.source_reset()) |
|
520 | blocks.append(self.source_reset()) | |
521 |
|
521 | |||
522 | #return blocks |
|
522 | #return blocks | |
523 | # HACK!!! Now that our input is in blocks but guaranteed to be pure |
|
523 | # HACK!!! Now that our input is in blocks but guaranteed to be pure | |
524 | # python syntax, feed it back a second time through the AST-based |
|
524 | # python syntax, feed it back a second time through the AST-based | |
525 | # splitter, which is more accurate than ours. |
|
525 | # splitter, which is more accurate than ours. | |
526 | return split_blocks(''.join(blocks)) |
|
526 | return split_blocks(''.join(blocks)) | |
527 |
|
527 | |||
528 | #------------------------------------------------------------------------ |
|
528 | #------------------------------------------------------------------------ | |
529 | # Private interface |
|
529 | # Private interface | |
530 | #------------------------------------------------------------------------ |
|
530 | #------------------------------------------------------------------------ | |
531 |
|
531 | |||
532 | def _find_indent(self, line): |
|
532 | def _find_indent(self, line): | |
533 | """Compute the new indentation level for a single line. |
|
533 | """Compute the new indentation level for a single line. | |
534 |
|
534 | |||
535 | Parameters |
|
535 | Parameters | |
536 | ---------- |
|
536 | ---------- | |
537 | line : str |
|
537 | line : str | |
538 | A single new line of non-whitespace, non-comment Python input. |
|
538 | A single new line of non-whitespace, non-comment Python input. | |
539 |
|
539 | |||
540 | Returns |
|
540 | Returns | |
541 | ------- |
|
541 | ------- | |
542 | indent_spaces : int |
|
542 | indent_spaces : int | |
543 | New value for the indent level (it may be equal to self.indent_spaces |
|
543 | New value for the indent level (it may be equal to self.indent_spaces | |
544 | if indentation doesn't change. |
|
544 | if indentation doesn't change. | |
545 |
|
545 | |||
546 | full_dedent : boolean |
|
546 | full_dedent : boolean | |
547 | Whether the new line causes a full flush-left dedent. |
|
547 | Whether the new line causes a full flush-left dedent. | |
548 | """ |
|
548 | """ | |
549 | indent_spaces = self.indent_spaces |
|
549 | indent_spaces = self.indent_spaces | |
550 | full_dedent = self._full_dedent |
|
550 | full_dedent = self._full_dedent | |
551 |
|
551 | |||
552 | inisp = num_ini_spaces(line) |
|
552 | inisp = num_ini_spaces(line) | |
553 | if inisp < indent_spaces: |
|
553 | if inisp < indent_spaces: | |
554 | indent_spaces = inisp |
|
554 | indent_spaces = inisp | |
555 | if indent_spaces <= 0: |
|
555 | if indent_spaces <= 0: | |
556 | #print 'Full dedent in text',self.source # dbg |
|
556 | #print 'Full dedent in text',self.source # dbg | |
557 | full_dedent = True |
|
557 | full_dedent = True | |
558 |
|
558 | |||
559 | if line[-1] == ':': |
|
559 | if line[-1] == ':': | |
560 | indent_spaces += 4 |
|
560 | indent_spaces += 4 | |
561 | elif dedent_re.match(line): |
|
561 | elif dedent_re.match(line): | |
562 | indent_spaces -= 4 |
|
562 | indent_spaces -= 4 | |
563 | if indent_spaces <= 0: |
|
563 | if indent_spaces <= 0: | |
564 | full_dedent = True |
|
564 | full_dedent = True | |
565 |
|
565 | |||
566 | # Safety |
|
566 | # Safety | |
567 | if indent_spaces < 0: |
|
567 | if indent_spaces < 0: | |
568 | indent_spaces = 0 |
|
568 | indent_spaces = 0 | |
569 | #print 'safety' # dbg |
|
569 | #print 'safety' # dbg | |
570 |
|
570 | |||
571 | return indent_spaces, full_dedent |
|
571 | return indent_spaces, full_dedent | |
572 |
|
572 | |||
573 | def _update_indent(self, lines): |
|
573 | def _update_indent(self, lines): | |
574 | for line in remove_comments(lines).splitlines(): |
|
574 | for line in remove_comments(lines).splitlines(): | |
575 | if line and not line.isspace(): |
|
575 | if line and not line.isspace(): | |
576 | self.indent_spaces, self._full_dedent = self._find_indent(line) |
|
576 | self.indent_spaces, self._full_dedent = self._find_indent(line) | |
577 |
|
577 | |||
578 | def _store(self, lines): |
|
578 | def _store(self, lines): | |
579 | """Store one or more lines of input. |
|
579 | """Store one or more lines of input. | |
580 |
|
580 | |||
581 | If input lines are not newline-terminated, a newline is automatically |
|
581 | If input lines are not newline-terminated, a newline is automatically | |
582 | appended.""" |
|
582 | appended.""" | |
583 |
|
583 | |||
584 | if lines.endswith('\n'): |
|
584 | if lines.endswith('\n'): | |
585 | self._buffer.append(lines) |
|
585 | self._buffer.append(lines) | |
586 | else: |
|
586 | else: | |
587 | self._buffer.append(lines+'\n') |
|
587 | self._buffer.append(lines+'\n') | |
588 | self._set_source() |
|
588 | self._set_source() | |
589 |
|
589 | |||
590 | def _set_source(self): |
|
590 | def _set_source(self): | |
591 | self.source = ''.join(self._buffer).encode(self.encoding) |
|
591 | self.source = ''.join(self._buffer).encode(self.encoding) | |
592 |
|
592 | |||
593 |
|
593 | |||
594 | #----------------------------------------------------------------------------- |
|
594 | #----------------------------------------------------------------------------- | |
595 | # Functions and classes for IPython-specific syntactic support |
|
595 | # Functions and classes for IPython-specific syntactic support | |
596 | #----------------------------------------------------------------------------- |
|
596 | #----------------------------------------------------------------------------- | |
597 |
|
597 | |||
598 | # RegExp for splitting line contents into pre-char//first word-method//rest. |
|
598 | # RegExp for splitting line contents into pre-char//first word-method//rest. | |
599 | # For clarity, each group in on one line. |
|
599 | # For clarity, each group in on one line. | |
600 |
|
600 | |||
601 | line_split = re.compile(""" |
|
601 | line_split = re.compile(""" | |
602 | ^(\s*) # any leading space |
|
602 | ^(\s*) # any leading space | |
603 | ([,;/%]|!!?|\?\??) # escape character or characters |
|
603 | ([,;/%]|!!?|\?\??) # escape character or characters | |
604 | \s*(%?[\w\.]*) # function/method, possibly with leading % |
|
604 | \s*(%?[\w\.]*) # function/method, possibly with leading % | |
605 | # to correctly treat things like '?%magic' |
|
605 | # to correctly treat things like '?%magic' | |
606 | (\s+.*$|$) # rest of line |
|
606 | (\s+.*$|$) # rest of line | |
607 | """, re.VERBOSE) |
|
607 | """, re.VERBOSE) | |
608 |
|
608 | |||
609 |
|
609 | |||
610 | def split_user_input(line): |
|
610 | def split_user_input(line): | |
611 | """Split user input into early whitespace, esc-char, function part and rest. |
|
611 | """Split user input into early whitespace, esc-char, function part and rest. | |
612 |
|
612 | |||
613 | This is currently handles lines with '=' in them in a very inconsistent |
|
613 | This is currently handles lines with '=' in them in a very inconsistent | |
614 | manner. |
|
614 | manner. | |
615 |
|
615 | |||
616 | Examples |
|
616 | Examples | |
617 | ======== |
|
617 | ======== | |
618 | >>> split_user_input('x=1') |
|
618 | >>> split_user_input('x=1') | |
619 | ('', '', 'x=1', '') |
|
619 | ('', '', 'x=1', '') | |
620 | >>> split_user_input('?') |
|
620 | >>> split_user_input('?') | |
621 | ('', '?', '', '') |
|
621 | ('', '?', '', '') | |
622 | >>> split_user_input('??') |
|
622 | >>> split_user_input('??') | |
623 | ('', '??', '', '') |
|
623 | ('', '??', '', '') | |
624 | >>> split_user_input(' ?') |
|
624 | >>> split_user_input(' ?') | |
625 | (' ', '?', '', '') |
|
625 | (' ', '?', '', '') | |
626 | >>> split_user_input(' ??') |
|
626 | >>> split_user_input(' ??') | |
627 | (' ', '??', '', '') |
|
627 | (' ', '??', '', '') | |
628 | >>> split_user_input('??x') |
|
628 | >>> split_user_input('??x') | |
629 | ('', '??', 'x', '') |
|
629 | ('', '??', 'x', '') | |
630 | >>> split_user_input('?x=1') |
|
630 | >>> split_user_input('?x=1') | |
631 | ('', '', '?x=1', '') |
|
631 | ('', '', '?x=1', '') | |
632 | >>> split_user_input('!ls') |
|
632 | >>> split_user_input('!ls') | |
633 | ('', '!', 'ls', '') |
|
633 | ('', '!', 'ls', '') | |
634 | >>> split_user_input(' !ls') |
|
634 | >>> split_user_input(' !ls') | |
635 | (' ', '!', 'ls', '') |
|
635 | (' ', '!', 'ls', '') | |
636 | >>> split_user_input('!!ls') |
|
636 | >>> split_user_input('!!ls') | |
637 | ('', '!!', 'ls', '') |
|
637 | ('', '!!', 'ls', '') | |
638 | >>> split_user_input(' !!ls') |
|
638 | >>> split_user_input(' !!ls') | |
639 | (' ', '!!', 'ls', '') |
|
639 | (' ', '!!', 'ls', '') | |
640 | >>> split_user_input(',ls') |
|
640 | >>> split_user_input(',ls') | |
641 | ('', ',', 'ls', '') |
|
641 | ('', ',', 'ls', '') | |
642 | >>> split_user_input(';ls') |
|
642 | >>> split_user_input(';ls') | |
643 | ('', ';', 'ls', '') |
|
643 | ('', ';', 'ls', '') | |
644 | >>> split_user_input(' ;ls') |
|
644 | >>> split_user_input(' ;ls') | |
645 | (' ', ';', 'ls', '') |
|
645 | (' ', ';', 'ls', '') | |
646 | >>> split_user_input('f.g(x)') |
|
646 | >>> split_user_input('f.g(x)') | |
647 | ('', '', 'f.g(x)', '') |
|
647 | ('', '', 'f.g(x)', '') | |
648 | >>> split_user_input('f.g (x)') |
|
648 | >>> split_user_input('f.g (x)') | |
649 | ('', '', 'f.g', '(x)') |
|
649 | ('', '', 'f.g', '(x)') | |
650 | >>> split_user_input('?%hist') |
|
650 | >>> split_user_input('?%hist') | |
651 | ('', '?', '%hist', '') |
|
651 | ('', '?', '%hist', '') | |
652 | """ |
|
652 | """ | |
653 | match = line_split.match(line) |
|
653 | match = line_split.match(line) | |
654 | if match: |
|
654 | if match: | |
655 | lspace, esc, fpart, rest = match.groups() |
|
655 | lspace, esc, fpart, rest = match.groups() | |
656 | else: |
|
656 | else: | |
657 | # print "match failed for line '%s'" % line |
|
657 | # print "match failed for line '%s'" % line | |
658 | try: |
|
658 | try: | |
659 | fpart, rest = line.split(None, 1) |
|
659 | fpart, rest = line.split(None, 1) | |
660 | except ValueError: |
|
660 | except ValueError: | |
661 | # print "split failed for line '%s'" % line |
|
661 | # print "split failed for line '%s'" % line | |
662 | fpart, rest = line,'' |
|
662 | fpart, rest = line,'' | |
663 | lspace = re.match('^(\s*)(.*)', line).groups()[0] |
|
663 | lspace = re.match('^(\s*)(.*)', line).groups()[0] | |
664 | esc = '' |
|
664 | esc = '' | |
665 |
|
665 | |||
666 | # fpart has to be a valid python identifier, so it better be only pure |
|
666 | # fpart has to be a valid python identifier, so it better be only pure | |
667 | # ascii, no unicode: |
|
667 | # ascii, no unicode: | |
668 | try: |
|
668 | try: | |
669 | fpart = fpart.encode('ascii') |
|
669 | fpart = fpart.encode('ascii') | |
670 | except UnicodeEncodeError: |
|
670 | except UnicodeEncodeError: | |
671 | lspace = unicode(lspace) |
|
671 | lspace = unicode(lspace) | |
672 | rest = fpart + u' ' + rest |
|
672 | rest = fpart + u' ' + rest | |
673 | fpart = u'' |
|
673 | fpart = u'' | |
674 |
|
674 | |||
675 | #print 'line:<%s>' % line # dbg |
|
675 | #print 'line:<%s>' % line # dbg | |
676 | #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg |
|
676 | #print 'esc <%s> fpart <%s> rest <%s>' % (esc,fpart.strip(),rest) # dbg | |
677 | return lspace, esc, fpart.strip(), rest.lstrip() |
|
677 | return lspace, esc, fpart.strip(), rest.lstrip() | |
678 |
|
678 | |||
679 |
|
679 | |||
680 | # The escaped translators ALL receive a line where their own escape has been |
|
680 | # The escaped translators ALL receive a line where their own escape has been | |
681 | # stripped. Only '?' is valid at the end of the line, all others can only be |
|
681 | # stripped. Only '?' is valid at the end of the line, all others can only be | |
682 | # placed at the start. |
|
682 | # placed at the start. | |
683 |
|
683 | |||
684 | class LineInfo(object): |
|
684 | class LineInfo(object): | |
685 | """A single line of input and associated info. |
|
685 | """A single line of input and associated info. | |
686 |
|
686 | |||
687 | This is a utility class that mostly wraps the output of |
|
687 | This is a utility class that mostly wraps the output of | |
688 | :func:`split_user_input` into a convenient object to be passed around |
|
688 | :func:`split_user_input` into a convenient object to be passed around | |
689 | during input transformations. |
|
689 | during input transformations. | |
690 |
|
690 | |||
691 | Includes the following as properties: |
|
691 | Includes the following as properties: | |
692 |
|
692 | |||
693 | line |
|
693 | line | |
694 | The original, raw line |
|
694 | The original, raw line | |
695 |
|
695 | |||
696 | lspace |
|
696 | lspace | |
697 | Any early whitespace before actual text starts. |
|
697 | Any early whitespace before actual text starts. | |
698 |
|
698 | |||
699 | esc |
|
699 | esc | |
700 | The initial esc character (or characters, for double-char escapes like |
|
700 | The initial esc character (or characters, for double-char escapes like | |
701 | '??' or '!!'). |
|
701 | '??' or '!!'). | |
702 |
|
702 | |||
703 | fpart |
|
703 | fpart | |
704 | The 'function part', which is basically the maximal initial sequence |
|
704 | The 'function part', which is basically the maximal initial sequence | |
705 | of valid python identifiers and the '.' character. This is what is |
|
705 | of valid python identifiers and the '.' character. This is what is | |
706 | checked for alias and magic transformations, used for auto-calling, |
|
706 | checked for alias and magic transformations, used for auto-calling, | |
707 | etc. |
|
707 | etc. | |
708 |
|
708 | |||
709 | rest |
|
709 | rest | |
710 | Everything else on the line. |
|
710 | Everything else on the line. | |
711 | """ |
|
711 | """ | |
712 | def __init__(self, line): |
|
712 | def __init__(self, line): | |
713 | self.line = line |
|
713 | self.line = line | |
714 | self.lspace, self.esc, self.fpart, self.rest = \ |
|
714 | self.lspace, self.esc, self.fpart, self.rest = \ | |
715 | split_user_input(line) |
|
715 | split_user_input(line) | |
716 |
|
716 | |||
717 | def __str__(self): |
|
717 | def __str__(self): | |
718 | return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc, |
|
718 | return "LineInfo [%s|%s|%s|%s]" % (self.lspace, self.esc, | |
719 | self.fpart, self.rest) |
|
719 | self.fpart, self.rest) | |
720 |
|
720 | |||
721 |
|
721 | |||
722 | # Transformations of the special syntaxes that don't rely on an explicit escape |
|
722 | # Transformations of the special syntaxes that don't rely on an explicit escape | |
723 | # character but instead on patterns on the input line |
|
723 | # character but instead on patterns on the input line | |
724 |
|
724 | |||
725 | # The core transformations are implemented as standalone functions that can be |
|
725 | # The core transformations are implemented as standalone functions that can be | |
726 | # tested and validated in isolation. Each of these uses a regexp, we |
|
726 | # tested and validated in isolation. Each of these uses a regexp, we | |
727 | # pre-compile these and keep them close to each function definition for clarity |
|
727 | # pre-compile these and keep them close to each function definition for clarity | |
728 |
|
728 | |||
729 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
729 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
730 | r'\s*=\s*!\s*(?P<cmd>.*)') |
|
730 | r'\s*=\s*!\s*(?P<cmd>.*)') | |
731 |
|
731 | |||
732 | def transform_assign_system(line): |
|
732 | def transform_assign_system(line): | |
733 | """Handle the `files = !ls` syntax.""" |
|
733 | """Handle the `files = !ls` syntax.""" | |
734 | # FIXME: This transforms the line to use %sc, but we've listed that magic |
|
|||
735 | # as deprecated. We should then implement this functionality in a |
|
|||
736 | # standalone api that we can transform to, without going through a |
|
|||
737 | # deprecated magic. |
|
|||
738 | m = _assign_system_re.match(line) |
|
734 | m = _assign_system_re.match(line) | |
739 | if m is not None: |
|
735 | if m is not None: | |
740 | cmd = m.group('cmd') |
|
736 | cmd = m.group('cmd') | |
741 | lhs = m.group('lhs') |
|
737 | lhs = m.group('lhs') | |
742 |
expr = make_quoted_expr( |
|
738 | expr = make_quoted_expr(cmd) | |
743 |
new_line = '%s = get_ipython(). |
|
739 | new_line = '%s = get_ipython().getoutput(%s)' % (lhs, expr) | |
744 | return new_line |
|
740 | return new_line | |
745 | return line |
|
741 | return line | |
746 |
|
742 | |||
747 |
|
743 | |||
748 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
744 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
749 | r'\s*=\s*%\s*(?P<cmd>.*)') |
|
745 | r'\s*=\s*%\s*(?P<cmd>.*)') | |
750 |
|
746 | |||
751 | def transform_assign_magic(line): |
|
747 | def transform_assign_magic(line): | |
752 | """Handle the `a = %who` syntax.""" |
|
748 | """Handle the `a = %who` syntax.""" | |
753 | m = _assign_magic_re.match(line) |
|
749 | m = _assign_magic_re.match(line) | |
754 | if m is not None: |
|
750 | if m is not None: | |
755 | cmd = m.group('cmd') |
|
751 | cmd = m.group('cmd') | |
756 | lhs = m.group('lhs') |
|
752 | lhs = m.group('lhs') | |
757 | expr = make_quoted_expr(cmd) |
|
753 | expr = make_quoted_expr(cmd) | |
758 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) |
|
754 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) | |
759 | return new_line |
|
755 | return new_line | |
760 | return line |
|
756 | return line | |
761 |
|
757 | |||
762 |
|
758 | |||
763 | _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )') |
|
759 | _classic_prompt_re = re.compile(r'^([ \t]*>>> |^[ \t]*\.\.\. )') | |
764 |
|
760 | |||
765 | def transform_classic_prompt(line): |
|
761 | def transform_classic_prompt(line): | |
766 | """Handle inputs that start with '>>> ' syntax.""" |
|
762 | """Handle inputs that start with '>>> ' syntax.""" | |
767 |
|
763 | |||
768 | if not line or line.isspace(): |
|
764 | if not line or line.isspace(): | |
769 | return line |
|
765 | return line | |
770 | m = _classic_prompt_re.match(line) |
|
766 | m = _classic_prompt_re.match(line) | |
771 | if m: |
|
767 | if m: | |
772 | return line[len(m.group(0)):] |
|
768 | return line[len(m.group(0)):] | |
773 | else: |
|
769 | else: | |
774 | return line |
|
770 | return line | |
775 |
|
771 | |||
776 |
|
772 | |||
777 | _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') |
|
773 | _ipy_prompt_re = re.compile(r'^([ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') | |
778 |
|
774 | |||
779 | def transform_ipy_prompt(line): |
|
775 | def transform_ipy_prompt(line): | |
780 | """Handle inputs that start classic IPython prompt syntax.""" |
|
776 | """Handle inputs that start classic IPython prompt syntax.""" | |
781 |
|
777 | |||
782 | if not line or line.isspace(): |
|
778 | if not line or line.isspace(): | |
783 | return line |
|
779 | return line | |
784 | #print 'LINE: %r' % line # dbg |
|
780 | #print 'LINE: %r' % line # dbg | |
785 | m = _ipy_prompt_re.match(line) |
|
781 | m = _ipy_prompt_re.match(line) | |
786 | if m: |
|
782 | if m: | |
787 | #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg |
|
783 | #print 'MATCH! %r -> %r' % (line, line[len(m.group(0)):]) # dbg | |
788 | return line[len(m.group(0)):] |
|
784 | return line[len(m.group(0)):] | |
789 | else: |
|
785 | else: | |
790 | return line |
|
786 | return line | |
791 |
|
787 | |||
792 |
|
788 | |||
793 | class EscapedTransformer(object): |
|
789 | class EscapedTransformer(object): | |
794 | """Class to transform lines that are explicitly escaped out.""" |
|
790 | """Class to transform lines that are explicitly escaped out.""" | |
795 |
|
791 | |||
796 | def __init__(self): |
|
792 | def __init__(self): | |
797 | tr = { ESC_SHELL : self._tr_system, |
|
793 | tr = { ESC_SHELL : self._tr_system, | |
798 | ESC_SH_CAP : self._tr_system2, |
|
794 | ESC_SH_CAP : self._tr_system2, | |
799 | ESC_HELP : self._tr_help, |
|
795 | ESC_HELP : self._tr_help, | |
800 | ESC_HELP2 : self._tr_help, |
|
796 | ESC_HELP2 : self._tr_help, | |
801 | ESC_MAGIC : self._tr_magic, |
|
797 | ESC_MAGIC : self._tr_magic, | |
802 | ESC_QUOTE : self._tr_quote, |
|
798 | ESC_QUOTE : self._tr_quote, | |
803 | ESC_QUOTE2 : self._tr_quote2, |
|
799 | ESC_QUOTE2 : self._tr_quote2, | |
804 | ESC_PAREN : self._tr_paren } |
|
800 | ESC_PAREN : self._tr_paren } | |
805 | self.tr = tr |
|
801 | self.tr = tr | |
806 |
|
802 | |||
807 | # Support for syntax transformations that use explicit escapes typed by the |
|
803 | # Support for syntax transformations that use explicit escapes typed by the | |
808 | # user at the beginning of a line |
|
804 | # user at the beginning of a line | |
809 | @staticmethod |
|
805 | @staticmethod | |
810 | def _tr_system(line_info): |
|
806 | def _tr_system(line_info): | |
811 | "Translate lines escaped with: !" |
|
807 | "Translate lines escaped with: !" | |
812 | cmd = line_info.line.lstrip().lstrip(ESC_SHELL) |
|
808 | cmd = line_info.line.lstrip().lstrip(ESC_SHELL) | |
813 | return '%sget_ipython().system(%s)' % (line_info.lspace, |
|
809 | return '%sget_ipython().system(%s)' % (line_info.lspace, | |
814 | make_quoted_expr(cmd)) |
|
810 | make_quoted_expr(cmd)) | |
815 |
|
811 | |||
816 | @staticmethod |
|
812 | @staticmethod | |
817 | def _tr_system2(line_info): |
|
813 | def _tr_system2(line_info): | |
818 | "Translate lines escaped with: !!" |
|
814 | "Translate lines escaped with: !!" | |
819 | cmd = line_info.line.lstrip()[2:] |
|
815 | cmd = line_info.line.lstrip()[2:] | |
820 | return '%sget_ipython().getoutput(%s)' % (line_info.lspace, |
|
816 | return '%sget_ipython().getoutput(%s)' % (line_info.lspace, | |
821 | make_quoted_expr(cmd)) |
|
817 | make_quoted_expr(cmd)) | |
822 |
|
818 | |||
823 | @staticmethod |
|
819 | @staticmethod | |
824 | def _tr_help(line_info): |
|
820 | def _tr_help(line_info): | |
825 | "Translate lines escaped with: ?/??" |
|
821 | "Translate lines escaped with: ?/??" | |
826 | # A naked help line should just fire the intro help screen |
|
822 | # A naked help line should just fire the intro help screen | |
827 | if not line_info.line[1:]: |
|
823 | if not line_info.line[1:]: | |
828 | return 'get_ipython().show_usage()' |
|
824 | return 'get_ipython().show_usage()' | |
829 |
|
825 | |||
830 | # There may be one or two '?' at the end, move them to the front so that |
|
826 | # There may be one or two '?' at the end, move them to the front so that | |
831 | # the rest of the logic can assume escapes are at the start |
|
827 | # the rest of the logic can assume escapes are at the start | |
832 | line = line_info.line |
|
828 | line = line_info.line | |
833 | if line.endswith('?'): |
|
829 | if line.endswith('?'): | |
834 | line = line[-1] + line[:-1] |
|
830 | line = line[-1] + line[:-1] | |
835 | if line.endswith('?'): |
|
831 | if line.endswith('?'): | |
836 | line = line[-1] + line[:-1] |
|
832 | line = line[-1] + line[:-1] | |
837 | line_info = LineInfo(line) |
|
833 | line_info = LineInfo(line) | |
838 |
|
834 | |||
839 | # From here on, simply choose which level of detail to get. |
|
835 | # From here on, simply choose which level of detail to get. | |
840 | if line_info.esc == '?': |
|
836 | if line_info.esc == '?': | |
841 | pinfo = 'pinfo' |
|
837 | pinfo = 'pinfo' | |
842 | elif line_info.esc == '??': |
|
838 | elif line_info.esc == '??': | |
843 | pinfo = 'pinfo2' |
|
839 | pinfo = 'pinfo2' | |
844 |
|
840 | |||
845 | tpl = '%sget_ipython().magic("%s %s")' |
|
841 | tpl = '%sget_ipython().magic("%s %s")' | |
846 | return tpl % (line_info.lspace, pinfo, |
|
842 | return tpl % (line_info.lspace, pinfo, | |
847 | ' '.join([line_info.fpart, line_info.rest]).strip()) |
|
843 | ' '.join([line_info.fpart, line_info.rest]).strip()) | |
848 |
|
844 | |||
849 | @staticmethod |
|
845 | @staticmethod | |
850 | def _tr_magic(line_info): |
|
846 | def _tr_magic(line_info): | |
851 | "Translate lines escaped with: %" |
|
847 | "Translate lines escaped with: %" | |
852 | tpl = '%sget_ipython().magic(%s)' |
|
848 | tpl = '%sget_ipython().magic(%s)' | |
853 | cmd = make_quoted_expr(' '.join([line_info.fpart, |
|
849 | cmd = make_quoted_expr(' '.join([line_info.fpart, | |
854 | line_info.rest]).strip()) |
|
850 | line_info.rest]).strip()) | |
855 | return tpl % (line_info.lspace, cmd) |
|
851 | return tpl % (line_info.lspace, cmd) | |
856 |
|
852 | |||
857 | @staticmethod |
|
853 | @staticmethod | |
858 | def _tr_quote(line_info): |
|
854 | def _tr_quote(line_info): | |
859 | "Translate lines escaped with: ," |
|
855 | "Translate lines escaped with: ," | |
860 | return '%s%s("%s")' % (line_info.lspace, line_info.fpart, |
|
856 | return '%s%s("%s")' % (line_info.lspace, line_info.fpart, | |
861 | '", "'.join(line_info.rest.split()) ) |
|
857 | '", "'.join(line_info.rest.split()) ) | |
862 |
|
858 | |||
863 | @staticmethod |
|
859 | @staticmethod | |
864 | def _tr_quote2(line_info): |
|
860 | def _tr_quote2(line_info): | |
865 | "Translate lines escaped with: ;" |
|
861 | "Translate lines escaped with: ;" | |
866 | return '%s%s("%s")' % (line_info.lspace, line_info.fpart, |
|
862 | return '%s%s("%s")' % (line_info.lspace, line_info.fpart, | |
867 | line_info.rest) |
|
863 | line_info.rest) | |
868 |
|
864 | |||
869 | @staticmethod |
|
865 | @staticmethod | |
870 | def _tr_paren(line_info): |
|
866 | def _tr_paren(line_info): | |
871 | "Translate lines escaped with: /" |
|
867 | "Translate lines escaped with: /" | |
872 | return '%s%s(%s)' % (line_info.lspace, line_info.fpart, |
|
868 | return '%s%s(%s)' % (line_info.lspace, line_info.fpart, | |
873 | ", ".join(line_info.rest.split())) |
|
869 | ", ".join(line_info.rest.split())) | |
874 |
|
870 | |||
875 | def __call__(self, line): |
|
871 | def __call__(self, line): | |
876 | """Class to transform lines that are explicitly escaped out. |
|
872 | """Class to transform lines that are explicitly escaped out. | |
877 |
|
873 | |||
878 | This calls the above _tr_* static methods for the actual line |
|
874 | This calls the above _tr_* static methods for the actual line | |
879 | translations.""" |
|
875 | translations.""" | |
880 |
|
876 | |||
881 | # Empty lines just get returned unmodified |
|
877 | # Empty lines just get returned unmodified | |
882 | if not line or line.isspace(): |
|
878 | if not line or line.isspace(): | |
883 | return line |
|
879 | return line | |
884 |
|
880 | |||
885 | # Get line endpoints, where the escapes can be |
|
881 | # Get line endpoints, where the escapes can be | |
886 | line_info = LineInfo(line) |
|
882 | line_info = LineInfo(line) | |
887 |
|
883 | |||
888 | # If the escape is not at the start, only '?' needs to be special-cased. |
|
884 | # If the escape is not at the start, only '?' needs to be special-cased. | |
889 | # All other escapes are only valid at the start |
|
885 | # All other escapes are only valid at the start | |
890 | if not line_info.esc in self.tr: |
|
886 | if not line_info.esc in self.tr: | |
891 | if line.endswith(ESC_HELP): |
|
887 | if line.endswith(ESC_HELP): | |
892 | return self._tr_help(line_info) |
|
888 | return self._tr_help(line_info) | |
893 | else: |
|
889 | else: | |
894 | # If we don't recognize the escape, don't modify the line |
|
890 | # If we don't recognize the escape, don't modify the line | |
895 | return line |
|
891 | return line | |
896 |
|
892 | |||
897 | return self.tr[line_info.esc](line_info) |
|
893 | return self.tr[line_info.esc](line_info) | |
898 |
|
894 | |||
899 |
|
895 | |||
900 | # A function-looking object to be used by the rest of the code. The purpose of |
|
896 | # A function-looking object to be used by the rest of the code. The purpose of | |
901 | # the class in this case is to organize related functionality, more than to |
|
897 | # the class in this case is to organize related functionality, more than to | |
902 | # manage state. |
|
898 | # manage state. | |
903 | transform_escaped = EscapedTransformer() |
|
899 | transform_escaped = EscapedTransformer() | |
904 |
|
900 | |||
905 |
|
901 | |||
906 | class IPythonInputSplitter(InputSplitter): |
|
902 | class IPythonInputSplitter(InputSplitter): | |
907 | """An input splitter that recognizes all of IPython's special syntax.""" |
|
903 | """An input splitter that recognizes all of IPython's special syntax.""" | |
908 |
|
904 | |||
909 | def push(self, lines): |
|
905 | def push(self, lines): | |
910 | """Push one or more lines of IPython input. |
|
906 | """Push one or more lines of IPython input. | |
911 | """ |
|
907 | """ | |
912 | if not lines: |
|
908 | if not lines: | |
913 | return super(IPythonInputSplitter, self).push(lines) |
|
909 | return super(IPythonInputSplitter, self).push(lines) | |
914 |
|
910 | |||
915 | lines_list = lines.splitlines() |
|
911 | lines_list = lines.splitlines() | |
916 |
|
912 | |||
917 | transforms = [transform_escaped, transform_assign_system, |
|
913 | transforms = [transform_escaped, transform_assign_system, | |
918 | transform_assign_magic, transform_ipy_prompt, |
|
914 | transform_assign_magic, transform_ipy_prompt, | |
919 | transform_classic_prompt] |
|
915 | transform_classic_prompt] | |
920 |
|
916 | |||
921 | # Transform logic |
|
917 | # Transform logic | |
922 | # |
|
918 | # | |
923 | # We only apply the line transformers to the input if we have either no |
|
919 | # We only apply the line transformers to the input if we have either no | |
924 | # input yet, or complete input, or if the last line of the buffer ends |
|
920 | # input yet, or complete input, or if the last line of the buffer ends | |
925 | # with ':' (opening an indented block). This prevents the accidental |
|
921 | # with ':' (opening an indented block). This prevents the accidental | |
926 | # transformation of escapes inside multiline expressions like |
|
922 | # transformation of escapes inside multiline expressions like | |
927 | # triple-quoted strings or parenthesized expressions. |
|
923 | # triple-quoted strings or parenthesized expressions. | |
928 | # |
|
924 | # | |
929 | # The last heuristic, while ugly, ensures that the first line of an |
|
925 | # The last heuristic, while ugly, ensures that the first line of an | |
930 | # indented block is correctly transformed. |
|
926 | # indented block is correctly transformed. | |
931 | # |
|
927 | # | |
932 | # FIXME: try to find a cleaner approach for this last bit. |
|
928 | # FIXME: try to find a cleaner approach for this last bit. | |
933 |
|
929 | |||
934 | # If we were in 'block' mode, since we're going to pump the parent |
|
930 | # If we were in 'block' mode, since we're going to pump the parent | |
935 | # class by hand line by line, we need to temporarily switch out to |
|
931 | # class by hand line by line, we need to temporarily switch out to | |
936 | # 'line' mode, do a single manual reset and then feed the lines one |
|
932 | # 'line' mode, do a single manual reset and then feed the lines one | |
937 | # by one. Note that this only matters if the input has more than one |
|
933 | # by one. Note that this only matters if the input has more than one | |
938 | # line. |
|
934 | # line. | |
939 | changed_input_mode = False |
|
935 | changed_input_mode = False | |
940 |
|
936 | |||
941 | if len(lines_list)>1 and self.input_mode == 'block': |
|
937 | if len(lines_list)>1 and self.input_mode == 'block': | |
942 | self.reset() |
|
938 | self.reset() | |
943 | changed_input_mode = True |
|
939 | changed_input_mode = True | |
944 | saved_input_mode = 'block' |
|
940 | saved_input_mode = 'block' | |
945 | self.input_mode = 'line' |
|
941 | self.input_mode = 'line' | |
946 |
|
942 | |||
947 | try: |
|
943 | try: | |
948 | push = super(IPythonInputSplitter, self).push |
|
944 | push = super(IPythonInputSplitter, self).push | |
949 | for line in lines_list: |
|
945 | for line in lines_list: | |
950 | if self._is_complete or not self._buffer or \ |
|
946 | if self._is_complete or not self._buffer or \ | |
951 | (self._buffer and self._buffer[-1].rstrip().endswith(':')): |
|
947 | (self._buffer and self._buffer[-1].rstrip().endswith(':')): | |
952 | for f in transforms: |
|
948 | for f in transforms: | |
953 | line = f(line) |
|
949 | line = f(line) | |
954 |
|
950 | |||
955 | out = push(line) |
|
951 | out = push(line) | |
956 | finally: |
|
952 | finally: | |
957 | if changed_input_mode: |
|
953 | if changed_input_mode: | |
958 | self.input_mode = saved_input_mode |
|
954 | self.input_mode = saved_input_mode | |
959 |
|
955 | |||
960 | return out |
|
956 | return out |
@@ -1,2497 +1,2523 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Main IPython class.""" |
|
2 | """Main IPython class.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2010 The IPython Development Team |
|
7 | # Copyright (C) 2008-2010 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 |
|
16 | |||
17 | from __future__ import with_statement |
|
17 | from __future__ import with_statement | |
18 | from __future__ import absolute_import |
|
18 | from __future__ import absolute_import | |
19 |
|
19 | |||
20 | import __builtin__ |
|
20 | import __builtin__ | |
21 | import __future__ |
|
21 | import __future__ | |
22 | import abc |
|
22 | import abc | |
23 | import atexit |
|
23 | import atexit | |
24 | import codeop |
|
24 | import codeop | |
25 | import exceptions |
|
25 | import exceptions | |
26 | import new |
|
26 | import new | |
27 | import os |
|
27 | import os | |
28 | import re |
|
28 | import re | |
29 | import string |
|
29 | import string | |
30 | import sys |
|
30 | import sys | |
31 | import tempfile |
|
31 | import tempfile | |
32 | from contextlib import nested |
|
32 | from contextlib import nested | |
33 |
|
33 | |||
34 | from IPython.config.configurable import Configurable |
|
34 | from IPython.config.configurable import Configurable | |
35 | from IPython.core import debugger, oinspect |
|
35 | from IPython.core import debugger, oinspect | |
36 | from IPython.core import history as ipcorehist |
|
36 | from IPython.core import history as ipcorehist | |
37 | from IPython.core import page |
|
37 | from IPython.core import page | |
38 | from IPython.core import prefilter |
|
38 | from IPython.core import prefilter | |
39 | from IPython.core import shadowns |
|
39 | from IPython.core import shadowns | |
40 | from IPython.core import ultratb |
|
40 | from IPython.core import ultratb | |
41 | from IPython.core.alias import AliasManager |
|
41 | from IPython.core.alias import AliasManager | |
42 | from IPython.core.builtin_trap import BuiltinTrap |
|
42 | from IPython.core.builtin_trap import BuiltinTrap | |
43 | from IPython.core.display_trap import DisplayTrap |
|
43 | from IPython.core.display_trap import DisplayTrap | |
44 | from IPython.core.displayhook import DisplayHook |
|
44 | from IPython.core.displayhook import DisplayHook | |
45 | from IPython.core.error import TryNext, UsageError |
|
45 | from IPython.core.error import TryNext, UsageError | |
46 | from IPython.core.extensions import ExtensionManager |
|
46 | from IPython.core.extensions import ExtensionManager | |
47 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict |
|
47 | from IPython.core.fakemodule import FakeModule, init_fakemod_dict | |
48 | from IPython.core.inputlist import InputList |
|
48 | from IPython.core.inputlist import InputList | |
49 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
49 | from IPython.core.inputsplitter import IPythonInputSplitter | |
50 | from IPython.core.logger import Logger |
|
50 | from IPython.core.logger import Logger | |
51 | from IPython.core.magic import Magic |
|
51 | from IPython.core.magic import Magic | |
52 | from IPython.core.payload import PayloadManager |
|
52 | from IPython.core.payload import PayloadManager | |
53 | from IPython.core.plugin import PluginManager |
|
53 | from IPython.core.plugin import PluginManager | |
54 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC |
|
54 | from IPython.core.prefilter import PrefilterManager, ESC_MAGIC | |
55 | from IPython.external.Itpl import ItplNS |
|
55 | from IPython.external.Itpl import ItplNS | |
56 | from IPython.utils import PyColorize |
|
56 | from IPython.utils import PyColorize | |
57 | from IPython.utils import io |
|
57 | from IPython.utils import io | |
58 | from IPython.utils import pickleshare |
|
58 | from IPython.utils import pickleshare | |
59 | from IPython.utils.doctestreload import doctest_reload |
|
59 | from IPython.utils.doctestreload import doctest_reload | |
60 | from IPython.utils.io import ask_yes_no, rprint |
|
60 | from IPython.utils.io import ask_yes_no, rprint | |
61 | from IPython.utils.ipstruct import Struct |
|
61 | from IPython.utils.ipstruct import Struct | |
62 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError |
|
62 | from IPython.utils.path import get_home_dir, get_ipython_dir, HomeDirError | |
63 | from IPython.utils.process import system, getoutput |
|
63 | from IPython.utils.process import system, getoutput | |
64 | from IPython.utils.strdispatch import StrDispatch |
|
64 | from IPython.utils.strdispatch import StrDispatch | |
65 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
65 | from IPython.utils.syspathcontext import prepended_to_syspath | |
66 | from IPython.utils.text import num_ini_spaces, format_screen |
|
66 | from IPython.utils.text import num_ini_spaces, format_screen, LSString, SList | |
67 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, |
|
67 | from IPython.utils.traitlets import (Int, Str, CBool, CaselessStrEnum, Enum, | |
68 | List, Unicode, Instance, Type) |
|
68 | List, Unicode, Instance, Type) | |
69 | from IPython.utils.warn import warn, error, fatal |
|
69 | from IPython.utils.warn import warn, error, fatal | |
70 | import IPython.core.hooks |
|
70 | import IPython.core.hooks | |
71 |
|
71 | |||
72 | #----------------------------------------------------------------------------- |
|
72 | #----------------------------------------------------------------------------- | |
73 | # Globals |
|
73 | # Globals | |
74 | #----------------------------------------------------------------------------- |
|
74 | #----------------------------------------------------------------------------- | |
75 |
|
75 | |||
76 | # compiled regexps for autoindent management |
|
76 | # compiled regexps for autoindent management | |
77 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
77 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
78 |
|
78 | |||
79 | #----------------------------------------------------------------------------- |
|
79 | #----------------------------------------------------------------------------- | |
80 | # Utilities |
|
80 | # Utilities | |
81 | #----------------------------------------------------------------------------- |
|
81 | #----------------------------------------------------------------------------- | |
82 |
|
82 | |||
83 | # store the builtin raw_input globally, and use this always, in case user code |
|
83 | # store the builtin raw_input globally, and use this always, in case user code | |
84 | # overwrites it (like wx.py.PyShell does) |
|
84 | # overwrites it (like wx.py.PyShell does) | |
85 | raw_input_original = raw_input |
|
85 | raw_input_original = raw_input | |
86 |
|
86 | |||
87 | def softspace(file, newvalue): |
|
87 | def softspace(file, newvalue): | |
88 | """Copied from code.py, to remove the dependency""" |
|
88 | """Copied from code.py, to remove the dependency""" | |
89 |
|
89 | |||
90 | oldvalue = 0 |
|
90 | oldvalue = 0 | |
91 | try: |
|
91 | try: | |
92 | oldvalue = file.softspace |
|
92 | oldvalue = file.softspace | |
93 | except AttributeError: |
|
93 | except AttributeError: | |
94 | pass |
|
94 | pass | |
95 | try: |
|
95 | try: | |
96 | file.softspace = newvalue |
|
96 | file.softspace = newvalue | |
97 | except (AttributeError, TypeError): |
|
97 | except (AttributeError, TypeError): | |
98 | # "attribute-less object" or "read-only attributes" |
|
98 | # "attribute-less object" or "read-only attributes" | |
99 | pass |
|
99 | pass | |
100 | return oldvalue |
|
100 | return oldvalue | |
101 |
|
101 | |||
102 |
|
102 | |||
103 | def no_op(*a, **kw): pass |
|
103 | def no_op(*a, **kw): pass | |
104 |
|
104 | |||
105 | class SpaceInInput(exceptions.Exception): pass |
|
105 | class SpaceInInput(exceptions.Exception): pass | |
106 |
|
106 | |||
107 | class Bunch: pass |
|
107 | class Bunch: pass | |
108 |
|
108 | |||
109 |
|
109 | |||
110 | def get_default_colors(): |
|
110 | def get_default_colors(): | |
111 | if sys.platform=='darwin': |
|
111 | if sys.platform=='darwin': | |
112 | return "LightBG" |
|
112 | return "LightBG" | |
113 | elif os.name=='nt': |
|
113 | elif os.name=='nt': | |
114 | return 'Linux' |
|
114 | return 'Linux' | |
115 | else: |
|
115 | else: | |
116 | return 'Linux' |
|
116 | return 'Linux' | |
117 |
|
117 | |||
118 |
|
118 | |||
119 | class SeparateStr(Str): |
|
119 | class SeparateStr(Str): | |
120 | """A Str subclass to validate separate_in, separate_out, etc. |
|
120 | """A Str subclass to validate separate_in, separate_out, etc. | |
121 |
|
121 | |||
122 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. |
|
122 | This is a Str based trait that converts '0'->'' and '\\n'->'\n'. | |
123 | """ |
|
123 | """ | |
124 |
|
124 | |||
125 | def validate(self, obj, value): |
|
125 | def validate(self, obj, value): | |
126 | if value == '0': value = '' |
|
126 | if value == '0': value = '' | |
127 | value = value.replace('\\n','\n') |
|
127 | value = value.replace('\\n','\n') | |
128 | return super(SeparateStr, self).validate(obj, value) |
|
128 | return super(SeparateStr, self).validate(obj, value) | |
129 |
|
129 | |||
130 | class MultipleInstanceError(Exception): |
|
130 | class MultipleInstanceError(Exception): | |
131 | pass |
|
131 | pass | |
132 |
|
132 | |||
133 |
|
133 | |||
134 | #----------------------------------------------------------------------------- |
|
134 | #----------------------------------------------------------------------------- | |
135 | # Main IPython class |
|
135 | # Main IPython class | |
136 | #----------------------------------------------------------------------------- |
|
136 | #----------------------------------------------------------------------------- | |
137 |
|
137 | |||
138 |
|
138 | |||
139 | class InteractiveShell(Configurable, Magic): |
|
139 | class InteractiveShell(Configurable, Magic): | |
140 | """An enhanced, interactive shell for Python.""" |
|
140 | """An enhanced, interactive shell for Python.""" | |
141 |
|
141 | |||
142 | _instance = None |
|
142 | _instance = None | |
143 | autocall = Enum((0,1,2), default_value=1, config=True) |
|
143 | autocall = Enum((0,1,2), default_value=1, config=True) | |
144 | # TODO: remove all autoindent logic and put into frontends. |
|
144 | # TODO: remove all autoindent logic and put into frontends. | |
145 | # We can't do this yet because even runlines uses the autoindent. |
|
145 | # We can't do this yet because even runlines uses the autoindent. | |
146 | autoindent = CBool(True, config=True) |
|
146 | autoindent = CBool(True, config=True) | |
147 | automagic = CBool(True, config=True) |
|
147 | automagic = CBool(True, config=True) | |
148 | cache_size = Int(1000, config=True) |
|
148 | cache_size = Int(1000, config=True) | |
149 | color_info = CBool(True, config=True) |
|
149 | color_info = CBool(True, config=True) | |
150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), |
|
150 | colors = CaselessStrEnum(('NoColor','LightBG','Linux'), | |
151 | default_value=get_default_colors(), config=True) |
|
151 | default_value=get_default_colors(), config=True) | |
152 | debug = CBool(False, config=True) |
|
152 | debug = CBool(False, config=True) | |
153 | deep_reload = CBool(False, config=True) |
|
153 | deep_reload = CBool(False, config=True) | |
154 | displayhook_class = Type(DisplayHook) |
|
154 | displayhook_class = Type(DisplayHook) | |
155 | exit_now = CBool(False) |
|
155 | exit_now = CBool(False) | |
156 | filename = Str("<ipython console>") |
|
156 | filename = Str("<ipython console>") | |
157 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ |
|
157 | ipython_dir= Unicode('', config=True) # Set to get_ipython_dir() in __init__ | |
158 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter') |
|
158 | input_splitter = Instance('IPython.core.inputsplitter.IPythonInputSplitter') | |
159 | logstart = CBool(False, config=True) |
|
159 | logstart = CBool(False, config=True) | |
160 | logfile = Str('', config=True) |
|
160 | logfile = Str('', config=True) | |
161 | logappend = Str('', config=True) |
|
161 | logappend = Str('', config=True) | |
162 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
162 | object_info_string_level = Enum((0,1,2), default_value=0, | |
163 | config=True) |
|
163 | config=True) | |
164 | pdb = CBool(False, config=True) |
|
164 | pdb = CBool(False, config=True) | |
165 |
|
165 | |||
166 | pprint = CBool(True, config=True) |
|
166 | pprint = CBool(True, config=True) | |
167 | profile = Str('', config=True) |
|
167 | profile = Str('', config=True) | |
168 | prompt_in1 = Str('In [\\#]: ', config=True) |
|
168 | prompt_in1 = Str('In [\\#]: ', config=True) | |
169 | prompt_in2 = Str(' .\\D.: ', config=True) |
|
169 | prompt_in2 = Str(' .\\D.: ', config=True) | |
170 | prompt_out = Str('Out[\\#]: ', config=True) |
|
170 | prompt_out = Str('Out[\\#]: ', config=True) | |
171 | prompts_pad_left = CBool(True, config=True) |
|
171 | prompts_pad_left = CBool(True, config=True) | |
172 | quiet = CBool(False, config=True) |
|
172 | quiet = CBool(False, config=True) | |
173 |
|
173 | |||
174 | # The readline stuff will eventually be moved to the terminal subclass |
|
174 | # The readline stuff will eventually be moved to the terminal subclass | |
175 | # but for now, we can't do that as readline is welded in everywhere. |
|
175 | # but for now, we can't do that as readline is welded in everywhere. | |
176 | readline_use = CBool(True, config=True) |
|
176 | readline_use = CBool(True, config=True) | |
177 | readline_merge_completions = CBool(True, config=True) |
|
177 | readline_merge_completions = CBool(True, config=True) | |
178 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) |
|
178 | readline_omit__names = Enum((0,1,2), default_value=0, config=True) | |
179 | readline_remove_delims = Str('-/~', config=True) |
|
179 | readline_remove_delims = Str('-/~', config=True) | |
180 | readline_parse_and_bind = List([ |
|
180 | readline_parse_and_bind = List([ | |
181 | 'tab: complete', |
|
181 | 'tab: complete', | |
182 | '"\C-l": clear-screen', |
|
182 | '"\C-l": clear-screen', | |
183 | 'set show-all-if-ambiguous on', |
|
183 | 'set show-all-if-ambiguous on', | |
184 | '"\C-o": tab-insert', |
|
184 | '"\C-o": tab-insert', | |
185 | '"\M-i": " "', |
|
185 | '"\M-i": " "', | |
186 | '"\M-o": "\d\d\d\d"', |
|
186 | '"\M-o": "\d\d\d\d"', | |
187 | '"\M-I": "\d\d\d\d"', |
|
187 | '"\M-I": "\d\d\d\d"', | |
188 | '"\C-r": reverse-search-history', |
|
188 | '"\C-r": reverse-search-history', | |
189 | '"\C-s": forward-search-history', |
|
189 | '"\C-s": forward-search-history', | |
190 | '"\C-p": history-search-backward', |
|
190 | '"\C-p": history-search-backward', | |
191 | '"\C-n": history-search-forward', |
|
191 | '"\C-n": history-search-forward', | |
192 | '"\e[A": history-search-backward', |
|
192 | '"\e[A": history-search-backward', | |
193 | '"\e[B": history-search-forward', |
|
193 | '"\e[B": history-search-forward', | |
194 | '"\C-k": kill-line', |
|
194 | '"\C-k": kill-line', | |
195 | '"\C-u": unix-line-discard', |
|
195 | '"\C-u": unix-line-discard', | |
196 | ], allow_none=False, config=True) |
|
196 | ], allow_none=False, config=True) | |
197 |
|
197 | |||
198 | # TODO: this part of prompt management should be moved to the frontends. |
|
198 | # TODO: this part of prompt management should be moved to the frontends. | |
199 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
199 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
200 | separate_in = SeparateStr('\n', config=True) |
|
200 | separate_in = SeparateStr('\n', config=True) | |
201 | separate_out = SeparateStr('', config=True) |
|
201 | separate_out = SeparateStr('', config=True) | |
202 | separate_out2 = SeparateStr('', config=True) |
|
202 | separate_out2 = SeparateStr('', config=True) | |
203 | wildcards_case_sensitive = CBool(True, config=True) |
|
203 | wildcards_case_sensitive = CBool(True, config=True) | |
204 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
204 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
205 | default_value='Context', config=True) |
|
205 | default_value='Context', config=True) | |
206 |
|
206 | |||
207 | # Subcomponents of InteractiveShell |
|
207 | # Subcomponents of InteractiveShell | |
208 | alias_manager = Instance('IPython.core.alias.AliasManager') |
|
208 | alias_manager = Instance('IPython.core.alias.AliasManager') | |
209 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
209 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
210 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') |
|
210 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap') | |
211 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') |
|
211 | display_trap = Instance('IPython.core.display_trap.DisplayTrap') | |
212 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') |
|
212 | extension_manager = Instance('IPython.core.extensions.ExtensionManager') | |
213 | plugin_manager = Instance('IPython.core.plugin.PluginManager') |
|
213 | plugin_manager = Instance('IPython.core.plugin.PluginManager') | |
214 | payload_manager = Instance('IPython.core.payload.PayloadManager') |
|
214 | payload_manager = Instance('IPython.core.payload.PayloadManager') | |
215 |
|
215 | |||
216 | # Private interface |
|
216 | # Private interface | |
217 | _post_execute = set() |
|
217 | _post_execute = set() | |
218 |
|
218 | |||
219 | def __init__(self, config=None, ipython_dir=None, |
|
219 | def __init__(self, config=None, ipython_dir=None, | |
220 | user_ns=None, user_global_ns=None, |
|
220 | user_ns=None, user_global_ns=None, | |
221 | custom_exceptions=((), None)): |
|
221 | custom_exceptions=((), None)): | |
222 |
|
222 | |||
223 | # This is where traits with a config_key argument are updated |
|
223 | # This is where traits with a config_key argument are updated | |
224 | # from the values on config. |
|
224 | # from the values on config. | |
225 | super(InteractiveShell, self).__init__(config=config) |
|
225 | super(InteractiveShell, self).__init__(config=config) | |
226 |
|
226 | |||
227 | # These are relatively independent and stateless |
|
227 | # These are relatively independent and stateless | |
228 | self.init_ipython_dir(ipython_dir) |
|
228 | self.init_ipython_dir(ipython_dir) | |
229 | self.init_instance_attrs() |
|
229 | self.init_instance_attrs() | |
230 |
|
230 | |||
231 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
231 | # Create namespaces (user_ns, user_global_ns, etc.) | |
232 | self.init_create_namespaces(user_ns, user_global_ns) |
|
232 | self.init_create_namespaces(user_ns, user_global_ns) | |
233 | # This has to be done after init_create_namespaces because it uses |
|
233 | # This has to be done after init_create_namespaces because it uses | |
234 | # something in self.user_ns, but before init_sys_modules, which |
|
234 | # something in self.user_ns, but before init_sys_modules, which | |
235 | # is the first thing to modify sys. |
|
235 | # is the first thing to modify sys. | |
236 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
236 | # TODO: When we override sys.stdout and sys.stderr before this class | |
237 | # is created, we are saving the overridden ones here. Not sure if this |
|
237 | # is created, we are saving the overridden ones here. Not sure if this | |
238 | # is what we want to do. |
|
238 | # is what we want to do. | |
239 | self.save_sys_module_state() |
|
239 | self.save_sys_module_state() | |
240 | self.init_sys_modules() |
|
240 | self.init_sys_modules() | |
241 |
|
241 | |||
242 | self.init_history() |
|
242 | self.init_history() | |
243 | self.init_encoding() |
|
243 | self.init_encoding() | |
244 | self.init_prefilter() |
|
244 | self.init_prefilter() | |
245 |
|
245 | |||
246 | Magic.__init__(self, self) |
|
246 | Magic.__init__(self, self) | |
247 |
|
247 | |||
248 | self.init_syntax_highlighting() |
|
248 | self.init_syntax_highlighting() | |
249 | self.init_hooks() |
|
249 | self.init_hooks() | |
250 | self.init_pushd_popd_magic() |
|
250 | self.init_pushd_popd_magic() | |
251 | # self.init_traceback_handlers use to be here, but we moved it below |
|
251 | # self.init_traceback_handlers use to be here, but we moved it below | |
252 | # because it and init_io have to come after init_readline. |
|
252 | # because it and init_io have to come after init_readline. | |
253 | self.init_user_ns() |
|
253 | self.init_user_ns() | |
254 | self.init_logger() |
|
254 | self.init_logger() | |
255 | self.init_alias() |
|
255 | self.init_alias() | |
256 | self.init_builtins() |
|
256 | self.init_builtins() | |
257 |
|
257 | |||
258 | # pre_config_initialization |
|
258 | # pre_config_initialization | |
259 | self.init_shadow_hist() |
|
259 | self.init_shadow_hist() | |
260 |
|
260 | |||
261 | # The next section should contain everything that was in ipmaker. |
|
261 | # The next section should contain everything that was in ipmaker. | |
262 | self.init_logstart() |
|
262 | self.init_logstart() | |
263 |
|
263 | |||
264 | # The following was in post_config_initialization |
|
264 | # The following was in post_config_initialization | |
265 | self.init_inspector() |
|
265 | self.init_inspector() | |
266 | # init_readline() must come before init_io(), because init_io uses |
|
266 | # init_readline() must come before init_io(), because init_io uses | |
267 | # readline related things. |
|
267 | # readline related things. | |
268 | self.init_readline() |
|
268 | self.init_readline() | |
269 | # init_completer must come after init_readline, because it needs to |
|
269 | # init_completer must come after init_readline, because it needs to | |
270 | # know whether readline is present or not system-wide to configure the |
|
270 | # know whether readline is present or not system-wide to configure the | |
271 | # completers, since the completion machinery can now operate |
|
271 | # completers, since the completion machinery can now operate | |
272 | # independently of readline (e.g. over the network) |
|
272 | # independently of readline (e.g. over the network) | |
273 | self.init_completer() |
|
273 | self.init_completer() | |
274 | # TODO: init_io() needs to happen before init_traceback handlers |
|
274 | # TODO: init_io() needs to happen before init_traceback handlers | |
275 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
275 | # because the traceback handlers hardcode the stdout/stderr streams. | |
276 | # This logic in in debugger.Pdb and should eventually be changed. |
|
276 | # This logic in in debugger.Pdb and should eventually be changed. | |
277 | self.init_io() |
|
277 | self.init_io() | |
278 | self.init_traceback_handlers(custom_exceptions) |
|
278 | self.init_traceback_handlers(custom_exceptions) | |
279 | self.init_prompts() |
|
279 | self.init_prompts() | |
280 | self.init_displayhook() |
|
280 | self.init_displayhook() | |
281 | self.init_reload_doctest() |
|
281 | self.init_reload_doctest() | |
282 | self.init_magics() |
|
282 | self.init_magics() | |
283 | self.init_pdb() |
|
283 | self.init_pdb() | |
284 | self.init_extension_manager() |
|
284 | self.init_extension_manager() | |
285 | self.init_plugin_manager() |
|
285 | self.init_plugin_manager() | |
286 | self.init_payload() |
|
286 | self.init_payload() | |
287 | self.hooks.late_startup_hook() |
|
287 | self.hooks.late_startup_hook() | |
288 | atexit.register(self.atexit_operations) |
|
288 | atexit.register(self.atexit_operations) | |
289 |
|
289 | |||
290 | @classmethod |
|
290 | @classmethod | |
291 | def instance(cls, *args, **kwargs): |
|
291 | def instance(cls, *args, **kwargs): | |
292 | """Returns a global InteractiveShell instance.""" |
|
292 | """Returns a global InteractiveShell instance.""" | |
293 | if cls._instance is None: |
|
293 | if cls._instance is None: | |
294 | inst = cls(*args, **kwargs) |
|
294 | inst = cls(*args, **kwargs) | |
295 | # Now make sure that the instance will also be returned by |
|
295 | # Now make sure that the instance will also be returned by | |
296 | # the subclasses instance attribute. |
|
296 | # the subclasses instance attribute. | |
297 | for subclass in cls.mro(): |
|
297 | for subclass in cls.mro(): | |
298 | if issubclass(cls, subclass) and \ |
|
298 | if issubclass(cls, subclass) and \ | |
299 | issubclass(subclass, InteractiveShell): |
|
299 | issubclass(subclass, InteractiveShell): | |
300 | subclass._instance = inst |
|
300 | subclass._instance = inst | |
301 | else: |
|
301 | else: | |
302 | break |
|
302 | break | |
303 | if isinstance(cls._instance, cls): |
|
303 | if isinstance(cls._instance, cls): | |
304 | return cls._instance |
|
304 | return cls._instance | |
305 | else: |
|
305 | else: | |
306 | raise MultipleInstanceError( |
|
306 | raise MultipleInstanceError( | |
307 | 'Multiple incompatible subclass instances of ' |
|
307 | 'Multiple incompatible subclass instances of ' | |
308 | 'InteractiveShell are being created.' |
|
308 | 'InteractiveShell are being created.' | |
309 | ) |
|
309 | ) | |
310 |
|
310 | |||
311 | @classmethod |
|
311 | @classmethod | |
312 | def initialized(cls): |
|
312 | def initialized(cls): | |
313 | return hasattr(cls, "_instance") |
|
313 | return hasattr(cls, "_instance") | |
314 |
|
314 | |||
315 | def get_ipython(self): |
|
315 | def get_ipython(self): | |
316 | """Return the currently running IPython instance.""" |
|
316 | """Return the currently running IPython instance.""" | |
317 | return self |
|
317 | return self | |
318 |
|
318 | |||
319 | #------------------------------------------------------------------------- |
|
319 | #------------------------------------------------------------------------- | |
320 | # Trait changed handlers |
|
320 | # Trait changed handlers | |
321 | #------------------------------------------------------------------------- |
|
321 | #------------------------------------------------------------------------- | |
322 |
|
322 | |||
323 | def _ipython_dir_changed(self, name, new): |
|
323 | def _ipython_dir_changed(self, name, new): | |
324 | if not os.path.isdir(new): |
|
324 | if not os.path.isdir(new): | |
325 | os.makedirs(new, mode = 0777) |
|
325 | os.makedirs(new, mode = 0777) | |
326 |
|
326 | |||
327 | def set_autoindent(self,value=None): |
|
327 | def set_autoindent(self,value=None): | |
328 | """Set the autoindent flag, checking for readline support. |
|
328 | """Set the autoindent flag, checking for readline support. | |
329 |
|
329 | |||
330 | If called with no arguments, it acts as a toggle.""" |
|
330 | If called with no arguments, it acts as a toggle.""" | |
331 |
|
331 | |||
332 | if not self.has_readline: |
|
332 | if not self.has_readline: | |
333 | if os.name == 'posix': |
|
333 | if os.name == 'posix': | |
334 | warn("The auto-indent feature requires the readline library") |
|
334 | warn("The auto-indent feature requires the readline library") | |
335 | self.autoindent = 0 |
|
335 | self.autoindent = 0 | |
336 | return |
|
336 | return | |
337 | if value is None: |
|
337 | if value is None: | |
338 | self.autoindent = not self.autoindent |
|
338 | self.autoindent = not self.autoindent | |
339 | else: |
|
339 | else: | |
340 | self.autoindent = value |
|
340 | self.autoindent = value | |
341 |
|
341 | |||
342 | #------------------------------------------------------------------------- |
|
342 | #------------------------------------------------------------------------- | |
343 | # init_* methods called by __init__ |
|
343 | # init_* methods called by __init__ | |
344 | #------------------------------------------------------------------------- |
|
344 | #------------------------------------------------------------------------- | |
345 |
|
345 | |||
346 | def init_ipython_dir(self, ipython_dir): |
|
346 | def init_ipython_dir(self, ipython_dir): | |
347 | if ipython_dir is not None: |
|
347 | if ipython_dir is not None: | |
348 | self.ipython_dir = ipython_dir |
|
348 | self.ipython_dir = ipython_dir | |
349 | self.config.Global.ipython_dir = self.ipython_dir |
|
349 | self.config.Global.ipython_dir = self.ipython_dir | |
350 | return |
|
350 | return | |
351 |
|
351 | |||
352 | if hasattr(self.config.Global, 'ipython_dir'): |
|
352 | if hasattr(self.config.Global, 'ipython_dir'): | |
353 | self.ipython_dir = self.config.Global.ipython_dir |
|
353 | self.ipython_dir = self.config.Global.ipython_dir | |
354 | else: |
|
354 | else: | |
355 | self.ipython_dir = get_ipython_dir() |
|
355 | self.ipython_dir = get_ipython_dir() | |
356 |
|
356 | |||
357 | # All children can just read this |
|
357 | # All children can just read this | |
358 | self.config.Global.ipython_dir = self.ipython_dir |
|
358 | self.config.Global.ipython_dir = self.ipython_dir | |
359 |
|
359 | |||
360 | def init_instance_attrs(self): |
|
360 | def init_instance_attrs(self): | |
361 | self.more = False |
|
361 | self.more = False | |
362 |
|
362 | |||
363 | # command compiler |
|
363 | # command compiler | |
364 | self.compile = codeop.CommandCompiler() |
|
364 | self.compile = codeop.CommandCompiler() | |
365 |
|
365 | |||
366 | # User input buffer |
|
366 | # User input buffer | |
367 | self.buffer = [] |
|
367 | self.buffer = [] | |
368 |
|
368 | |||
369 | # Make an empty namespace, which extension writers can rely on both |
|
369 | # Make an empty namespace, which extension writers can rely on both | |
370 | # existing and NEVER being used by ipython itself. This gives them a |
|
370 | # existing and NEVER being used by ipython itself. This gives them a | |
371 | # convenient location for storing additional information and state |
|
371 | # convenient location for storing additional information and state | |
372 | # their extensions may require, without fear of collisions with other |
|
372 | # their extensions may require, without fear of collisions with other | |
373 | # ipython names that may develop later. |
|
373 | # ipython names that may develop later. | |
374 | self.meta = Struct() |
|
374 | self.meta = Struct() | |
375 |
|
375 | |||
376 | # Object variable to store code object waiting execution. This is |
|
376 | # Object variable to store code object waiting execution. This is | |
377 | # used mainly by the multithreaded shells, but it can come in handy in |
|
377 | # used mainly by the multithreaded shells, but it can come in handy in | |
378 | # other situations. No need to use a Queue here, since it's a single |
|
378 | # other situations. No need to use a Queue here, since it's a single | |
379 | # item which gets cleared once run. |
|
379 | # item which gets cleared once run. | |
380 | self.code_to_run = None |
|
380 | self.code_to_run = None | |
381 |
|
381 | |||
382 | # Temporary files used for various purposes. Deleted at exit. |
|
382 | # Temporary files used for various purposes. Deleted at exit. | |
383 | self.tempfiles = [] |
|
383 | self.tempfiles = [] | |
384 |
|
384 | |||
385 | # Keep track of readline usage (later set by init_readline) |
|
385 | # Keep track of readline usage (later set by init_readline) | |
386 | self.has_readline = False |
|
386 | self.has_readline = False | |
387 |
|
387 | |||
388 | # keep track of where we started running (mainly for crash post-mortem) |
|
388 | # keep track of where we started running (mainly for crash post-mortem) | |
389 | # This is not being used anywhere currently. |
|
389 | # This is not being used anywhere currently. | |
390 | self.starting_dir = os.getcwd() |
|
390 | self.starting_dir = os.getcwd() | |
391 |
|
391 | |||
392 | # Indentation management |
|
392 | # Indentation management | |
393 | self.indent_current_nsp = 0 |
|
393 | self.indent_current_nsp = 0 | |
394 |
|
394 | |||
395 | # Input splitter, to split entire cells of input into either individual |
|
395 | # Input splitter, to split entire cells of input into either individual | |
396 | # interactive statements or whole blocks. |
|
396 | # interactive statements or whole blocks. | |
397 | self.input_splitter = IPythonInputSplitter() |
|
397 | self.input_splitter = IPythonInputSplitter() | |
398 |
|
398 | |||
399 | def init_encoding(self): |
|
399 | def init_encoding(self): | |
400 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
400 | # Get system encoding at startup time. Certain terminals (like Emacs | |
401 | # under Win32 have it set to None, and we need to have a known valid |
|
401 | # under Win32 have it set to None, and we need to have a known valid | |
402 | # encoding to use in the raw_input() method |
|
402 | # encoding to use in the raw_input() method | |
403 | try: |
|
403 | try: | |
404 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
404 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
405 | except AttributeError: |
|
405 | except AttributeError: | |
406 | self.stdin_encoding = 'ascii' |
|
406 | self.stdin_encoding = 'ascii' | |
407 |
|
407 | |||
408 | def init_syntax_highlighting(self): |
|
408 | def init_syntax_highlighting(self): | |
409 | # Python source parser/formatter for syntax highlighting |
|
409 | # Python source parser/formatter for syntax highlighting | |
410 | pyformat = PyColorize.Parser().format |
|
410 | pyformat = PyColorize.Parser().format | |
411 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) |
|
411 | self.pycolorize = lambda src: pyformat(src,'str',self.colors) | |
412 |
|
412 | |||
413 | def init_pushd_popd_magic(self): |
|
413 | def init_pushd_popd_magic(self): | |
414 | # for pushd/popd management |
|
414 | # for pushd/popd management | |
415 | try: |
|
415 | try: | |
416 | self.home_dir = get_home_dir() |
|
416 | self.home_dir = get_home_dir() | |
417 | except HomeDirError, msg: |
|
417 | except HomeDirError, msg: | |
418 | fatal(msg) |
|
418 | fatal(msg) | |
419 |
|
419 | |||
420 | self.dir_stack = [] |
|
420 | self.dir_stack = [] | |
421 |
|
421 | |||
422 | def init_logger(self): |
|
422 | def init_logger(self): | |
423 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') |
|
423 | self.logger = Logger(self, logfname='ipython_log.py', logmode='rotate') | |
424 | # local shortcut, this is used a LOT |
|
424 | # local shortcut, this is used a LOT | |
425 | self.log = self.logger.log |
|
425 | self.log = self.logger.log | |
426 |
|
426 | |||
427 | def init_logstart(self): |
|
427 | def init_logstart(self): | |
428 | if self.logappend: |
|
428 | if self.logappend: | |
429 | self.magic_logstart(self.logappend + ' append') |
|
429 | self.magic_logstart(self.logappend + ' append') | |
430 | elif self.logfile: |
|
430 | elif self.logfile: | |
431 | self.magic_logstart(self.logfile) |
|
431 | self.magic_logstart(self.logfile) | |
432 | elif self.logstart: |
|
432 | elif self.logstart: | |
433 | self.magic_logstart() |
|
433 | self.magic_logstart() | |
434 |
|
434 | |||
435 | def init_builtins(self): |
|
435 | def init_builtins(self): | |
436 | self.builtin_trap = BuiltinTrap(shell=self) |
|
436 | self.builtin_trap = BuiltinTrap(shell=self) | |
437 |
|
437 | |||
438 | def init_inspector(self): |
|
438 | def init_inspector(self): | |
439 | # Object inspector |
|
439 | # Object inspector | |
440 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
440 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
441 | PyColorize.ANSICodeColors, |
|
441 | PyColorize.ANSICodeColors, | |
442 | 'NoColor', |
|
442 | 'NoColor', | |
443 | self.object_info_string_level) |
|
443 | self.object_info_string_level) | |
444 |
|
444 | |||
445 | def init_io(self): |
|
445 | def init_io(self): | |
446 | # This will just use sys.stdout and sys.stderr. If you want to |
|
446 | # This will just use sys.stdout and sys.stderr. If you want to | |
447 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
447 | # override sys.stdout and sys.stderr themselves, you need to do that | |
448 | # *before* instantiating this class, because Term holds onto |
|
448 | # *before* instantiating this class, because Term holds onto | |
449 | # references to the underlying streams. |
|
449 | # references to the underlying streams. | |
450 | if sys.platform == 'win32' and self.has_readline: |
|
450 | if sys.platform == 'win32' and self.has_readline: | |
451 | Term = io.IOTerm(cout=self.readline._outputfile, |
|
451 | Term = io.IOTerm(cout=self.readline._outputfile, | |
452 | cerr=self.readline._outputfile) |
|
452 | cerr=self.readline._outputfile) | |
453 | else: |
|
453 | else: | |
454 | Term = io.IOTerm() |
|
454 | Term = io.IOTerm() | |
455 | io.Term = Term |
|
455 | io.Term = Term | |
456 |
|
456 | |||
457 | def init_prompts(self): |
|
457 | def init_prompts(self): | |
458 | # TODO: This is a pass for now because the prompts are managed inside |
|
458 | # TODO: This is a pass for now because the prompts are managed inside | |
459 | # the DisplayHook. Once there is a separate prompt manager, this |
|
459 | # the DisplayHook. Once there is a separate prompt manager, this | |
460 | # will initialize that object and all prompt related information. |
|
460 | # will initialize that object and all prompt related information. | |
461 | pass |
|
461 | pass | |
462 |
|
462 | |||
463 | def init_displayhook(self): |
|
463 | def init_displayhook(self): | |
464 | # Initialize displayhook, set in/out prompts and printing system |
|
464 | # Initialize displayhook, set in/out prompts and printing system | |
465 | self.displayhook = self.displayhook_class( |
|
465 | self.displayhook = self.displayhook_class( | |
466 | shell=self, |
|
466 | shell=self, | |
467 | cache_size=self.cache_size, |
|
467 | cache_size=self.cache_size, | |
468 | input_sep = self.separate_in, |
|
468 | input_sep = self.separate_in, | |
469 | output_sep = self.separate_out, |
|
469 | output_sep = self.separate_out, | |
470 | output_sep2 = self.separate_out2, |
|
470 | output_sep2 = self.separate_out2, | |
471 | ps1 = self.prompt_in1, |
|
471 | ps1 = self.prompt_in1, | |
472 | ps2 = self.prompt_in2, |
|
472 | ps2 = self.prompt_in2, | |
473 | ps_out = self.prompt_out, |
|
473 | ps_out = self.prompt_out, | |
474 | pad_left = self.prompts_pad_left |
|
474 | pad_left = self.prompts_pad_left | |
475 | ) |
|
475 | ) | |
476 | # This is a context manager that installs/revmoes the displayhook at |
|
476 | # This is a context manager that installs/revmoes the displayhook at | |
477 | # the appropriate time. |
|
477 | # the appropriate time. | |
478 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
478 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
479 |
|
479 | |||
480 | def init_reload_doctest(self): |
|
480 | def init_reload_doctest(self): | |
481 | # Do a proper resetting of doctest, including the necessary displayhook |
|
481 | # Do a proper resetting of doctest, including the necessary displayhook | |
482 | # monkeypatching |
|
482 | # monkeypatching | |
483 | try: |
|
483 | try: | |
484 | doctest_reload() |
|
484 | doctest_reload() | |
485 | except ImportError: |
|
485 | except ImportError: | |
486 | warn("doctest module does not exist.") |
|
486 | warn("doctest module does not exist.") | |
487 |
|
487 | |||
488 | #------------------------------------------------------------------------- |
|
488 | #------------------------------------------------------------------------- | |
489 | # Things related to injections into the sys module |
|
489 | # Things related to injections into the sys module | |
490 | #------------------------------------------------------------------------- |
|
490 | #------------------------------------------------------------------------- | |
491 |
|
491 | |||
492 | def save_sys_module_state(self): |
|
492 | def save_sys_module_state(self): | |
493 | """Save the state of hooks in the sys module. |
|
493 | """Save the state of hooks in the sys module. | |
494 |
|
494 | |||
495 | This has to be called after self.user_ns is created. |
|
495 | This has to be called after self.user_ns is created. | |
496 | """ |
|
496 | """ | |
497 | self._orig_sys_module_state = {} |
|
497 | self._orig_sys_module_state = {} | |
498 | self._orig_sys_module_state['stdin'] = sys.stdin |
|
498 | self._orig_sys_module_state['stdin'] = sys.stdin | |
499 | self._orig_sys_module_state['stdout'] = sys.stdout |
|
499 | self._orig_sys_module_state['stdout'] = sys.stdout | |
500 | self._orig_sys_module_state['stderr'] = sys.stderr |
|
500 | self._orig_sys_module_state['stderr'] = sys.stderr | |
501 | self._orig_sys_module_state['excepthook'] = sys.excepthook |
|
501 | self._orig_sys_module_state['excepthook'] = sys.excepthook | |
502 | try: |
|
502 | try: | |
503 | self._orig_sys_modules_main_name = self.user_ns['__name__'] |
|
503 | self._orig_sys_modules_main_name = self.user_ns['__name__'] | |
504 | except KeyError: |
|
504 | except KeyError: | |
505 | pass |
|
505 | pass | |
506 |
|
506 | |||
507 | def restore_sys_module_state(self): |
|
507 | def restore_sys_module_state(self): | |
508 | """Restore the state of the sys module.""" |
|
508 | """Restore the state of the sys module.""" | |
509 | try: |
|
509 | try: | |
510 | for k, v in self._orig_sys_module_state.items(): |
|
510 | for k, v in self._orig_sys_module_state.items(): | |
511 | setattr(sys, k, v) |
|
511 | setattr(sys, k, v) | |
512 | except AttributeError: |
|
512 | except AttributeError: | |
513 | pass |
|
513 | pass | |
514 | # Reset what what done in self.init_sys_modules |
|
514 | # Reset what what done in self.init_sys_modules | |
515 | try: |
|
515 | try: | |
516 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name |
|
516 | sys.modules[self.user_ns['__name__']] = self._orig_sys_modules_main_name | |
517 | except (AttributeError, KeyError): |
|
517 | except (AttributeError, KeyError): | |
518 | pass |
|
518 | pass | |
519 |
|
519 | |||
520 | #------------------------------------------------------------------------- |
|
520 | #------------------------------------------------------------------------- | |
521 | # Things related to hooks |
|
521 | # Things related to hooks | |
522 | #------------------------------------------------------------------------- |
|
522 | #------------------------------------------------------------------------- | |
523 |
|
523 | |||
524 | def init_hooks(self): |
|
524 | def init_hooks(self): | |
525 | # hooks holds pointers used for user-side customizations |
|
525 | # hooks holds pointers used for user-side customizations | |
526 | self.hooks = Struct() |
|
526 | self.hooks = Struct() | |
527 |
|
527 | |||
528 | self.strdispatchers = {} |
|
528 | self.strdispatchers = {} | |
529 |
|
529 | |||
530 | # Set all default hooks, defined in the IPython.hooks module. |
|
530 | # Set all default hooks, defined in the IPython.hooks module. | |
531 | hooks = IPython.core.hooks |
|
531 | hooks = IPython.core.hooks | |
532 | for hook_name in hooks.__all__: |
|
532 | for hook_name in hooks.__all__: | |
533 | # default hooks have priority 100, i.e. low; user hooks should have |
|
533 | # default hooks have priority 100, i.e. low; user hooks should have | |
534 | # 0-100 priority |
|
534 | # 0-100 priority | |
535 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) |
|
535 | self.set_hook(hook_name,getattr(hooks,hook_name), 100) | |
536 |
|
536 | |||
537 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): |
|
537 | def set_hook(self,name,hook, priority = 50, str_key = None, re_key = None): | |
538 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
538 | """set_hook(name,hook) -> sets an internal IPython hook. | |
539 |
|
539 | |||
540 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
540 | IPython exposes some of its internal API as user-modifiable hooks. By | |
541 | adding your function to one of these hooks, you can modify IPython's |
|
541 | adding your function to one of these hooks, you can modify IPython's | |
542 | behavior to call at runtime your own routines.""" |
|
542 | behavior to call at runtime your own routines.""" | |
543 |
|
543 | |||
544 | # At some point in the future, this should validate the hook before it |
|
544 | # At some point in the future, this should validate the hook before it | |
545 | # accepts it. Probably at least check that the hook takes the number |
|
545 | # accepts it. Probably at least check that the hook takes the number | |
546 | # of args it's supposed to. |
|
546 | # of args it's supposed to. | |
547 |
|
547 | |||
548 | f = new.instancemethod(hook,self,self.__class__) |
|
548 | f = new.instancemethod(hook,self,self.__class__) | |
549 |
|
549 | |||
550 | # check if the hook is for strdispatcher first |
|
550 | # check if the hook is for strdispatcher first | |
551 | if str_key is not None: |
|
551 | if str_key is not None: | |
552 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
552 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
553 | sdp.add_s(str_key, f, priority ) |
|
553 | sdp.add_s(str_key, f, priority ) | |
554 | self.strdispatchers[name] = sdp |
|
554 | self.strdispatchers[name] = sdp | |
555 | return |
|
555 | return | |
556 | if re_key is not None: |
|
556 | if re_key is not None: | |
557 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
557 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
558 | sdp.add_re(re.compile(re_key), f, priority ) |
|
558 | sdp.add_re(re.compile(re_key), f, priority ) | |
559 | self.strdispatchers[name] = sdp |
|
559 | self.strdispatchers[name] = sdp | |
560 | return |
|
560 | return | |
561 |
|
561 | |||
562 | dp = getattr(self.hooks, name, None) |
|
562 | dp = getattr(self.hooks, name, None) | |
563 | if name not in IPython.core.hooks.__all__: |
|
563 | if name not in IPython.core.hooks.__all__: | |
564 | print "Warning! Hook '%s' is not one of %s" % \ |
|
564 | print "Warning! Hook '%s' is not one of %s" % \ | |
565 | (name, IPython.core.hooks.__all__ ) |
|
565 | (name, IPython.core.hooks.__all__ ) | |
566 | if not dp: |
|
566 | if not dp: | |
567 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
567 | dp = IPython.core.hooks.CommandChainDispatcher() | |
568 |
|
568 | |||
569 | try: |
|
569 | try: | |
570 | dp.add(f,priority) |
|
570 | dp.add(f,priority) | |
571 | except AttributeError: |
|
571 | except AttributeError: | |
572 | # it was not commandchain, plain old func - replace |
|
572 | # it was not commandchain, plain old func - replace | |
573 | dp = f |
|
573 | dp = f | |
574 |
|
574 | |||
575 | setattr(self.hooks,name, dp) |
|
575 | setattr(self.hooks,name, dp) | |
576 |
|
576 | |||
577 | def register_post_execute(self, func): |
|
577 | def register_post_execute(self, func): | |
578 | """Register a function for calling after code execution. |
|
578 | """Register a function for calling after code execution. | |
579 | """ |
|
579 | """ | |
580 | if not callable(func): |
|
580 | if not callable(func): | |
581 | raise ValueError('argument %s must be callable' % func) |
|
581 | raise ValueError('argument %s must be callable' % func) | |
582 | self._post_execute.add(func) |
|
582 | self._post_execute.add(func) | |
583 |
|
583 | |||
584 | #------------------------------------------------------------------------- |
|
584 | #------------------------------------------------------------------------- | |
585 | # Things related to the "main" module |
|
585 | # Things related to the "main" module | |
586 | #------------------------------------------------------------------------- |
|
586 | #------------------------------------------------------------------------- | |
587 |
|
587 | |||
588 | def new_main_mod(self,ns=None): |
|
588 | def new_main_mod(self,ns=None): | |
589 | """Return a new 'main' module object for user code execution. |
|
589 | """Return a new 'main' module object for user code execution. | |
590 | """ |
|
590 | """ | |
591 | main_mod = self._user_main_module |
|
591 | main_mod = self._user_main_module | |
592 | init_fakemod_dict(main_mod,ns) |
|
592 | init_fakemod_dict(main_mod,ns) | |
593 | return main_mod |
|
593 | return main_mod | |
594 |
|
594 | |||
595 | def cache_main_mod(self,ns,fname): |
|
595 | def cache_main_mod(self,ns,fname): | |
596 | """Cache a main module's namespace. |
|
596 | """Cache a main module's namespace. | |
597 |
|
597 | |||
598 | When scripts are executed via %run, we must keep a reference to the |
|
598 | When scripts are executed via %run, we must keep a reference to the | |
599 | namespace of their __main__ module (a FakeModule instance) around so |
|
599 | namespace of their __main__ module (a FakeModule instance) around so | |
600 | that Python doesn't clear it, rendering objects defined therein |
|
600 | that Python doesn't clear it, rendering objects defined therein | |
601 | useless. |
|
601 | useless. | |
602 |
|
602 | |||
603 | This method keeps said reference in a private dict, keyed by the |
|
603 | This method keeps said reference in a private dict, keyed by the | |
604 | absolute path of the module object (which corresponds to the script |
|
604 | absolute path of the module object (which corresponds to the script | |
605 | path). This way, for multiple executions of the same script we only |
|
605 | path). This way, for multiple executions of the same script we only | |
606 | keep one copy of the namespace (the last one), thus preventing memory |
|
606 | keep one copy of the namespace (the last one), thus preventing memory | |
607 | leaks from old references while allowing the objects from the last |
|
607 | leaks from old references while allowing the objects from the last | |
608 | execution to be accessible. |
|
608 | execution to be accessible. | |
609 |
|
609 | |||
610 | Note: we can not allow the actual FakeModule instances to be deleted, |
|
610 | Note: we can not allow the actual FakeModule instances to be deleted, | |
611 | because of how Python tears down modules (it hard-sets all their |
|
611 | because of how Python tears down modules (it hard-sets all their | |
612 | references to None without regard for reference counts). This method |
|
612 | references to None without regard for reference counts). This method | |
613 | must therefore make a *copy* of the given namespace, to allow the |
|
613 | must therefore make a *copy* of the given namespace, to allow the | |
614 | original module's __dict__ to be cleared and reused. |
|
614 | original module's __dict__ to be cleared and reused. | |
615 |
|
615 | |||
616 |
|
616 | |||
617 | Parameters |
|
617 | Parameters | |
618 | ---------- |
|
618 | ---------- | |
619 | ns : a namespace (a dict, typically) |
|
619 | ns : a namespace (a dict, typically) | |
620 |
|
620 | |||
621 | fname : str |
|
621 | fname : str | |
622 | Filename associated with the namespace. |
|
622 | Filename associated with the namespace. | |
623 |
|
623 | |||
624 | Examples |
|
624 | Examples | |
625 | -------- |
|
625 | -------- | |
626 |
|
626 | |||
627 | In [10]: import IPython |
|
627 | In [10]: import IPython | |
628 |
|
628 | |||
629 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
629 | In [11]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
630 |
|
630 | |||
631 | In [12]: IPython.__file__ in _ip._main_ns_cache |
|
631 | In [12]: IPython.__file__ in _ip._main_ns_cache | |
632 | Out[12]: True |
|
632 | Out[12]: True | |
633 | """ |
|
633 | """ | |
634 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() |
|
634 | self._main_ns_cache[os.path.abspath(fname)] = ns.copy() | |
635 |
|
635 | |||
636 | def clear_main_mod_cache(self): |
|
636 | def clear_main_mod_cache(self): | |
637 | """Clear the cache of main modules. |
|
637 | """Clear the cache of main modules. | |
638 |
|
638 | |||
639 | Mainly for use by utilities like %reset. |
|
639 | Mainly for use by utilities like %reset. | |
640 |
|
640 | |||
641 | Examples |
|
641 | Examples | |
642 | -------- |
|
642 | -------- | |
643 |
|
643 | |||
644 | In [15]: import IPython |
|
644 | In [15]: import IPython | |
645 |
|
645 | |||
646 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) |
|
646 | In [16]: _ip.cache_main_mod(IPython.__dict__,IPython.__file__) | |
647 |
|
647 | |||
648 | In [17]: len(_ip._main_ns_cache) > 0 |
|
648 | In [17]: len(_ip._main_ns_cache) > 0 | |
649 | Out[17]: True |
|
649 | Out[17]: True | |
650 |
|
650 | |||
651 | In [18]: _ip.clear_main_mod_cache() |
|
651 | In [18]: _ip.clear_main_mod_cache() | |
652 |
|
652 | |||
653 | In [19]: len(_ip._main_ns_cache) == 0 |
|
653 | In [19]: len(_ip._main_ns_cache) == 0 | |
654 | Out[19]: True |
|
654 | Out[19]: True | |
655 | """ |
|
655 | """ | |
656 | self._main_ns_cache.clear() |
|
656 | self._main_ns_cache.clear() | |
657 |
|
657 | |||
658 | #------------------------------------------------------------------------- |
|
658 | #------------------------------------------------------------------------- | |
659 | # Things related to debugging |
|
659 | # Things related to debugging | |
660 | #------------------------------------------------------------------------- |
|
660 | #------------------------------------------------------------------------- | |
661 |
|
661 | |||
662 | def init_pdb(self): |
|
662 | def init_pdb(self): | |
663 | # Set calling of pdb on exceptions |
|
663 | # Set calling of pdb on exceptions | |
664 | # self.call_pdb is a property |
|
664 | # self.call_pdb is a property | |
665 | self.call_pdb = self.pdb |
|
665 | self.call_pdb = self.pdb | |
666 |
|
666 | |||
667 | def _get_call_pdb(self): |
|
667 | def _get_call_pdb(self): | |
668 | return self._call_pdb |
|
668 | return self._call_pdb | |
669 |
|
669 | |||
670 | def _set_call_pdb(self,val): |
|
670 | def _set_call_pdb(self,val): | |
671 |
|
671 | |||
672 | if val not in (0,1,False,True): |
|
672 | if val not in (0,1,False,True): | |
673 | raise ValueError,'new call_pdb value must be boolean' |
|
673 | raise ValueError,'new call_pdb value must be boolean' | |
674 |
|
674 | |||
675 | # store value in instance |
|
675 | # store value in instance | |
676 | self._call_pdb = val |
|
676 | self._call_pdb = val | |
677 |
|
677 | |||
678 | # notify the actual exception handlers |
|
678 | # notify the actual exception handlers | |
679 | self.InteractiveTB.call_pdb = val |
|
679 | self.InteractiveTB.call_pdb = val | |
680 |
|
680 | |||
681 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
681 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
682 | 'Control auto-activation of pdb at exceptions') |
|
682 | 'Control auto-activation of pdb at exceptions') | |
683 |
|
683 | |||
684 | def debugger(self,force=False): |
|
684 | def debugger(self,force=False): | |
685 | """Call the pydb/pdb debugger. |
|
685 | """Call the pydb/pdb debugger. | |
686 |
|
686 | |||
687 | Keywords: |
|
687 | Keywords: | |
688 |
|
688 | |||
689 | - force(False): by default, this routine checks the instance call_pdb |
|
689 | - force(False): by default, this routine checks the instance call_pdb | |
690 | flag and does not actually invoke the debugger if the flag is false. |
|
690 | flag and does not actually invoke the debugger if the flag is false. | |
691 | The 'force' option forces the debugger to activate even if the flag |
|
691 | The 'force' option forces the debugger to activate even if the flag | |
692 | is false. |
|
692 | is false. | |
693 | """ |
|
693 | """ | |
694 |
|
694 | |||
695 | if not (force or self.call_pdb): |
|
695 | if not (force or self.call_pdb): | |
696 | return |
|
696 | return | |
697 |
|
697 | |||
698 | if not hasattr(sys,'last_traceback'): |
|
698 | if not hasattr(sys,'last_traceback'): | |
699 | error('No traceback has been produced, nothing to debug.') |
|
699 | error('No traceback has been produced, nothing to debug.') | |
700 | return |
|
700 | return | |
701 |
|
701 | |||
702 | # use pydb if available |
|
702 | # use pydb if available | |
703 | if debugger.has_pydb: |
|
703 | if debugger.has_pydb: | |
704 | from pydb import pm |
|
704 | from pydb import pm | |
705 | else: |
|
705 | else: | |
706 | # fallback to our internal debugger |
|
706 | # fallback to our internal debugger | |
707 | pm = lambda : self.InteractiveTB.debugger(force=True) |
|
707 | pm = lambda : self.InteractiveTB.debugger(force=True) | |
708 | self.history_saving_wrapper(pm)() |
|
708 | self.history_saving_wrapper(pm)() | |
709 |
|
709 | |||
710 | #------------------------------------------------------------------------- |
|
710 | #------------------------------------------------------------------------- | |
711 | # Things related to IPython's various namespaces |
|
711 | # Things related to IPython's various namespaces | |
712 | #------------------------------------------------------------------------- |
|
712 | #------------------------------------------------------------------------- | |
713 |
|
713 | |||
714 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): |
|
714 | def init_create_namespaces(self, user_ns=None, user_global_ns=None): | |
715 | # Create the namespace where the user will operate. user_ns is |
|
715 | # Create the namespace where the user will operate. user_ns is | |
716 | # normally the only one used, and it is passed to the exec calls as |
|
716 | # normally the only one used, and it is passed to the exec calls as | |
717 | # the locals argument. But we do carry a user_global_ns namespace |
|
717 | # the locals argument. But we do carry a user_global_ns namespace | |
718 | # given as the exec 'globals' argument, This is useful in embedding |
|
718 | # given as the exec 'globals' argument, This is useful in embedding | |
719 | # situations where the ipython shell opens in a context where the |
|
719 | # situations where the ipython shell opens in a context where the | |
720 | # distinction between locals and globals is meaningful. For |
|
720 | # distinction between locals and globals is meaningful. For | |
721 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
721 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
722 |
|
722 | |||
723 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
723 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
724 | # level as a dict instead of a module. This is a manual fix, but I |
|
724 | # level as a dict instead of a module. This is a manual fix, but I | |
725 | # should really track down where the problem is coming from. Alex |
|
725 | # should really track down where the problem is coming from. Alex | |
726 | # Schmolck reported this problem first. |
|
726 | # Schmolck reported this problem first. | |
727 |
|
727 | |||
728 | # A useful post by Alex Martelli on this topic: |
|
728 | # A useful post by Alex Martelli on this topic: | |
729 | # Re: inconsistent value from __builtins__ |
|
729 | # Re: inconsistent value from __builtins__ | |
730 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
730 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
731 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
731 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
732 | # Gruppen: comp.lang.python |
|
732 | # Gruppen: comp.lang.python | |
733 |
|
733 | |||
734 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
734 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
735 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
735 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
736 | # > <type 'dict'> |
|
736 | # > <type 'dict'> | |
737 | # > >>> print type(__builtins__) |
|
737 | # > >>> print type(__builtins__) | |
738 | # > <type 'module'> |
|
738 | # > <type 'module'> | |
739 | # > Is this difference in return value intentional? |
|
739 | # > Is this difference in return value intentional? | |
740 |
|
740 | |||
741 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
741 | # Well, it's documented that '__builtins__' can be either a dictionary | |
742 | # or a module, and it's been that way for a long time. Whether it's |
|
742 | # or a module, and it's been that way for a long time. Whether it's | |
743 | # intentional (or sensible), I don't know. In any case, the idea is |
|
743 | # intentional (or sensible), I don't know. In any case, the idea is | |
744 | # that if you need to access the built-in namespace directly, you |
|
744 | # that if you need to access the built-in namespace directly, you | |
745 | # should start with "import __builtin__" (note, no 's') which will |
|
745 | # should start with "import __builtin__" (note, no 's') which will | |
746 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
746 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
747 |
|
747 | |||
748 | # These routines return properly built dicts as needed by the rest of |
|
748 | # These routines return properly built dicts as needed by the rest of | |
749 | # the code, and can also be used by extension writers to generate |
|
749 | # the code, and can also be used by extension writers to generate | |
750 | # properly initialized namespaces. |
|
750 | # properly initialized namespaces. | |
751 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, |
|
751 | user_ns, user_global_ns = self.make_user_namespaces(user_ns, | |
752 | user_global_ns) |
|
752 | user_global_ns) | |
753 |
|
753 | |||
754 | # Assign namespaces |
|
754 | # Assign namespaces | |
755 | # This is the namespace where all normal user variables live |
|
755 | # This is the namespace where all normal user variables live | |
756 | self.user_ns = user_ns |
|
756 | self.user_ns = user_ns | |
757 | self.user_global_ns = user_global_ns |
|
757 | self.user_global_ns = user_global_ns | |
758 |
|
758 | |||
759 | # An auxiliary namespace that checks what parts of the user_ns were |
|
759 | # An auxiliary namespace that checks what parts of the user_ns were | |
760 | # loaded at startup, so we can list later only variables defined in |
|
760 | # loaded at startup, so we can list later only variables defined in | |
761 | # actual interactive use. Since it is always a subset of user_ns, it |
|
761 | # actual interactive use. Since it is always a subset of user_ns, it | |
762 | # doesn't need to be separately tracked in the ns_table. |
|
762 | # doesn't need to be separately tracked in the ns_table. | |
763 | self.user_ns_hidden = {} |
|
763 | self.user_ns_hidden = {} | |
764 |
|
764 | |||
765 | # A namespace to keep track of internal data structures to prevent |
|
765 | # A namespace to keep track of internal data structures to prevent | |
766 | # them from cluttering user-visible stuff. Will be updated later |
|
766 | # them from cluttering user-visible stuff. Will be updated later | |
767 | self.internal_ns = {} |
|
767 | self.internal_ns = {} | |
768 |
|
768 | |||
769 | # Now that FakeModule produces a real module, we've run into a nasty |
|
769 | # Now that FakeModule produces a real module, we've run into a nasty | |
770 | # problem: after script execution (via %run), the module where the user |
|
770 | # problem: after script execution (via %run), the module where the user | |
771 | # code ran is deleted. Now that this object is a true module (needed |
|
771 | # code ran is deleted. Now that this object is a true module (needed | |
772 | # so docetst and other tools work correctly), the Python module |
|
772 | # so docetst and other tools work correctly), the Python module | |
773 | # teardown mechanism runs over it, and sets to None every variable |
|
773 | # teardown mechanism runs over it, and sets to None every variable | |
774 | # present in that module. Top-level references to objects from the |
|
774 | # present in that module. Top-level references to objects from the | |
775 | # script survive, because the user_ns is updated with them. However, |
|
775 | # script survive, because the user_ns is updated with them. However, | |
776 | # calling functions defined in the script that use other things from |
|
776 | # calling functions defined in the script that use other things from | |
777 | # the script will fail, because the function's closure had references |
|
777 | # the script will fail, because the function's closure had references | |
778 | # to the original objects, which are now all None. So we must protect |
|
778 | # to the original objects, which are now all None. So we must protect | |
779 | # these modules from deletion by keeping a cache. |
|
779 | # these modules from deletion by keeping a cache. | |
780 | # |
|
780 | # | |
781 | # To avoid keeping stale modules around (we only need the one from the |
|
781 | # To avoid keeping stale modules around (we only need the one from the | |
782 | # last run), we use a dict keyed with the full path to the script, so |
|
782 | # last run), we use a dict keyed with the full path to the script, so | |
783 | # only the last version of the module is held in the cache. Note, |
|
783 | # only the last version of the module is held in the cache. Note, | |
784 | # however, that we must cache the module *namespace contents* (their |
|
784 | # however, that we must cache the module *namespace contents* (their | |
785 | # __dict__). Because if we try to cache the actual modules, old ones |
|
785 | # __dict__). Because if we try to cache the actual modules, old ones | |
786 | # (uncached) could be destroyed while still holding references (such as |
|
786 | # (uncached) could be destroyed while still holding references (such as | |
787 | # those held by GUI objects that tend to be long-lived)> |
|
787 | # those held by GUI objects that tend to be long-lived)> | |
788 | # |
|
788 | # | |
789 | # The %reset command will flush this cache. See the cache_main_mod() |
|
789 | # The %reset command will flush this cache. See the cache_main_mod() | |
790 | # and clear_main_mod_cache() methods for details on use. |
|
790 | # and clear_main_mod_cache() methods for details on use. | |
791 |
|
791 | |||
792 | # This is the cache used for 'main' namespaces |
|
792 | # This is the cache used for 'main' namespaces | |
793 | self._main_ns_cache = {} |
|
793 | self._main_ns_cache = {} | |
794 | # And this is the single instance of FakeModule whose __dict__ we keep |
|
794 | # And this is the single instance of FakeModule whose __dict__ we keep | |
795 | # copying and clearing for reuse on each %run |
|
795 | # copying and clearing for reuse on each %run | |
796 | self._user_main_module = FakeModule() |
|
796 | self._user_main_module = FakeModule() | |
797 |
|
797 | |||
798 | # A table holding all the namespaces IPython deals with, so that |
|
798 | # A table holding all the namespaces IPython deals with, so that | |
799 | # introspection facilities can search easily. |
|
799 | # introspection facilities can search easily. | |
800 | self.ns_table = {'user':user_ns, |
|
800 | self.ns_table = {'user':user_ns, | |
801 | 'user_global':user_global_ns, |
|
801 | 'user_global':user_global_ns, | |
802 | 'internal':self.internal_ns, |
|
802 | 'internal':self.internal_ns, | |
803 | 'builtin':__builtin__.__dict__ |
|
803 | 'builtin':__builtin__.__dict__ | |
804 | } |
|
804 | } | |
805 |
|
805 | |||
806 | # Similarly, track all namespaces where references can be held and that |
|
806 | # Similarly, track all namespaces where references can be held and that | |
807 | # we can safely clear (so it can NOT include builtin). This one can be |
|
807 | # we can safely clear (so it can NOT include builtin). This one can be | |
808 | # a simple list. |
|
808 | # a simple list. | |
809 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden, |
|
809 | self.ns_refs_table = [ user_ns, user_global_ns, self.user_ns_hidden, | |
810 | self.internal_ns, self._main_ns_cache ] |
|
810 | self.internal_ns, self._main_ns_cache ] | |
811 |
|
811 | |||
812 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): |
|
812 | def make_user_namespaces(self, user_ns=None, user_global_ns=None): | |
813 | """Return a valid local and global user interactive namespaces. |
|
813 | """Return a valid local and global user interactive namespaces. | |
814 |
|
814 | |||
815 | This builds a dict with the minimal information needed to operate as a |
|
815 | This builds a dict with the minimal information needed to operate as a | |
816 | valid IPython user namespace, which you can pass to the various |
|
816 | valid IPython user namespace, which you can pass to the various | |
817 | embedding classes in ipython. The default implementation returns the |
|
817 | embedding classes in ipython. The default implementation returns the | |
818 | same dict for both the locals and the globals to allow functions to |
|
818 | same dict for both the locals and the globals to allow functions to | |
819 | refer to variables in the namespace. Customized implementations can |
|
819 | refer to variables in the namespace. Customized implementations can | |
820 | return different dicts. The locals dictionary can actually be anything |
|
820 | return different dicts. The locals dictionary can actually be anything | |
821 | following the basic mapping protocol of a dict, but the globals dict |
|
821 | following the basic mapping protocol of a dict, but the globals dict | |
822 | must be a true dict, not even a subclass. It is recommended that any |
|
822 | must be a true dict, not even a subclass. It is recommended that any | |
823 | custom object for the locals namespace synchronize with the globals |
|
823 | custom object for the locals namespace synchronize with the globals | |
824 | dict somehow. |
|
824 | dict somehow. | |
825 |
|
825 | |||
826 | Raises TypeError if the provided globals namespace is not a true dict. |
|
826 | Raises TypeError if the provided globals namespace is not a true dict. | |
827 |
|
827 | |||
828 | Parameters |
|
828 | Parameters | |
829 | ---------- |
|
829 | ---------- | |
830 | user_ns : dict-like, optional |
|
830 | user_ns : dict-like, optional | |
831 | The current user namespace. The items in this namespace should |
|
831 | The current user namespace. The items in this namespace should | |
832 | be included in the output. If None, an appropriate blank |
|
832 | be included in the output. If None, an appropriate blank | |
833 | namespace should be created. |
|
833 | namespace should be created. | |
834 | user_global_ns : dict, optional |
|
834 | user_global_ns : dict, optional | |
835 | The current user global namespace. The items in this namespace |
|
835 | The current user global namespace. The items in this namespace | |
836 | should be included in the output. If None, an appropriate |
|
836 | should be included in the output. If None, an appropriate | |
837 | blank namespace should be created. |
|
837 | blank namespace should be created. | |
838 |
|
838 | |||
839 | Returns |
|
839 | Returns | |
840 | ------- |
|
840 | ------- | |
841 | A pair of dictionary-like object to be used as the local namespace |
|
841 | A pair of dictionary-like object to be used as the local namespace | |
842 | of the interpreter and a dict to be used as the global namespace. |
|
842 | of the interpreter and a dict to be used as the global namespace. | |
843 | """ |
|
843 | """ | |
844 |
|
844 | |||
845 |
|
845 | |||
846 | # We must ensure that __builtin__ (without the final 's') is always |
|
846 | # We must ensure that __builtin__ (without the final 's') is always | |
847 | # available and pointing to the __builtin__ *module*. For more details: |
|
847 | # available and pointing to the __builtin__ *module*. For more details: | |
848 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
848 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
849 |
|
849 | |||
850 | if user_ns is None: |
|
850 | if user_ns is None: | |
851 | # Set __name__ to __main__ to better match the behavior of the |
|
851 | # Set __name__ to __main__ to better match the behavior of the | |
852 | # normal interpreter. |
|
852 | # normal interpreter. | |
853 | user_ns = {'__name__' :'__main__', |
|
853 | user_ns = {'__name__' :'__main__', | |
854 | '__builtin__' : __builtin__, |
|
854 | '__builtin__' : __builtin__, | |
855 | '__builtins__' : __builtin__, |
|
855 | '__builtins__' : __builtin__, | |
856 | } |
|
856 | } | |
857 | else: |
|
857 | else: | |
858 | user_ns.setdefault('__name__','__main__') |
|
858 | user_ns.setdefault('__name__','__main__') | |
859 | user_ns.setdefault('__builtin__',__builtin__) |
|
859 | user_ns.setdefault('__builtin__',__builtin__) | |
860 | user_ns.setdefault('__builtins__',__builtin__) |
|
860 | user_ns.setdefault('__builtins__',__builtin__) | |
861 |
|
861 | |||
862 | if user_global_ns is None: |
|
862 | if user_global_ns is None: | |
863 | user_global_ns = user_ns |
|
863 | user_global_ns = user_ns | |
864 | if type(user_global_ns) is not dict: |
|
864 | if type(user_global_ns) is not dict: | |
865 | raise TypeError("user_global_ns must be a true dict; got %r" |
|
865 | raise TypeError("user_global_ns must be a true dict; got %r" | |
866 | % type(user_global_ns)) |
|
866 | % type(user_global_ns)) | |
867 |
|
867 | |||
868 | return user_ns, user_global_ns |
|
868 | return user_ns, user_global_ns | |
869 |
|
869 | |||
870 | def init_sys_modules(self): |
|
870 | def init_sys_modules(self): | |
871 | # We need to insert into sys.modules something that looks like a |
|
871 | # We need to insert into sys.modules something that looks like a | |
872 | # module but which accesses the IPython namespace, for shelve and |
|
872 | # module but which accesses the IPython namespace, for shelve and | |
873 | # pickle to work interactively. Normally they rely on getting |
|
873 | # pickle to work interactively. Normally they rely on getting | |
874 | # everything out of __main__, but for embedding purposes each IPython |
|
874 | # everything out of __main__, but for embedding purposes each IPython | |
875 | # instance has its own private namespace, so we can't go shoving |
|
875 | # instance has its own private namespace, so we can't go shoving | |
876 | # everything into __main__. |
|
876 | # everything into __main__. | |
877 |
|
877 | |||
878 | # note, however, that we should only do this for non-embedded |
|
878 | # note, however, that we should only do this for non-embedded | |
879 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
879 | # ipythons, which really mimic the __main__.__dict__ with their own | |
880 | # namespace. Embedded instances, on the other hand, should not do |
|
880 | # namespace. Embedded instances, on the other hand, should not do | |
881 | # this because they need to manage the user local/global namespaces |
|
881 | # this because they need to manage the user local/global namespaces | |
882 | # only, but they live within a 'normal' __main__ (meaning, they |
|
882 | # only, but they live within a 'normal' __main__ (meaning, they | |
883 | # shouldn't overtake the execution environment of the script they're |
|
883 | # shouldn't overtake the execution environment of the script they're | |
884 | # embedded in). |
|
884 | # embedded in). | |
885 |
|
885 | |||
886 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
886 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
887 |
|
887 | |||
888 | try: |
|
888 | try: | |
889 | main_name = self.user_ns['__name__'] |
|
889 | main_name = self.user_ns['__name__'] | |
890 | except KeyError: |
|
890 | except KeyError: | |
891 | raise KeyError('user_ns dictionary MUST have a "__name__" key') |
|
891 | raise KeyError('user_ns dictionary MUST have a "__name__" key') | |
892 | else: |
|
892 | else: | |
893 | sys.modules[main_name] = FakeModule(self.user_ns) |
|
893 | sys.modules[main_name] = FakeModule(self.user_ns) | |
894 |
|
894 | |||
895 | def init_user_ns(self): |
|
895 | def init_user_ns(self): | |
896 | """Initialize all user-visible namespaces to their minimum defaults. |
|
896 | """Initialize all user-visible namespaces to their minimum defaults. | |
897 |
|
897 | |||
898 | Certain history lists are also initialized here, as they effectively |
|
898 | Certain history lists are also initialized here, as they effectively | |
899 | act as user namespaces. |
|
899 | act as user namespaces. | |
900 |
|
900 | |||
901 | Notes |
|
901 | Notes | |
902 | ----- |
|
902 | ----- | |
903 | All data structures here are only filled in, they are NOT reset by this |
|
903 | All data structures here are only filled in, they are NOT reset by this | |
904 | method. If they were not empty before, data will simply be added to |
|
904 | method. If they were not empty before, data will simply be added to | |
905 | therm. |
|
905 | therm. | |
906 | """ |
|
906 | """ | |
907 | # This function works in two parts: first we put a few things in |
|
907 | # This function works in two parts: first we put a few things in | |
908 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
908 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
909 | # initial variables aren't shown by %who. After the sync, we add the |
|
909 | # initial variables aren't shown by %who. After the sync, we add the | |
910 | # rest of what we *do* want the user to see with %who even on a new |
|
910 | # rest of what we *do* want the user to see with %who even on a new | |
911 | # session (probably nothing, so theye really only see their own stuff) |
|
911 | # session (probably nothing, so theye really only see their own stuff) | |
912 |
|
912 | |||
913 | # The user dict must *always* have a __builtin__ reference to the |
|
913 | # The user dict must *always* have a __builtin__ reference to the | |
914 | # Python standard __builtin__ namespace, which must be imported. |
|
914 | # Python standard __builtin__ namespace, which must be imported. | |
915 | # This is so that certain operations in prompt evaluation can be |
|
915 | # This is so that certain operations in prompt evaluation can be | |
916 | # reliably executed with builtins. Note that we can NOT use |
|
916 | # reliably executed with builtins. Note that we can NOT use | |
917 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
917 | # __builtins__ (note the 's'), because that can either be a dict or a | |
918 | # module, and can even mutate at runtime, depending on the context |
|
918 | # module, and can even mutate at runtime, depending on the context | |
919 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
919 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
920 | # always a module object, though it must be explicitly imported. |
|
920 | # always a module object, though it must be explicitly imported. | |
921 |
|
921 | |||
922 | # For more details: |
|
922 | # For more details: | |
923 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
923 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
924 | ns = dict(__builtin__ = __builtin__) |
|
924 | ns = dict(__builtin__ = __builtin__) | |
925 |
|
925 | |||
926 | # Put 'help' in the user namespace |
|
926 | # Put 'help' in the user namespace | |
927 | try: |
|
927 | try: | |
928 | from site import _Helper |
|
928 | from site import _Helper | |
929 | ns['help'] = _Helper() |
|
929 | ns['help'] = _Helper() | |
930 | except ImportError: |
|
930 | except ImportError: | |
931 | warn('help() not available - check site.py') |
|
931 | warn('help() not available - check site.py') | |
932 |
|
932 | |||
933 | # make global variables for user access to the histories |
|
933 | # make global variables for user access to the histories | |
934 | ns['_ih'] = self.input_hist |
|
934 | ns['_ih'] = self.input_hist | |
935 | ns['_oh'] = self.output_hist |
|
935 | ns['_oh'] = self.output_hist | |
936 | ns['_dh'] = self.dir_hist |
|
936 | ns['_dh'] = self.dir_hist | |
937 |
|
937 | |||
938 | ns['_sh'] = shadowns |
|
938 | ns['_sh'] = shadowns | |
939 |
|
939 | |||
940 | # user aliases to input and output histories. These shouldn't show up |
|
940 | # user aliases to input and output histories. These shouldn't show up | |
941 | # in %who, as they can have very large reprs. |
|
941 | # in %who, as they can have very large reprs. | |
942 | ns['In'] = self.input_hist |
|
942 | ns['In'] = self.input_hist | |
943 | ns['Out'] = self.output_hist |
|
943 | ns['Out'] = self.output_hist | |
944 |
|
944 | |||
945 | # Store myself as the public api!!! |
|
945 | # Store myself as the public api!!! | |
946 | ns['get_ipython'] = self.get_ipython |
|
946 | ns['get_ipython'] = self.get_ipython | |
947 |
|
947 | |||
948 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
948 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
949 | # by %who |
|
949 | # by %who | |
950 | self.user_ns_hidden.update(ns) |
|
950 | self.user_ns_hidden.update(ns) | |
951 |
|
951 | |||
952 | # Anything put into ns now would show up in %who. Think twice before |
|
952 | # Anything put into ns now would show up in %who. Think twice before | |
953 | # putting anything here, as we really want %who to show the user their |
|
953 | # putting anything here, as we really want %who to show the user their | |
954 | # stuff, not our variables. |
|
954 | # stuff, not our variables. | |
955 |
|
955 | |||
956 | # Finally, update the real user's namespace |
|
956 | # Finally, update the real user's namespace | |
957 | self.user_ns.update(ns) |
|
957 | self.user_ns.update(ns) | |
958 |
|
958 | |||
959 |
|
959 | |||
960 | def reset(self): |
|
960 | def reset(self): | |
961 | """Clear all internal namespaces. |
|
961 | """Clear all internal namespaces. | |
962 |
|
962 | |||
963 | Note that this is much more aggressive than %reset, since it clears |
|
963 | Note that this is much more aggressive than %reset, since it clears | |
964 | fully all namespaces, as well as all input/output lists. |
|
964 | fully all namespaces, as well as all input/output lists. | |
965 | """ |
|
965 | """ | |
966 | for ns in self.ns_refs_table: |
|
966 | for ns in self.ns_refs_table: | |
967 | ns.clear() |
|
967 | ns.clear() | |
968 |
|
968 | |||
969 | self.alias_manager.clear_aliases() |
|
969 | self.alias_manager.clear_aliases() | |
970 |
|
970 | |||
971 | # Clear input and output histories |
|
971 | # Clear input and output histories | |
972 | self.input_hist[:] = [] |
|
972 | self.input_hist[:] = [] | |
973 | self.input_hist_raw[:] = [] |
|
973 | self.input_hist_raw[:] = [] | |
974 | self.output_hist.clear() |
|
974 | self.output_hist.clear() | |
975 |
|
975 | |||
976 | # Restore the user namespaces to minimal usability |
|
976 | # Restore the user namespaces to minimal usability | |
977 | self.init_user_ns() |
|
977 | self.init_user_ns() | |
978 |
|
978 | |||
979 | # Restore the default and user aliases |
|
979 | # Restore the default and user aliases | |
980 | self.alias_manager.init_aliases() |
|
980 | self.alias_manager.init_aliases() | |
981 |
|
981 | |||
982 | def reset_selective(self, regex=None): |
|
982 | def reset_selective(self, regex=None): | |
983 | """Clear selective variables from internal namespaces based on a |
|
983 | """Clear selective variables from internal namespaces based on a | |
984 | specified regular expression. |
|
984 | specified regular expression. | |
985 |
|
985 | |||
986 | Parameters |
|
986 | Parameters | |
987 | ---------- |
|
987 | ---------- | |
988 | regex : string or compiled pattern, optional |
|
988 | regex : string or compiled pattern, optional | |
989 | A regular expression pattern that will be used in searching |
|
989 | A regular expression pattern that will be used in searching | |
990 | variable names in the users namespaces. |
|
990 | variable names in the users namespaces. | |
991 | """ |
|
991 | """ | |
992 | if regex is not None: |
|
992 | if regex is not None: | |
993 | try: |
|
993 | try: | |
994 | m = re.compile(regex) |
|
994 | m = re.compile(regex) | |
995 | except TypeError: |
|
995 | except TypeError: | |
996 | raise TypeError('regex must be a string or compiled pattern') |
|
996 | raise TypeError('regex must be a string or compiled pattern') | |
997 | # Search for keys in each namespace that match the given regex |
|
997 | # Search for keys in each namespace that match the given regex | |
998 | # If a match is found, delete the key/value pair. |
|
998 | # If a match is found, delete the key/value pair. | |
999 | for ns in self.ns_refs_table: |
|
999 | for ns in self.ns_refs_table: | |
1000 | for var in ns: |
|
1000 | for var in ns: | |
1001 | if m.search(var): |
|
1001 | if m.search(var): | |
1002 | del ns[var] |
|
1002 | del ns[var] | |
1003 |
|
1003 | |||
1004 | def push(self, variables, interactive=True): |
|
1004 | def push(self, variables, interactive=True): | |
1005 | """Inject a group of variables into the IPython user namespace. |
|
1005 | """Inject a group of variables into the IPython user namespace. | |
1006 |
|
1006 | |||
1007 | Parameters |
|
1007 | Parameters | |
1008 | ---------- |
|
1008 | ---------- | |
1009 | variables : dict, str or list/tuple of str |
|
1009 | variables : dict, str or list/tuple of str | |
1010 | The variables to inject into the user's namespace. If a dict, a |
|
1010 | The variables to inject into the user's namespace. If a dict, a | |
1011 | simple update is done. If a str, the string is assumed to have |
|
1011 | simple update is done. If a str, the string is assumed to have | |
1012 | variable names separated by spaces. A list/tuple of str can also |
|
1012 | variable names separated by spaces. A list/tuple of str can also | |
1013 | be used to give the variable names. If just the variable names are |
|
1013 | be used to give the variable names. If just the variable names are | |
1014 | give (list/tuple/str) then the variable values looked up in the |
|
1014 | give (list/tuple/str) then the variable values looked up in the | |
1015 | callers frame. |
|
1015 | callers frame. | |
1016 | interactive : bool |
|
1016 | interactive : bool | |
1017 | If True (default), the variables will be listed with the ``who`` |
|
1017 | If True (default), the variables will be listed with the ``who`` | |
1018 | magic. |
|
1018 | magic. | |
1019 | """ |
|
1019 | """ | |
1020 | vdict = None |
|
1020 | vdict = None | |
1021 |
|
1021 | |||
1022 | # We need a dict of name/value pairs to do namespace updates. |
|
1022 | # We need a dict of name/value pairs to do namespace updates. | |
1023 | if isinstance(variables, dict): |
|
1023 | if isinstance(variables, dict): | |
1024 | vdict = variables |
|
1024 | vdict = variables | |
1025 | elif isinstance(variables, (basestring, list, tuple)): |
|
1025 | elif isinstance(variables, (basestring, list, tuple)): | |
1026 | if isinstance(variables, basestring): |
|
1026 | if isinstance(variables, basestring): | |
1027 | vlist = variables.split() |
|
1027 | vlist = variables.split() | |
1028 | else: |
|
1028 | else: | |
1029 | vlist = variables |
|
1029 | vlist = variables | |
1030 | vdict = {} |
|
1030 | vdict = {} | |
1031 | cf = sys._getframe(1) |
|
1031 | cf = sys._getframe(1) | |
1032 | for name in vlist: |
|
1032 | for name in vlist: | |
1033 | try: |
|
1033 | try: | |
1034 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1034 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1035 | except: |
|
1035 | except: | |
1036 | print ('Could not get variable %s from %s' % |
|
1036 | print ('Could not get variable %s from %s' % | |
1037 | (name,cf.f_code.co_name)) |
|
1037 | (name,cf.f_code.co_name)) | |
1038 | else: |
|
1038 | else: | |
1039 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1039 | raise ValueError('variables must be a dict/str/list/tuple') | |
1040 |
|
1040 | |||
1041 | # Propagate variables to user namespace |
|
1041 | # Propagate variables to user namespace | |
1042 | self.user_ns.update(vdict) |
|
1042 | self.user_ns.update(vdict) | |
1043 |
|
1043 | |||
1044 | # And configure interactive visibility |
|
1044 | # And configure interactive visibility | |
1045 | config_ns = self.user_ns_hidden |
|
1045 | config_ns = self.user_ns_hidden | |
1046 | if interactive: |
|
1046 | if interactive: | |
1047 | for name, val in vdict.iteritems(): |
|
1047 | for name, val in vdict.iteritems(): | |
1048 | config_ns.pop(name, None) |
|
1048 | config_ns.pop(name, None) | |
1049 | else: |
|
1049 | else: | |
1050 | for name,val in vdict.iteritems(): |
|
1050 | for name,val in vdict.iteritems(): | |
1051 | config_ns[name] = val |
|
1051 | config_ns[name] = val | |
1052 |
|
1052 | |||
1053 | #------------------------------------------------------------------------- |
|
1053 | #------------------------------------------------------------------------- | |
1054 | # Things related to object introspection |
|
1054 | # Things related to object introspection | |
1055 | #------------------------------------------------------------------------- |
|
1055 | #------------------------------------------------------------------------- | |
1056 | def _ofind(self, oname, namespaces=None): |
|
1056 | def _ofind(self, oname, namespaces=None): | |
1057 | """Find an object in the available namespaces. |
|
1057 | """Find an object in the available namespaces. | |
1058 |
|
1058 | |||
1059 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1059 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1060 |
|
1060 | |||
1061 | Has special code to detect magic functions. |
|
1061 | Has special code to detect magic functions. | |
1062 | """ |
|
1062 | """ | |
1063 | #oname = oname.strip() |
|
1063 | #oname = oname.strip() | |
1064 | #print '1- oname: <%r>' % oname # dbg |
|
1064 | #print '1- oname: <%r>' % oname # dbg | |
1065 | try: |
|
1065 | try: | |
1066 | oname = oname.strip().encode('ascii') |
|
1066 | oname = oname.strip().encode('ascii') | |
1067 | #print '2- oname: <%r>' % oname # dbg |
|
1067 | #print '2- oname: <%r>' % oname # dbg | |
1068 | except UnicodeEncodeError: |
|
1068 | except UnicodeEncodeError: | |
1069 | print 'Python identifiers can only contain ascii characters.' |
|
1069 | print 'Python identifiers can only contain ascii characters.' | |
1070 | return dict(found=False) |
|
1070 | return dict(found=False) | |
1071 |
|
1071 | |||
1072 | alias_ns = None |
|
1072 | alias_ns = None | |
1073 | if namespaces is None: |
|
1073 | if namespaces is None: | |
1074 | # Namespaces to search in: |
|
1074 | # Namespaces to search in: | |
1075 | # Put them in a list. The order is important so that we |
|
1075 | # Put them in a list. The order is important so that we | |
1076 | # find things in the same order that Python finds them. |
|
1076 | # find things in the same order that Python finds them. | |
1077 | namespaces = [ ('Interactive', self.user_ns), |
|
1077 | namespaces = [ ('Interactive', self.user_ns), | |
1078 | ('IPython internal', self.internal_ns), |
|
1078 | ('IPython internal', self.internal_ns), | |
1079 | ('Python builtin', __builtin__.__dict__), |
|
1079 | ('Python builtin', __builtin__.__dict__), | |
1080 | ('Alias', self.alias_manager.alias_table), |
|
1080 | ('Alias', self.alias_manager.alias_table), | |
1081 | ] |
|
1081 | ] | |
1082 | alias_ns = self.alias_manager.alias_table |
|
1082 | alias_ns = self.alias_manager.alias_table | |
1083 |
|
1083 | |||
1084 | # initialize results to 'null' |
|
1084 | # initialize results to 'null' | |
1085 | found = False; obj = None; ospace = None; ds = None; |
|
1085 | found = False; obj = None; ospace = None; ds = None; | |
1086 | ismagic = False; isalias = False; parent = None |
|
1086 | ismagic = False; isalias = False; parent = None | |
1087 |
|
1087 | |||
1088 | # We need to special-case 'print', which as of python2.6 registers as a |
|
1088 | # We need to special-case 'print', which as of python2.6 registers as a | |
1089 | # function but should only be treated as one if print_function was |
|
1089 | # function but should only be treated as one if print_function was | |
1090 | # loaded with a future import. In this case, just bail. |
|
1090 | # loaded with a future import. In this case, just bail. | |
1091 | if (oname == 'print' and not (self.compile.compiler.flags & |
|
1091 | if (oname == 'print' and not (self.compile.compiler.flags & | |
1092 | __future__.CO_FUTURE_PRINT_FUNCTION)): |
|
1092 | __future__.CO_FUTURE_PRINT_FUNCTION)): | |
1093 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1093 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1094 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1094 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1095 |
|
1095 | |||
1096 | # Look for the given name by splitting it in parts. If the head is |
|
1096 | # Look for the given name by splitting it in parts. If the head is | |
1097 | # found, then we look for all the remaining parts as members, and only |
|
1097 | # found, then we look for all the remaining parts as members, and only | |
1098 | # declare success if we can find them all. |
|
1098 | # declare success if we can find them all. | |
1099 | oname_parts = oname.split('.') |
|
1099 | oname_parts = oname.split('.') | |
1100 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1100 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1101 | for nsname,ns in namespaces: |
|
1101 | for nsname,ns in namespaces: | |
1102 | try: |
|
1102 | try: | |
1103 | obj = ns[oname_head] |
|
1103 | obj = ns[oname_head] | |
1104 | except KeyError: |
|
1104 | except KeyError: | |
1105 | continue |
|
1105 | continue | |
1106 | else: |
|
1106 | else: | |
1107 | #print 'oname_rest:', oname_rest # dbg |
|
1107 | #print 'oname_rest:', oname_rest # dbg | |
1108 | for part in oname_rest: |
|
1108 | for part in oname_rest: | |
1109 | try: |
|
1109 | try: | |
1110 | parent = obj |
|
1110 | parent = obj | |
1111 | obj = getattr(obj,part) |
|
1111 | obj = getattr(obj,part) | |
1112 | except: |
|
1112 | except: | |
1113 | # Blanket except b/c some badly implemented objects |
|
1113 | # Blanket except b/c some badly implemented objects | |
1114 | # allow __getattr__ to raise exceptions other than |
|
1114 | # allow __getattr__ to raise exceptions other than | |
1115 | # AttributeError, which then crashes IPython. |
|
1115 | # AttributeError, which then crashes IPython. | |
1116 | break |
|
1116 | break | |
1117 | else: |
|
1117 | else: | |
1118 | # If we finish the for loop (no break), we got all members |
|
1118 | # If we finish the for loop (no break), we got all members | |
1119 | found = True |
|
1119 | found = True | |
1120 | ospace = nsname |
|
1120 | ospace = nsname | |
1121 | if ns == alias_ns: |
|
1121 | if ns == alias_ns: | |
1122 | isalias = True |
|
1122 | isalias = True | |
1123 | break # namespace loop |
|
1123 | break # namespace loop | |
1124 |
|
1124 | |||
1125 | # Try to see if it's magic |
|
1125 | # Try to see if it's magic | |
1126 | if not found: |
|
1126 | if not found: | |
1127 | if oname.startswith(ESC_MAGIC): |
|
1127 | if oname.startswith(ESC_MAGIC): | |
1128 | oname = oname[1:] |
|
1128 | oname = oname[1:] | |
1129 | obj = getattr(self,'magic_'+oname,None) |
|
1129 | obj = getattr(self,'magic_'+oname,None) | |
1130 | if obj is not None: |
|
1130 | if obj is not None: | |
1131 | found = True |
|
1131 | found = True | |
1132 | ospace = 'IPython internal' |
|
1132 | ospace = 'IPython internal' | |
1133 | ismagic = True |
|
1133 | ismagic = True | |
1134 |
|
1134 | |||
1135 | # Last try: special-case some literals like '', [], {}, etc: |
|
1135 | # Last try: special-case some literals like '', [], {}, etc: | |
1136 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1136 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1137 | obj = eval(oname_head) |
|
1137 | obj = eval(oname_head) | |
1138 | found = True |
|
1138 | found = True | |
1139 | ospace = 'Interactive' |
|
1139 | ospace = 'Interactive' | |
1140 |
|
1140 | |||
1141 | return {'found':found, 'obj':obj, 'namespace':ospace, |
|
1141 | return {'found':found, 'obj':obj, 'namespace':ospace, | |
1142 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} |
|
1142 | 'ismagic':ismagic, 'isalias':isalias, 'parent':parent} | |
1143 |
|
1143 | |||
1144 | def _ofind_property(self, oname, info): |
|
1144 | def _ofind_property(self, oname, info): | |
1145 | """Second part of object finding, to look for property details.""" |
|
1145 | """Second part of object finding, to look for property details.""" | |
1146 | if info.found: |
|
1146 | if info.found: | |
1147 | # Get the docstring of the class property if it exists. |
|
1147 | # Get the docstring of the class property if it exists. | |
1148 | path = oname.split('.') |
|
1148 | path = oname.split('.') | |
1149 | root = '.'.join(path[:-1]) |
|
1149 | root = '.'.join(path[:-1]) | |
1150 | if info.parent is not None: |
|
1150 | if info.parent is not None: | |
1151 | try: |
|
1151 | try: | |
1152 | target = getattr(info.parent, '__class__') |
|
1152 | target = getattr(info.parent, '__class__') | |
1153 | # The object belongs to a class instance. |
|
1153 | # The object belongs to a class instance. | |
1154 | try: |
|
1154 | try: | |
1155 | target = getattr(target, path[-1]) |
|
1155 | target = getattr(target, path[-1]) | |
1156 | # The class defines the object. |
|
1156 | # The class defines the object. | |
1157 | if isinstance(target, property): |
|
1157 | if isinstance(target, property): | |
1158 | oname = root + '.__class__.' + path[-1] |
|
1158 | oname = root + '.__class__.' + path[-1] | |
1159 | info = Struct(self._ofind(oname)) |
|
1159 | info = Struct(self._ofind(oname)) | |
1160 | except AttributeError: pass |
|
1160 | except AttributeError: pass | |
1161 | except AttributeError: pass |
|
1161 | except AttributeError: pass | |
1162 |
|
1162 | |||
1163 | # We return either the new info or the unmodified input if the object |
|
1163 | # We return either the new info or the unmodified input if the object | |
1164 | # hadn't been found |
|
1164 | # hadn't been found | |
1165 | return info |
|
1165 | return info | |
1166 |
|
1166 | |||
1167 | def _object_find(self, oname, namespaces=None): |
|
1167 | def _object_find(self, oname, namespaces=None): | |
1168 | """Find an object and return a struct with info about it.""" |
|
1168 | """Find an object and return a struct with info about it.""" | |
1169 | inf = Struct(self._ofind(oname, namespaces)) |
|
1169 | inf = Struct(self._ofind(oname, namespaces)) | |
1170 | return Struct(self._ofind_property(oname, inf)) |
|
1170 | return Struct(self._ofind_property(oname, inf)) | |
1171 |
|
1171 | |||
1172 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1172 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1173 | """Generic interface to the inspector system. |
|
1173 | """Generic interface to the inspector system. | |
1174 |
|
1174 | |||
1175 | This function is meant to be called by pdef, pdoc & friends.""" |
|
1175 | This function is meant to be called by pdef, pdoc & friends.""" | |
1176 | info = self._object_find(oname) |
|
1176 | info = self._object_find(oname) | |
1177 | if info.found: |
|
1177 | if info.found: | |
1178 | pmethod = getattr(self.inspector, meth) |
|
1178 | pmethod = getattr(self.inspector, meth) | |
1179 | formatter = format_screen if info.ismagic else None |
|
1179 | formatter = format_screen if info.ismagic else None | |
1180 | if meth == 'pdoc': |
|
1180 | if meth == 'pdoc': | |
1181 | pmethod(info.obj, oname, formatter) |
|
1181 | pmethod(info.obj, oname, formatter) | |
1182 | elif meth == 'pinfo': |
|
1182 | elif meth == 'pinfo': | |
1183 | pmethod(info.obj, oname, formatter, info, **kw) |
|
1183 | pmethod(info.obj, oname, formatter, info, **kw) | |
1184 | else: |
|
1184 | else: | |
1185 | pmethod(info.obj, oname) |
|
1185 | pmethod(info.obj, oname) | |
1186 | else: |
|
1186 | else: | |
1187 | print 'Object `%s` not found.' % oname |
|
1187 | print 'Object `%s` not found.' % oname | |
1188 | return 'not found' # so callers can take other action |
|
1188 | return 'not found' # so callers can take other action | |
1189 |
|
1189 | |||
1190 | def object_inspect(self, oname): |
|
1190 | def object_inspect(self, oname): | |
1191 | info = self._object_find(oname) |
|
1191 | info = self._object_find(oname) | |
1192 | if info.found: |
|
1192 | if info.found: | |
1193 | return self.inspector.info(info.obj, info=info) |
|
1193 | return self.inspector.info(info.obj, info=info) | |
1194 | else: |
|
1194 | else: | |
1195 | return oinspect.mk_object_info({'found' : False}) |
|
1195 | return oinspect.mk_object_info({'found' : False}) | |
1196 |
|
1196 | |||
1197 | #------------------------------------------------------------------------- |
|
1197 | #------------------------------------------------------------------------- | |
1198 | # Things related to history management |
|
1198 | # Things related to history management | |
1199 | #------------------------------------------------------------------------- |
|
1199 | #------------------------------------------------------------------------- | |
1200 |
|
1200 | |||
1201 | def init_history(self): |
|
1201 | def init_history(self): | |
1202 | # List of input with multi-line handling. |
|
1202 | # List of input with multi-line handling. | |
1203 | self.input_hist = InputList() |
|
1203 | self.input_hist = InputList() | |
1204 | # This one will hold the 'raw' input history, without any |
|
1204 | # This one will hold the 'raw' input history, without any | |
1205 | # pre-processing. This will allow users to retrieve the input just as |
|
1205 | # pre-processing. This will allow users to retrieve the input just as | |
1206 | # it was exactly typed in by the user, with %hist -r. |
|
1206 | # it was exactly typed in by the user, with %hist -r. | |
1207 | self.input_hist_raw = InputList() |
|
1207 | self.input_hist_raw = InputList() | |
1208 |
|
1208 | |||
1209 | # list of visited directories |
|
1209 | # list of visited directories | |
1210 | try: |
|
1210 | try: | |
1211 | self.dir_hist = [os.getcwd()] |
|
1211 | self.dir_hist = [os.getcwd()] | |
1212 | except OSError: |
|
1212 | except OSError: | |
1213 | self.dir_hist = [] |
|
1213 | self.dir_hist = [] | |
1214 |
|
1214 | |||
1215 | # dict of output history |
|
1215 | # dict of output history | |
1216 | self.output_hist = {} |
|
1216 | self.output_hist = {} | |
1217 |
|
1217 | |||
1218 | # Now the history file |
|
1218 | # Now the history file | |
1219 | if self.profile: |
|
1219 | if self.profile: | |
1220 | histfname = 'history-%s' % self.profile |
|
1220 | histfname = 'history-%s' % self.profile | |
1221 | else: |
|
1221 | else: | |
1222 | histfname = 'history' |
|
1222 | histfname = 'history' | |
1223 | self.histfile = os.path.join(self.ipython_dir, histfname) |
|
1223 | self.histfile = os.path.join(self.ipython_dir, histfname) | |
1224 |
|
1224 | |||
1225 | # Fill the history zero entry, user counter starts at 1 |
|
1225 | # Fill the history zero entry, user counter starts at 1 | |
1226 | self.input_hist.append('\n') |
|
1226 | self.input_hist.append('\n') | |
1227 | self.input_hist_raw.append('\n') |
|
1227 | self.input_hist_raw.append('\n') | |
1228 |
|
1228 | |||
1229 | def init_shadow_hist(self): |
|
1229 | def init_shadow_hist(self): | |
1230 | try: |
|
1230 | try: | |
1231 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") |
|
1231 | self.db = pickleshare.PickleShareDB(self.ipython_dir + "/db") | |
1232 | except exceptions.UnicodeDecodeError: |
|
1232 | except exceptions.UnicodeDecodeError: | |
1233 | print "Your ipython_dir can't be decoded to unicode!" |
|
1233 | print "Your ipython_dir can't be decoded to unicode!" | |
1234 | print "Please set HOME environment variable to something that" |
|
1234 | print "Please set HOME environment variable to something that" | |
1235 | print r"only has ASCII characters, e.g. c:\home" |
|
1235 | print r"only has ASCII characters, e.g. c:\home" | |
1236 | print "Now it is", self.ipython_dir |
|
1236 | print "Now it is", self.ipython_dir | |
1237 | sys.exit() |
|
1237 | sys.exit() | |
1238 | self.shadowhist = ipcorehist.ShadowHist(self.db) |
|
1238 | self.shadowhist = ipcorehist.ShadowHist(self.db) | |
1239 |
|
1239 | |||
1240 | def savehist(self): |
|
1240 | def savehist(self): | |
1241 | """Save input history to a file (via readline library).""" |
|
1241 | """Save input history to a file (via readline library).""" | |
1242 |
|
1242 | |||
1243 | try: |
|
1243 | try: | |
1244 | self.readline.write_history_file(self.histfile) |
|
1244 | self.readline.write_history_file(self.histfile) | |
1245 | except: |
|
1245 | except: | |
1246 | print 'Unable to save IPython command history to file: ' + \ |
|
1246 | print 'Unable to save IPython command history to file: ' + \ | |
1247 | `self.histfile` |
|
1247 | `self.histfile` | |
1248 |
|
1248 | |||
1249 | def reloadhist(self): |
|
1249 | def reloadhist(self): | |
1250 | """Reload the input history from disk file.""" |
|
1250 | """Reload the input history from disk file.""" | |
1251 |
|
1251 | |||
1252 | try: |
|
1252 | try: | |
1253 | self.readline.clear_history() |
|
1253 | self.readline.clear_history() | |
1254 | self.readline.read_history_file(self.shell.histfile) |
|
1254 | self.readline.read_history_file(self.shell.histfile) | |
1255 | except AttributeError: |
|
1255 | except AttributeError: | |
1256 | pass |
|
1256 | pass | |
1257 |
|
1257 | |||
1258 | def history_saving_wrapper(self, func): |
|
1258 | def history_saving_wrapper(self, func): | |
1259 | """ Wrap func for readline history saving |
|
1259 | """ Wrap func for readline history saving | |
1260 |
|
1260 | |||
1261 | Convert func into callable that saves & restores |
|
1261 | Convert func into callable that saves & restores | |
1262 | history around the call """ |
|
1262 | history around the call """ | |
1263 |
|
1263 | |||
1264 | if self.has_readline: |
|
1264 | if self.has_readline: | |
1265 | from IPython.utils import rlineimpl as readline |
|
1265 | from IPython.utils import rlineimpl as readline | |
1266 | else: |
|
1266 | else: | |
1267 | return func |
|
1267 | return func | |
1268 |
|
1268 | |||
1269 | def wrapper(): |
|
1269 | def wrapper(): | |
1270 | self.savehist() |
|
1270 | self.savehist() | |
1271 | try: |
|
1271 | try: | |
1272 | func() |
|
1272 | func() | |
1273 | finally: |
|
1273 | finally: | |
1274 | readline.read_history_file(self.histfile) |
|
1274 | readline.read_history_file(self.histfile) | |
1275 | return wrapper |
|
1275 | return wrapper | |
1276 |
|
1276 | |||
1277 | def get_history(self, index=None, raw=False, output=True): |
|
1277 | def get_history(self, index=None, raw=False, output=True): | |
1278 | """Get the history list. |
|
1278 | """Get the history list. | |
1279 |
|
1279 | |||
1280 | Get the input and output history. |
|
1280 | Get the input and output history. | |
1281 |
|
1281 | |||
1282 | Parameters |
|
1282 | Parameters | |
1283 | ---------- |
|
1283 | ---------- | |
1284 | index : n or (n1, n2) or None |
|
1284 | index : n or (n1, n2) or None | |
1285 | If n, then the last entries. If a tuple, then all in |
|
1285 | If n, then the last entries. If a tuple, then all in | |
1286 | range(n1, n2). If None, then all entries. Raises IndexError if |
|
1286 | range(n1, n2). If None, then all entries. Raises IndexError if | |
1287 | the format of index is incorrect. |
|
1287 | the format of index is incorrect. | |
1288 | raw : bool |
|
1288 | raw : bool | |
1289 | If True, return the raw input. |
|
1289 | If True, return the raw input. | |
1290 | output : bool |
|
1290 | output : bool | |
1291 | If True, then return the output as well. |
|
1291 | If True, then return the output as well. | |
1292 |
|
1292 | |||
1293 | Returns |
|
1293 | Returns | |
1294 | ------- |
|
1294 | ------- | |
1295 | If output is True, then return a dict of tuples, keyed by the prompt |
|
1295 | If output is True, then return a dict of tuples, keyed by the prompt | |
1296 | numbers and with values of (input, output). If output is False, then |
|
1296 | numbers and with values of (input, output). If output is False, then | |
1297 | a dict, keyed by the prompt number with the values of input. Raises |
|
1297 | a dict, keyed by the prompt number with the values of input. Raises | |
1298 | IndexError if no history is found. |
|
1298 | IndexError if no history is found. | |
1299 | """ |
|
1299 | """ | |
1300 | if raw: |
|
1300 | if raw: | |
1301 | input_hist = self.input_hist_raw |
|
1301 | input_hist = self.input_hist_raw | |
1302 | else: |
|
1302 | else: | |
1303 | input_hist = self.input_hist |
|
1303 | input_hist = self.input_hist | |
1304 | if output: |
|
1304 | if output: | |
1305 | output_hist = self.user_ns['Out'] |
|
1305 | output_hist = self.user_ns['Out'] | |
1306 | n = len(input_hist) |
|
1306 | n = len(input_hist) | |
1307 | if index is None: |
|
1307 | if index is None: | |
1308 | start=0; stop=n |
|
1308 | start=0; stop=n | |
1309 | elif isinstance(index, int): |
|
1309 | elif isinstance(index, int): | |
1310 | start=n-index; stop=n |
|
1310 | start=n-index; stop=n | |
1311 | elif isinstance(index, tuple) and len(index) == 2: |
|
1311 | elif isinstance(index, tuple) and len(index) == 2: | |
1312 | start=index[0]; stop=index[1] |
|
1312 | start=index[0]; stop=index[1] | |
1313 | else: |
|
1313 | else: | |
1314 | raise IndexError('Not a valid index for the input history: %r' |
|
1314 | raise IndexError('Not a valid index for the input history: %r' | |
1315 | % index) |
|
1315 | % index) | |
1316 | hist = {} |
|
1316 | hist = {} | |
1317 | for i in range(start, stop): |
|
1317 | for i in range(start, stop): | |
1318 | if output: |
|
1318 | if output: | |
1319 | hist[i] = (input_hist[i], output_hist.get(i)) |
|
1319 | hist[i] = (input_hist[i], output_hist.get(i)) | |
1320 | else: |
|
1320 | else: | |
1321 | hist[i] = input_hist[i] |
|
1321 | hist[i] = input_hist[i] | |
1322 | if len(hist)==0: |
|
1322 | if len(hist)==0: | |
1323 | raise IndexError('No history for range of indices: %r' % index) |
|
1323 | raise IndexError('No history for range of indices: %r' % index) | |
1324 | return hist |
|
1324 | return hist | |
1325 |
|
1325 | |||
1326 | #------------------------------------------------------------------------- |
|
1326 | #------------------------------------------------------------------------- | |
1327 | # Things related to exception handling and tracebacks (not debugging) |
|
1327 | # Things related to exception handling and tracebacks (not debugging) | |
1328 | #------------------------------------------------------------------------- |
|
1328 | #------------------------------------------------------------------------- | |
1329 |
|
1329 | |||
1330 | def init_traceback_handlers(self, custom_exceptions): |
|
1330 | def init_traceback_handlers(self, custom_exceptions): | |
1331 | # Syntax error handler. |
|
1331 | # Syntax error handler. | |
1332 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') |
|
1332 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor') | |
1333 |
|
1333 | |||
1334 | # The interactive one is initialized with an offset, meaning we always |
|
1334 | # The interactive one is initialized with an offset, meaning we always | |
1335 | # want to remove the topmost item in the traceback, which is our own |
|
1335 | # want to remove the topmost item in the traceback, which is our own | |
1336 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1336 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1337 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1337 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1338 | color_scheme='NoColor', |
|
1338 | color_scheme='NoColor', | |
1339 | tb_offset = 1) |
|
1339 | tb_offset = 1) | |
1340 |
|
1340 | |||
1341 | # The instance will store a pointer to the system-wide exception hook, |
|
1341 | # The instance will store a pointer to the system-wide exception hook, | |
1342 | # so that runtime code (such as magics) can access it. This is because |
|
1342 | # so that runtime code (such as magics) can access it. This is because | |
1343 | # during the read-eval loop, it may get temporarily overwritten. |
|
1343 | # during the read-eval loop, it may get temporarily overwritten. | |
1344 | self.sys_excepthook = sys.excepthook |
|
1344 | self.sys_excepthook = sys.excepthook | |
1345 |
|
1345 | |||
1346 | # and add any custom exception handlers the user may have specified |
|
1346 | # and add any custom exception handlers the user may have specified | |
1347 | self.set_custom_exc(*custom_exceptions) |
|
1347 | self.set_custom_exc(*custom_exceptions) | |
1348 |
|
1348 | |||
1349 | # Set the exception mode |
|
1349 | # Set the exception mode | |
1350 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1350 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1351 |
|
1351 | |||
1352 | def set_custom_exc(self, exc_tuple, handler): |
|
1352 | def set_custom_exc(self, exc_tuple, handler): | |
1353 | """set_custom_exc(exc_tuple,handler) |
|
1353 | """set_custom_exc(exc_tuple,handler) | |
1354 |
|
1354 | |||
1355 | Set a custom exception handler, which will be called if any of the |
|
1355 | Set a custom exception handler, which will be called if any of the | |
1356 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1356 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1357 | runcode() method. |
|
1357 | runcode() method. | |
1358 |
|
1358 | |||
1359 | Inputs: |
|
1359 | Inputs: | |
1360 |
|
1360 | |||
1361 | - exc_tuple: a *tuple* of valid exceptions to call the defined |
|
1361 | - exc_tuple: a *tuple* of valid exceptions to call the defined | |
1362 | handler for. It is very important that you use a tuple, and NOT A |
|
1362 | handler for. It is very important that you use a tuple, and NOT A | |
1363 | LIST here, because of the way Python's except statement works. If |
|
1363 | LIST here, because of the way Python's except statement works. If | |
1364 | you only want to trap a single exception, use a singleton tuple: |
|
1364 | you only want to trap a single exception, use a singleton tuple: | |
1365 |
|
1365 | |||
1366 | exc_tuple == (MyCustomException,) |
|
1366 | exc_tuple == (MyCustomException,) | |
1367 |
|
1367 | |||
1368 | - handler: this must be defined as a function with the following |
|
1368 | - handler: this must be defined as a function with the following | |
1369 | basic interface:: |
|
1369 | basic interface:: | |
1370 |
|
1370 | |||
1371 | def my_handler(self, etype, value, tb, tb_offset=None) |
|
1371 | def my_handler(self, etype, value, tb, tb_offset=None) | |
1372 | ... |
|
1372 | ... | |
1373 | # The return value must be |
|
1373 | # The return value must be | |
1374 | return structured_traceback |
|
1374 | return structured_traceback | |
1375 |
|
1375 | |||
1376 | This will be made into an instance method (via new.instancemethod) |
|
1376 | This will be made into an instance method (via new.instancemethod) | |
1377 | of IPython itself, and it will be called if any of the exceptions |
|
1377 | of IPython itself, and it will be called if any of the exceptions | |
1378 | listed in the exc_tuple are caught. If the handler is None, an |
|
1378 | listed in the exc_tuple are caught. If the handler is None, an | |
1379 | internal basic one is used, which just prints basic info. |
|
1379 | internal basic one is used, which just prints basic info. | |
1380 |
|
1380 | |||
1381 | WARNING: by putting in your own exception handler into IPython's main |
|
1381 | WARNING: by putting in your own exception handler into IPython's main | |
1382 | execution loop, you run a very good chance of nasty crashes. This |
|
1382 | execution loop, you run a very good chance of nasty crashes. This | |
1383 | facility should only be used if you really know what you are doing.""" |
|
1383 | facility should only be used if you really know what you are doing.""" | |
1384 |
|
1384 | |||
1385 | assert type(exc_tuple)==type(()) , \ |
|
1385 | assert type(exc_tuple)==type(()) , \ | |
1386 | "The custom exceptions must be given AS A TUPLE." |
|
1386 | "The custom exceptions must be given AS A TUPLE." | |
1387 |
|
1387 | |||
1388 | def dummy_handler(self,etype,value,tb): |
|
1388 | def dummy_handler(self,etype,value,tb): | |
1389 | print '*** Simple custom exception handler ***' |
|
1389 | print '*** Simple custom exception handler ***' | |
1390 | print 'Exception type :',etype |
|
1390 | print 'Exception type :',etype | |
1391 | print 'Exception value:',value |
|
1391 | print 'Exception value:',value | |
1392 | print 'Traceback :',tb |
|
1392 | print 'Traceback :',tb | |
1393 | print 'Source code :','\n'.join(self.buffer) |
|
1393 | print 'Source code :','\n'.join(self.buffer) | |
1394 |
|
1394 | |||
1395 | if handler is None: handler = dummy_handler |
|
1395 | if handler is None: handler = dummy_handler | |
1396 |
|
1396 | |||
1397 | self.CustomTB = new.instancemethod(handler,self,self.__class__) |
|
1397 | self.CustomTB = new.instancemethod(handler,self,self.__class__) | |
1398 | self.custom_exceptions = exc_tuple |
|
1398 | self.custom_exceptions = exc_tuple | |
1399 |
|
1399 | |||
1400 | def excepthook(self, etype, value, tb): |
|
1400 | def excepthook(self, etype, value, tb): | |
1401 | """One more defense for GUI apps that call sys.excepthook. |
|
1401 | """One more defense for GUI apps that call sys.excepthook. | |
1402 |
|
1402 | |||
1403 | GUI frameworks like wxPython trap exceptions and call |
|
1403 | GUI frameworks like wxPython trap exceptions and call | |
1404 | sys.excepthook themselves. I guess this is a feature that |
|
1404 | sys.excepthook themselves. I guess this is a feature that | |
1405 | enables them to keep running after exceptions that would |
|
1405 | enables them to keep running after exceptions that would | |
1406 | otherwise kill their mainloop. This is a bother for IPython |
|
1406 | otherwise kill their mainloop. This is a bother for IPython | |
1407 | which excepts to catch all of the program exceptions with a try: |
|
1407 | which excepts to catch all of the program exceptions with a try: | |
1408 | except: statement. |
|
1408 | except: statement. | |
1409 |
|
1409 | |||
1410 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1410 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1411 | any app directly invokes sys.excepthook, it will look to the user like |
|
1411 | any app directly invokes sys.excepthook, it will look to the user like | |
1412 | IPython crashed. In order to work around this, we can disable the |
|
1412 | IPython crashed. In order to work around this, we can disable the | |
1413 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1413 | CrashHandler and replace it with this excepthook instead, which prints a | |
1414 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1414 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1415 | call sys.excepthook will generate a regular-looking exception from |
|
1415 | call sys.excepthook will generate a regular-looking exception from | |
1416 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1416 | IPython, and the CrashHandler will only be triggered by real IPython | |
1417 | crashes. |
|
1417 | crashes. | |
1418 |
|
1418 | |||
1419 | This hook should be used sparingly, only in places which are not likely |
|
1419 | This hook should be used sparingly, only in places which are not likely | |
1420 | to be true IPython errors. |
|
1420 | to be true IPython errors. | |
1421 | """ |
|
1421 | """ | |
1422 | self.showtraceback((etype,value,tb),tb_offset=0) |
|
1422 | self.showtraceback((etype,value,tb),tb_offset=0) | |
1423 |
|
1423 | |||
1424 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, |
|
1424 | def showtraceback(self,exc_tuple = None,filename=None,tb_offset=None, | |
1425 | exception_only=False): |
|
1425 | exception_only=False): | |
1426 | """Display the exception that just occurred. |
|
1426 | """Display the exception that just occurred. | |
1427 |
|
1427 | |||
1428 | If nothing is known about the exception, this is the method which |
|
1428 | If nothing is known about the exception, this is the method which | |
1429 | should be used throughout the code for presenting user tracebacks, |
|
1429 | should be used throughout the code for presenting user tracebacks, | |
1430 | rather than directly invoking the InteractiveTB object. |
|
1430 | rather than directly invoking the InteractiveTB object. | |
1431 |
|
1431 | |||
1432 | A specific showsyntaxerror() also exists, but this method can take |
|
1432 | A specific showsyntaxerror() also exists, but this method can take | |
1433 | care of calling it if needed, so unless you are explicitly catching a |
|
1433 | care of calling it if needed, so unless you are explicitly catching a | |
1434 | SyntaxError exception, don't try to analyze the stack manually and |
|
1434 | SyntaxError exception, don't try to analyze the stack manually and | |
1435 | simply call this method.""" |
|
1435 | simply call this method.""" | |
1436 |
|
1436 | |||
1437 | try: |
|
1437 | try: | |
1438 | if exc_tuple is None: |
|
1438 | if exc_tuple is None: | |
1439 | etype, value, tb = sys.exc_info() |
|
1439 | etype, value, tb = sys.exc_info() | |
1440 | else: |
|
1440 | else: | |
1441 | etype, value, tb = exc_tuple |
|
1441 | etype, value, tb = exc_tuple | |
1442 |
|
1442 | |||
1443 | if etype is None: |
|
1443 | if etype is None: | |
1444 | if hasattr(sys, 'last_type'): |
|
1444 | if hasattr(sys, 'last_type'): | |
1445 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1445 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1446 | sys.last_traceback |
|
1446 | sys.last_traceback | |
1447 | else: |
|
1447 | else: | |
1448 | self.write_err('No traceback available to show.\n') |
|
1448 | self.write_err('No traceback available to show.\n') | |
1449 | return |
|
1449 | return | |
1450 |
|
1450 | |||
1451 | if etype is SyntaxError: |
|
1451 | if etype is SyntaxError: | |
1452 | # Though this won't be called by syntax errors in the input |
|
1452 | # Though this won't be called by syntax errors in the input | |
1453 | # line, there may be SyntaxError cases whith imported code. |
|
1453 | # line, there may be SyntaxError cases whith imported code. | |
1454 | self.showsyntaxerror(filename) |
|
1454 | self.showsyntaxerror(filename) | |
1455 | elif etype is UsageError: |
|
1455 | elif etype is UsageError: | |
1456 | print "UsageError:", value |
|
1456 | print "UsageError:", value | |
1457 | else: |
|
1457 | else: | |
1458 | # WARNING: these variables are somewhat deprecated and not |
|
1458 | # WARNING: these variables are somewhat deprecated and not | |
1459 | # necessarily safe to use in a threaded environment, but tools |
|
1459 | # necessarily safe to use in a threaded environment, but tools | |
1460 | # like pdb depend on their existence, so let's set them. If we |
|
1460 | # like pdb depend on their existence, so let's set them. If we | |
1461 | # find problems in the field, we'll need to revisit their use. |
|
1461 | # find problems in the field, we'll need to revisit their use. | |
1462 | sys.last_type = etype |
|
1462 | sys.last_type = etype | |
1463 | sys.last_value = value |
|
1463 | sys.last_value = value | |
1464 | sys.last_traceback = tb |
|
1464 | sys.last_traceback = tb | |
1465 |
|
1465 | |||
1466 | if etype in self.custom_exceptions: |
|
1466 | if etype in self.custom_exceptions: | |
1467 | # FIXME: Old custom traceback objects may just return a |
|
1467 | # FIXME: Old custom traceback objects may just return a | |
1468 | # string, in that case we just put it into a list |
|
1468 | # string, in that case we just put it into a list | |
1469 | stb = self.CustomTB(etype, value, tb, tb_offset) |
|
1469 | stb = self.CustomTB(etype, value, tb, tb_offset) | |
1470 | if isinstance(ctb, basestring): |
|
1470 | if isinstance(ctb, basestring): | |
1471 | stb = [stb] |
|
1471 | stb = [stb] | |
1472 | else: |
|
1472 | else: | |
1473 | if exception_only: |
|
1473 | if exception_only: | |
1474 | stb = ['An exception has occurred, use %tb to see ' |
|
1474 | stb = ['An exception has occurred, use %tb to see ' | |
1475 | 'the full traceback.\n'] |
|
1475 | 'the full traceback.\n'] | |
1476 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1476 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1477 | value)) |
|
1477 | value)) | |
1478 | else: |
|
1478 | else: | |
1479 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1479 | stb = self.InteractiveTB.structured_traceback(etype, | |
1480 | value, tb, tb_offset=tb_offset) |
|
1480 | value, tb, tb_offset=tb_offset) | |
1481 | # FIXME: the pdb calling should be done by us, not by |
|
1481 | # FIXME: the pdb calling should be done by us, not by | |
1482 | # the code computing the traceback. |
|
1482 | # the code computing the traceback. | |
1483 | if self.InteractiveTB.call_pdb: |
|
1483 | if self.InteractiveTB.call_pdb: | |
1484 | # pdb mucks up readline, fix it back |
|
1484 | # pdb mucks up readline, fix it back | |
1485 | self.set_readline_completer() |
|
1485 | self.set_readline_completer() | |
1486 |
|
1486 | |||
1487 | # Actually show the traceback |
|
1487 | # Actually show the traceback | |
1488 | self._showtraceback(etype, value, stb) |
|
1488 | self._showtraceback(etype, value, stb) | |
1489 |
|
1489 | |||
1490 | except KeyboardInterrupt: |
|
1490 | except KeyboardInterrupt: | |
1491 | self.write_err("\nKeyboardInterrupt\n") |
|
1491 | self.write_err("\nKeyboardInterrupt\n") | |
1492 |
|
1492 | |||
1493 | def _showtraceback(self, etype, evalue, stb): |
|
1493 | def _showtraceback(self, etype, evalue, stb): | |
1494 | """Actually show a traceback. |
|
1494 | """Actually show a traceback. | |
1495 |
|
1495 | |||
1496 | Subclasses may override this method to put the traceback on a different |
|
1496 | Subclasses may override this method to put the traceback on a different | |
1497 | place, like a side channel. |
|
1497 | place, like a side channel. | |
1498 | """ |
|
1498 | """ | |
1499 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) |
|
1499 | print >> io.Term.cout, self.InteractiveTB.stb2text(stb) | |
1500 |
|
1500 | |||
1501 | def showsyntaxerror(self, filename=None): |
|
1501 | def showsyntaxerror(self, filename=None): | |
1502 | """Display the syntax error that just occurred. |
|
1502 | """Display the syntax error that just occurred. | |
1503 |
|
1503 | |||
1504 | This doesn't display a stack trace because there isn't one. |
|
1504 | This doesn't display a stack trace because there isn't one. | |
1505 |
|
1505 | |||
1506 | If a filename is given, it is stuffed in the exception instead |
|
1506 | If a filename is given, it is stuffed in the exception instead | |
1507 | of what was there before (because Python's parser always uses |
|
1507 | of what was there before (because Python's parser always uses | |
1508 | "<string>" when reading from a string). |
|
1508 | "<string>" when reading from a string). | |
1509 | """ |
|
1509 | """ | |
1510 | etype, value, last_traceback = sys.exc_info() |
|
1510 | etype, value, last_traceback = sys.exc_info() | |
1511 |
|
1511 | |||
1512 | # See note about these variables in showtraceback() above |
|
1512 | # See note about these variables in showtraceback() above | |
1513 | sys.last_type = etype |
|
1513 | sys.last_type = etype | |
1514 | sys.last_value = value |
|
1514 | sys.last_value = value | |
1515 | sys.last_traceback = last_traceback |
|
1515 | sys.last_traceback = last_traceback | |
1516 |
|
1516 | |||
1517 | if filename and etype is SyntaxError: |
|
1517 | if filename and etype is SyntaxError: | |
1518 | # Work hard to stuff the correct filename in the exception |
|
1518 | # Work hard to stuff the correct filename in the exception | |
1519 | try: |
|
1519 | try: | |
1520 | msg, (dummy_filename, lineno, offset, line) = value |
|
1520 | msg, (dummy_filename, lineno, offset, line) = value | |
1521 | except: |
|
1521 | except: | |
1522 | # Not the format we expect; leave it alone |
|
1522 | # Not the format we expect; leave it alone | |
1523 | pass |
|
1523 | pass | |
1524 | else: |
|
1524 | else: | |
1525 | # Stuff in the right filename |
|
1525 | # Stuff in the right filename | |
1526 | try: |
|
1526 | try: | |
1527 | # Assume SyntaxError is a class exception |
|
1527 | # Assume SyntaxError is a class exception | |
1528 | value = SyntaxError(msg, (filename, lineno, offset, line)) |
|
1528 | value = SyntaxError(msg, (filename, lineno, offset, line)) | |
1529 | except: |
|
1529 | except: | |
1530 | # If that failed, assume SyntaxError is a string |
|
1530 | # If that failed, assume SyntaxError is a string | |
1531 | value = msg, (filename, lineno, offset, line) |
|
1531 | value = msg, (filename, lineno, offset, line) | |
1532 | stb = self.SyntaxTB.structured_traceback(etype, value, []) |
|
1532 | stb = self.SyntaxTB.structured_traceback(etype, value, []) | |
1533 | self._showtraceback(etype, value, stb) |
|
1533 | self._showtraceback(etype, value, stb) | |
1534 |
|
1534 | |||
1535 | #------------------------------------------------------------------------- |
|
1535 | #------------------------------------------------------------------------- | |
1536 | # Things related to readline |
|
1536 | # Things related to readline | |
1537 | #------------------------------------------------------------------------- |
|
1537 | #------------------------------------------------------------------------- | |
1538 |
|
1538 | |||
1539 | def init_readline(self): |
|
1539 | def init_readline(self): | |
1540 | """Command history completion/saving/reloading.""" |
|
1540 | """Command history completion/saving/reloading.""" | |
1541 |
|
1541 | |||
1542 | if self.readline_use: |
|
1542 | if self.readline_use: | |
1543 | import IPython.utils.rlineimpl as readline |
|
1543 | import IPython.utils.rlineimpl as readline | |
1544 |
|
1544 | |||
1545 | self.rl_next_input = None |
|
1545 | self.rl_next_input = None | |
1546 | self.rl_do_indent = False |
|
1546 | self.rl_do_indent = False | |
1547 |
|
1547 | |||
1548 | if not self.readline_use or not readline.have_readline: |
|
1548 | if not self.readline_use or not readline.have_readline: | |
1549 | self.has_readline = False |
|
1549 | self.has_readline = False | |
1550 | self.readline = None |
|
1550 | self.readline = None | |
1551 | # Set a number of methods that depend on readline to be no-op |
|
1551 | # Set a number of methods that depend on readline to be no-op | |
1552 | self.savehist = no_op |
|
1552 | self.savehist = no_op | |
1553 | self.reloadhist = no_op |
|
1553 | self.reloadhist = no_op | |
1554 | self.set_readline_completer = no_op |
|
1554 | self.set_readline_completer = no_op | |
1555 | self.set_custom_completer = no_op |
|
1555 | self.set_custom_completer = no_op | |
1556 | self.set_completer_frame = no_op |
|
1556 | self.set_completer_frame = no_op | |
1557 | warn('Readline services not available or not loaded.') |
|
1557 | warn('Readline services not available or not loaded.') | |
1558 | else: |
|
1558 | else: | |
1559 | self.has_readline = True |
|
1559 | self.has_readline = True | |
1560 | self.readline = readline |
|
1560 | self.readline = readline | |
1561 | sys.modules['readline'] = readline |
|
1561 | sys.modules['readline'] = readline | |
1562 |
|
1562 | |||
1563 | # Platform-specific configuration |
|
1563 | # Platform-specific configuration | |
1564 | if os.name == 'nt': |
|
1564 | if os.name == 'nt': | |
1565 | # FIXME - check with Frederick to see if we can harmonize |
|
1565 | # FIXME - check with Frederick to see if we can harmonize | |
1566 | # naming conventions with pyreadline to avoid this |
|
1566 | # naming conventions with pyreadline to avoid this | |
1567 | # platform-dependent check |
|
1567 | # platform-dependent check | |
1568 | self.readline_startup_hook = readline.set_pre_input_hook |
|
1568 | self.readline_startup_hook = readline.set_pre_input_hook | |
1569 | else: |
|
1569 | else: | |
1570 | self.readline_startup_hook = readline.set_startup_hook |
|
1570 | self.readline_startup_hook = readline.set_startup_hook | |
1571 |
|
1571 | |||
1572 | # Load user's initrc file (readline config) |
|
1572 | # Load user's initrc file (readline config) | |
1573 | # Or if libedit is used, load editrc. |
|
1573 | # Or if libedit is used, load editrc. | |
1574 | inputrc_name = os.environ.get('INPUTRC') |
|
1574 | inputrc_name = os.environ.get('INPUTRC') | |
1575 | if inputrc_name is None: |
|
1575 | if inputrc_name is None: | |
1576 | home_dir = get_home_dir() |
|
1576 | home_dir = get_home_dir() | |
1577 | if home_dir is not None: |
|
1577 | if home_dir is not None: | |
1578 | inputrc_name = '.inputrc' |
|
1578 | inputrc_name = '.inputrc' | |
1579 | if readline.uses_libedit: |
|
1579 | if readline.uses_libedit: | |
1580 | inputrc_name = '.editrc' |
|
1580 | inputrc_name = '.editrc' | |
1581 | inputrc_name = os.path.join(home_dir, inputrc_name) |
|
1581 | inputrc_name = os.path.join(home_dir, inputrc_name) | |
1582 | if os.path.isfile(inputrc_name): |
|
1582 | if os.path.isfile(inputrc_name): | |
1583 | try: |
|
1583 | try: | |
1584 | readline.read_init_file(inputrc_name) |
|
1584 | readline.read_init_file(inputrc_name) | |
1585 | except: |
|
1585 | except: | |
1586 | warn('Problems reading readline initialization file <%s>' |
|
1586 | warn('Problems reading readline initialization file <%s>' | |
1587 | % inputrc_name) |
|
1587 | % inputrc_name) | |
1588 |
|
1588 | |||
1589 | # Configure readline according to user's prefs |
|
1589 | # Configure readline according to user's prefs | |
1590 | # This is only done if GNU readline is being used. If libedit |
|
1590 | # This is only done if GNU readline is being used. If libedit | |
1591 | # is being used (as on Leopard) the readline config is |
|
1591 | # is being used (as on Leopard) the readline config is | |
1592 | # not run as the syntax for libedit is different. |
|
1592 | # not run as the syntax for libedit is different. | |
1593 | if not readline.uses_libedit: |
|
1593 | if not readline.uses_libedit: | |
1594 | for rlcommand in self.readline_parse_and_bind: |
|
1594 | for rlcommand in self.readline_parse_and_bind: | |
1595 | #print "loading rl:",rlcommand # dbg |
|
1595 | #print "loading rl:",rlcommand # dbg | |
1596 | readline.parse_and_bind(rlcommand) |
|
1596 | readline.parse_and_bind(rlcommand) | |
1597 |
|
1597 | |||
1598 | # Remove some chars from the delimiters list. If we encounter |
|
1598 | # Remove some chars from the delimiters list. If we encounter | |
1599 | # unicode chars, discard them. |
|
1599 | # unicode chars, discard them. | |
1600 | delims = readline.get_completer_delims().encode("ascii", "ignore") |
|
1600 | delims = readline.get_completer_delims().encode("ascii", "ignore") | |
1601 | delims = delims.translate(string._idmap, |
|
1601 | delims = delims.translate(string._idmap, | |
1602 | self.readline_remove_delims) |
|
1602 | self.readline_remove_delims) | |
1603 | delims = delims.replace(ESC_MAGIC, '') |
|
1603 | delims = delims.replace(ESC_MAGIC, '') | |
1604 | readline.set_completer_delims(delims) |
|
1604 | readline.set_completer_delims(delims) | |
1605 | # otherwise we end up with a monster history after a while: |
|
1605 | # otherwise we end up with a monster history after a while: | |
1606 | readline.set_history_length(1000) |
|
1606 | readline.set_history_length(1000) | |
1607 | try: |
|
1607 | try: | |
1608 | #print '*** Reading readline history' # dbg |
|
1608 | #print '*** Reading readline history' # dbg | |
1609 | readline.read_history_file(self.histfile) |
|
1609 | readline.read_history_file(self.histfile) | |
1610 | except IOError: |
|
1610 | except IOError: | |
1611 | pass # It doesn't exist yet. |
|
1611 | pass # It doesn't exist yet. | |
1612 |
|
1612 | |||
1613 | # If we have readline, we want our history saved upon ipython |
|
1613 | # If we have readline, we want our history saved upon ipython | |
1614 | # exiting. |
|
1614 | # exiting. | |
1615 | atexit.register(self.savehist) |
|
1615 | atexit.register(self.savehist) | |
1616 |
|
1616 | |||
1617 | # Configure auto-indent for all platforms |
|
1617 | # Configure auto-indent for all platforms | |
1618 | self.set_autoindent(self.autoindent) |
|
1618 | self.set_autoindent(self.autoindent) | |
1619 |
|
1619 | |||
1620 | def set_next_input(self, s): |
|
1620 | def set_next_input(self, s): | |
1621 | """ Sets the 'default' input string for the next command line. |
|
1621 | """ Sets the 'default' input string for the next command line. | |
1622 |
|
1622 | |||
1623 | Requires readline. |
|
1623 | Requires readline. | |
1624 |
|
1624 | |||
1625 | Example: |
|
1625 | Example: | |
1626 |
|
1626 | |||
1627 | [D:\ipython]|1> _ip.set_next_input("Hello Word") |
|
1627 | [D:\ipython]|1> _ip.set_next_input("Hello Word") | |
1628 | [D:\ipython]|2> Hello Word_ # cursor is here |
|
1628 | [D:\ipython]|2> Hello Word_ # cursor is here | |
1629 | """ |
|
1629 | """ | |
1630 |
|
1630 | |||
1631 | self.rl_next_input = s |
|
1631 | self.rl_next_input = s | |
1632 |
|
1632 | |||
1633 | # Maybe move this to the terminal subclass? |
|
1633 | # Maybe move this to the terminal subclass? | |
1634 | def pre_readline(self): |
|
1634 | def pre_readline(self): | |
1635 | """readline hook to be used at the start of each line. |
|
1635 | """readline hook to be used at the start of each line. | |
1636 |
|
1636 | |||
1637 | Currently it handles auto-indent only.""" |
|
1637 | Currently it handles auto-indent only.""" | |
1638 |
|
1638 | |||
1639 | if self.rl_do_indent: |
|
1639 | if self.rl_do_indent: | |
1640 | self.readline.insert_text(self._indent_current_str()) |
|
1640 | self.readline.insert_text(self._indent_current_str()) | |
1641 | if self.rl_next_input is not None: |
|
1641 | if self.rl_next_input is not None: | |
1642 | self.readline.insert_text(self.rl_next_input) |
|
1642 | self.readline.insert_text(self.rl_next_input) | |
1643 | self.rl_next_input = None |
|
1643 | self.rl_next_input = None | |
1644 |
|
1644 | |||
1645 | def _indent_current_str(self): |
|
1645 | def _indent_current_str(self): | |
1646 | """return the current level of indentation as a string""" |
|
1646 | """return the current level of indentation as a string""" | |
1647 | return self.indent_current_nsp * ' ' |
|
1647 | return self.indent_current_nsp * ' ' | |
1648 |
|
1648 | |||
1649 | #------------------------------------------------------------------------- |
|
1649 | #------------------------------------------------------------------------- | |
1650 | # Things related to text completion |
|
1650 | # Things related to text completion | |
1651 | #------------------------------------------------------------------------- |
|
1651 | #------------------------------------------------------------------------- | |
1652 |
|
1652 | |||
1653 | def init_completer(self): |
|
1653 | def init_completer(self): | |
1654 | """Initialize the completion machinery. |
|
1654 | """Initialize the completion machinery. | |
1655 |
|
1655 | |||
1656 | This creates completion machinery that can be used by client code, |
|
1656 | This creates completion machinery that can be used by client code, | |
1657 | either interactively in-process (typically triggered by the readline |
|
1657 | either interactively in-process (typically triggered by the readline | |
1658 | library), programatically (such as in test suites) or out-of-prcess |
|
1658 | library), programatically (such as in test suites) or out-of-prcess | |
1659 | (typically over the network by remote frontends). |
|
1659 | (typically over the network by remote frontends). | |
1660 | """ |
|
1660 | """ | |
1661 | from IPython.core.completer import IPCompleter |
|
1661 | from IPython.core.completer import IPCompleter | |
1662 | from IPython.core.completerlib import (module_completer, |
|
1662 | from IPython.core.completerlib import (module_completer, | |
1663 | magic_run_completer, cd_completer) |
|
1663 | magic_run_completer, cd_completer) | |
1664 |
|
1664 | |||
1665 | self.Completer = IPCompleter(self, |
|
1665 | self.Completer = IPCompleter(self, | |
1666 | self.user_ns, |
|
1666 | self.user_ns, | |
1667 | self.user_global_ns, |
|
1667 | self.user_global_ns, | |
1668 | self.readline_omit__names, |
|
1668 | self.readline_omit__names, | |
1669 | self.alias_manager.alias_table, |
|
1669 | self.alias_manager.alias_table, | |
1670 | self.has_readline) |
|
1670 | self.has_readline) | |
1671 |
|
1671 | |||
1672 | # Add custom completers to the basic ones built into IPCompleter |
|
1672 | # Add custom completers to the basic ones built into IPCompleter | |
1673 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1673 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1674 | self.strdispatchers['complete_command'] = sdisp |
|
1674 | self.strdispatchers['complete_command'] = sdisp | |
1675 | self.Completer.custom_completers = sdisp |
|
1675 | self.Completer.custom_completers = sdisp | |
1676 |
|
1676 | |||
1677 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1677 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1678 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1678 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1679 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1679 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1680 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
1680 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1681 |
|
1681 | |||
1682 | # Only configure readline if we truly are using readline. IPython can |
|
1682 | # Only configure readline if we truly are using readline. IPython can | |
1683 | # do tab-completion over the network, in GUIs, etc, where readline |
|
1683 | # do tab-completion over the network, in GUIs, etc, where readline | |
1684 | # itself may be absent |
|
1684 | # itself may be absent | |
1685 | if self.has_readline: |
|
1685 | if self.has_readline: | |
1686 | self.set_readline_completer() |
|
1686 | self.set_readline_completer() | |
1687 |
|
1687 | |||
1688 | def complete(self, text, line=None, cursor_pos=None): |
|
1688 | def complete(self, text, line=None, cursor_pos=None): | |
1689 | """Return the completed text and a list of completions. |
|
1689 | """Return the completed text and a list of completions. | |
1690 |
|
1690 | |||
1691 | Parameters |
|
1691 | Parameters | |
1692 | ---------- |
|
1692 | ---------- | |
1693 |
|
1693 | |||
1694 | text : string |
|
1694 | text : string | |
1695 | A string of text to be completed on. It can be given as empty and |
|
1695 | A string of text to be completed on. It can be given as empty and | |
1696 | instead a line/position pair are given. In this case, the |
|
1696 | instead a line/position pair are given. In this case, the | |
1697 | completer itself will split the line like readline does. |
|
1697 | completer itself will split the line like readline does. | |
1698 |
|
1698 | |||
1699 | line : string, optional |
|
1699 | line : string, optional | |
1700 | The complete line that text is part of. |
|
1700 | The complete line that text is part of. | |
1701 |
|
1701 | |||
1702 | cursor_pos : int, optional |
|
1702 | cursor_pos : int, optional | |
1703 | The position of the cursor on the input line. |
|
1703 | The position of the cursor on the input line. | |
1704 |
|
1704 | |||
1705 | Returns |
|
1705 | Returns | |
1706 | ------- |
|
1706 | ------- | |
1707 | text : string |
|
1707 | text : string | |
1708 | The actual text that was completed. |
|
1708 | The actual text that was completed. | |
1709 |
|
1709 | |||
1710 | matches : list |
|
1710 | matches : list | |
1711 | A sorted list with all possible completions. |
|
1711 | A sorted list with all possible completions. | |
1712 |
|
1712 | |||
1713 | The optional arguments allow the completion to take more context into |
|
1713 | The optional arguments allow the completion to take more context into | |
1714 | account, and are part of the low-level completion API. |
|
1714 | account, and are part of the low-level completion API. | |
1715 |
|
1715 | |||
1716 | This is a wrapper around the completion mechanism, similar to what |
|
1716 | This is a wrapper around the completion mechanism, similar to what | |
1717 | readline does at the command line when the TAB key is hit. By |
|
1717 | readline does at the command line when the TAB key is hit. By | |
1718 | exposing it as a method, it can be used by other non-readline |
|
1718 | exposing it as a method, it can be used by other non-readline | |
1719 | environments (such as GUIs) for text completion. |
|
1719 | environments (such as GUIs) for text completion. | |
1720 |
|
1720 | |||
1721 | Simple usage example: |
|
1721 | Simple usage example: | |
1722 |
|
1722 | |||
1723 | In [1]: x = 'hello' |
|
1723 | In [1]: x = 'hello' | |
1724 |
|
1724 | |||
1725 | In [2]: _ip.complete('x.l') |
|
1725 | In [2]: _ip.complete('x.l') | |
1726 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
1726 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
1727 | """ |
|
1727 | """ | |
1728 |
|
1728 | |||
1729 | # Inject names into __builtin__ so we can complete on the added names. |
|
1729 | # Inject names into __builtin__ so we can complete on the added names. | |
1730 | with self.builtin_trap: |
|
1730 | with self.builtin_trap: | |
1731 | return self.Completer.complete(text, line, cursor_pos) |
|
1731 | return self.Completer.complete(text, line, cursor_pos) | |
1732 |
|
1732 | |||
1733 | def set_custom_completer(self, completer, pos=0): |
|
1733 | def set_custom_completer(self, completer, pos=0): | |
1734 | """Adds a new custom completer function. |
|
1734 | """Adds a new custom completer function. | |
1735 |
|
1735 | |||
1736 | The position argument (defaults to 0) is the index in the completers |
|
1736 | The position argument (defaults to 0) is the index in the completers | |
1737 | list where you want the completer to be inserted.""" |
|
1737 | list where you want the completer to be inserted.""" | |
1738 |
|
1738 | |||
1739 | newcomp = new.instancemethod(completer,self.Completer, |
|
1739 | newcomp = new.instancemethod(completer,self.Completer, | |
1740 | self.Completer.__class__) |
|
1740 | self.Completer.__class__) | |
1741 | self.Completer.matchers.insert(pos,newcomp) |
|
1741 | self.Completer.matchers.insert(pos,newcomp) | |
1742 |
|
1742 | |||
1743 | def set_readline_completer(self): |
|
1743 | def set_readline_completer(self): | |
1744 | """Reset readline's completer to be our own.""" |
|
1744 | """Reset readline's completer to be our own.""" | |
1745 | self.readline.set_completer(self.Completer.rlcomplete) |
|
1745 | self.readline.set_completer(self.Completer.rlcomplete) | |
1746 |
|
1746 | |||
1747 | def set_completer_frame(self, frame=None): |
|
1747 | def set_completer_frame(self, frame=None): | |
1748 | """Set the frame of the completer.""" |
|
1748 | """Set the frame of the completer.""" | |
1749 | if frame: |
|
1749 | if frame: | |
1750 | self.Completer.namespace = frame.f_locals |
|
1750 | self.Completer.namespace = frame.f_locals | |
1751 | self.Completer.global_namespace = frame.f_globals |
|
1751 | self.Completer.global_namespace = frame.f_globals | |
1752 | else: |
|
1752 | else: | |
1753 | self.Completer.namespace = self.user_ns |
|
1753 | self.Completer.namespace = self.user_ns | |
1754 | self.Completer.global_namespace = self.user_global_ns |
|
1754 | self.Completer.global_namespace = self.user_global_ns | |
1755 |
|
1755 | |||
1756 | #------------------------------------------------------------------------- |
|
1756 | #------------------------------------------------------------------------- | |
1757 | # Things related to magics |
|
1757 | # Things related to magics | |
1758 | #------------------------------------------------------------------------- |
|
1758 | #------------------------------------------------------------------------- | |
1759 |
|
1759 | |||
1760 | def init_magics(self): |
|
1760 | def init_magics(self): | |
1761 | # FIXME: Move the color initialization to the DisplayHook, which |
|
1761 | # FIXME: Move the color initialization to the DisplayHook, which | |
1762 | # should be split into a prompt manager and displayhook. We probably |
|
1762 | # should be split into a prompt manager and displayhook. We probably | |
1763 | # even need a centralize colors management object. |
|
1763 | # even need a centralize colors management object. | |
1764 | self.magic_colors(self.colors) |
|
1764 | self.magic_colors(self.colors) | |
1765 | # History was moved to a separate module |
|
1765 | # History was moved to a separate module | |
1766 | from . import history |
|
1766 | from . import history | |
1767 | history.init_ipython(self) |
|
1767 | history.init_ipython(self) | |
1768 |
|
1768 | |||
1769 | def magic(self,arg_s): |
|
1769 | def magic(self,arg_s): | |
1770 | """Call a magic function by name. |
|
1770 | """Call a magic function by name. | |
1771 |
|
1771 | |||
1772 | Input: a string containing the name of the magic function to call and |
|
1772 | Input: a string containing the name of the magic function to call and | |
1773 | any additional arguments to be passed to the magic. |
|
1773 | any additional arguments to be passed to the magic. | |
1774 |
|
1774 | |||
1775 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
1775 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
1776 | prompt: |
|
1776 | prompt: | |
1777 |
|
1777 | |||
1778 | In[1]: %name -opt foo bar |
|
1778 | In[1]: %name -opt foo bar | |
1779 |
|
1779 | |||
1780 | To call a magic without arguments, simply use magic('name'). |
|
1780 | To call a magic without arguments, simply use magic('name'). | |
1781 |
|
1781 | |||
1782 | This provides a proper Python function to call IPython's magics in any |
|
1782 | This provides a proper Python function to call IPython's magics in any | |
1783 | valid Python code you can type at the interpreter, including loops and |
|
1783 | valid Python code you can type at the interpreter, including loops and | |
1784 | compound statements. |
|
1784 | compound statements. | |
1785 | """ |
|
1785 | """ | |
1786 | args = arg_s.split(' ',1) |
|
1786 | args = arg_s.split(' ',1) | |
1787 | magic_name = args[0] |
|
1787 | magic_name = args[0] | |
1788 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
1788 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
1789 |
|
1789 | |||
1790 | try: |
|
1790 | try: | |
1791 | magic_args = args[1] |
|
1791 | magic_args = args[1] | |
1792 | except IndexError: |
|
1792 | except IndexError: | |
1793 | magic_args = '' |
|
1793 | magic_args = '' | |
1794 | fn = getattr(self,'magic_'+magic_name,None) |
|
1794 | fn = getattr(self,'magic_'+magic_name,None) | |
1795 | if fn is None: |
|
1795 | if fn is None: | |
1796 | error("Magic function `%s` not found." % magic_name) |
|
1796 | error("Magic function `%s` not found." % magic_name) | |
1797 | else: |
|
1797 | else: | |
1798 | magic_args = self.var_expand(magic_args,1) |
|
1798 | magic_args = self.var_expand(magic_args,1) | |
1799 | with nested(self.builtin_trap,): |
|
1799 | with nested(self.builtin_trap,): | |
1800 | result = fn(magic_args) |
|
1800 | result = fn(magic_args) | |
1801 | return result |
|
1801 | return result | |
1802 |
|
1802 | |||
1803 | def define_magic(self, magicname, func): |
|
1803 | def define_magic(self, magicname, func): | |
1804 | """Expose own function as magic function for ipython |
|
1804 | """Expose own function as magic function for ipython | |
1805 |
|
1805 | |||
1806 | def foo_impl(self,parameter_s=''): |
|
1806 | def foo_impl(self,parameter_s=''): | |
1807 | 'My very own magic!. (Use docstrings, IPython reads them).' |
|
1807 | 'My very own magic!. (Use docstrings, IPython reads them).' | |
1808 | print 'Magic function. Passed parameter is between < >:' |
|
1808 | print 'Magic function. Passed parameter is between < >:' | |
1809 | print '<%s>' % parameter_s |
|
1809 | print '<%s>' % parameter_s | |
1810 | print 'The self object is:',self |
|
1810 | print 'The self object is:',self | |
1811 |
|
1811 | |||
1812 | self.define_magic('foo',foo_impl) |
|
1812 | self.define_magic('foo',foo_impl) | |
1813 | """ |
|
1813 | """ | |
1814 |
|
1814 | |||
1815 | import new |
|
1815 | import new | |
1816 | im = new.instancemethod(func,self, self.__class__) |
|
1816 | im = new.instancemethod(func,self, self.__class__) | |
1817 | old = getattr(self, "magic_" + magicname, None) |
|
1817 | old = getattr(self, "magic_" + magicname, None) | |
1818 | setattr(self, "magic_" + magicname, im) |
|
1818 | setattr(self, "magic_" + magicname, im) | |
1819 | return old |
|
1819 | return old | |
1820 |
|
1820 | |||
1821 | #------------------------------------------------------------------------- |
|
1821 | #------------------------------------------------------------------------- | |
1822 | # Things related to macros |
|
1822 | # Things related to macros | |
1823 | #------------------------------------------------------------------------- |
|
1823 | #------------------------------------------------------------------------- | |
1824 |
|
1824 | |||
1825 | def define_macro(self, name, themacro): |
|
1825 | def define_macro(self, name, themacro): | |
1826 | """Define a new macro |
|
1826 | """Define a new macro | |
1827 |
|
1827 | |||
1828 | Parameters |
|
1828 | Parameters | |
1829 | ---------- |
|
1829 | ---------- | |
1830 | name : str |
|
1830 | name : str | |
1831 | The name of the macro. |
|
1831 | The name of the macro. | |
1832 | themacro : str or Macro |
|
1832 | themacro : str or Macro | |
1833 | The action to do upon invoking the macro. If a string, a new |
|
1833 | The action to do upon invoking the macro. If a string, a new | |
1834 | Macro object is created by passing the string to it. |
|
1834 | Macro object is created by passing the string to it. | |
1835 | """ |
|
1835 | """ | |
1836 |
|
1836 | |||
1837 | from IPython.core import macro |
|
1837 | from IPython.core import macro | |
1838 |
|
1838 | |||
1839 | if isinstance(themacro, basestring): |
|
1839 | if isinstance(themacro, basestring): | |
1840 | themacro = macro.Macro(themacro) |
|
1840 | themacro = macro.Macro(themacro) | |
1841 | if not isinstance(themacro, macro.Macro): |
|
1841 | if not isinstance(themacro, macro.Macro): | |
1842 | raise ValueError('A macro must be a string or a Macro instance.') |
|
1842 | raise ValueError('A macro must be a string or a Macro instance.') | |
1843 | self.user_ns[name] = themacro |
|
1843 | self.user_ns[name] = themacro | |
1844 |
|
1844 | |||
1845 | #------------------------------------------------------------------------- |
|
1845 | #------------------------------------------------------------------------- | |
1846 | # Things related to the running of system commands |
|
1846 | # Things related to the running of system commands | |
1847 | #------------------------------------------------------------------------- |
|
1847 | #------------------------------------------------------------------------- | |
1848 |
|
1848 | |||
1849 | def system(self, cmd): |
|
1849 | def system(self, cmd): | |
1850 |
"""Call the given cmd in a subprocess. |
|
1850 | """Call the given cmd in a subprocess. | |
|
1851 | ||||
|
1852 | Parameters | |||
|
1853 | ---------- | |||
|
1854 | cmd : str | |||
|
1855 | Command to execute (can not end in '&', as bacground processes are | |||
|
1856 | not supported. | |||
|
1857 | """ | |||
1851 | # We do not support backgrounding processes because we either use |
|
1858 | # We do not support backgrounding processes because we either use | |
1852 | # pexpect or pipes to read from. Users can always just call |
|
1859 | # pexpect or pipes to read from. Users can always just call | |
1853 | # os.system() if they really want a background process. |
|
1860 | # os.system() if they really want a background process. | |
1854 | if cmd.endswith('&'): |
|
1861 | if cmd.endswith('&'): | |
1855 | raise OSError("Background processes not supported.") |
|
1862 | raise OSError("Background processes not supported.") | |
1856 |
|
1863 | |||
1857 | return system(self.var_expand(cmd, depth=2)) |
|
1864 | return system(self.var_expand(cmd, depth=2)) | |
1858 |
|
1865 | |||
1859 | def getoutput(self, cmd): |
|
1866 | def getoutput(self, cmd, split=True): | |
1860 |
"""Get output (possibly including stderr) from a subprocess. |
|
1867 | """Get output (possibly including stderr) from a subprocess. | |
|
1868 | ||||
|
1869 | Parameters | |||
|
1870 | ---------- | |||
|
1871 | cmd : str | |||
|
1872 | Command to execute (can not end in '&', as bacground processes are | |||
|
1873 | not supported. | |||
|
1874 | split : bool, optional | |||
|
1875 | ||||
|
1876 | If True, split the output into an IPython SList. Otherwise, an | |||
|
1877 | IPython LSString is returned. These are objects similar to normal | |||
|
1878 | lists and strings, with a few convenience attributes for easier | |||
|
1879 | manipulation of line-based output. You can use '?' on them for | |||
|
1880 | details. | |||
|
1881 | """ | |||
1861 | if cmd.endswith('&'): |
|
1882 | if cmd.endswith('&'): | |
1862 | raise OSError("Background processes not supported.") |
|
1883 | raise OSError("Background processes not supported.") | |
1863 |
|
|
1884 | out = getoutput(self.var_expand(cmd, depth=2)) | |
|
1885 | if split: | |||
|
1886 | out = SList(out.splitlines()) | |||
|
1887 | else: | |||
|
1888 | out = LSString(out) | |||
|
1889 | return out | |||
1864 |
|
1890 | |||
1865 | #------------------------------------------------------------------------- |
|
1891 | #------------------------------------------------------------------------- | |
1866 | # Things related to aliases |
|
1892 | # Things related to aliases | |
1867 | #------------------------------------------------------------------------- |
|
1893 | #------------------------------------------------------------------------- | |
1868 |
|
1894 | |||
1869 | def init_alias(self): |
|
1895 | def init_alias(self): | |
1870 | self.alias_manager = AliasManager(shell=self, config=self.config) |
|
1896 | self.alias_manager = AliasManager(shell=self, config=self.config) | |
1871 | self.ns_table['alias'] = self.alias_manager.alias_table, |
|
1897 | self.ns_table['alias'] = self.alias_manager.alias_table, | |
1872 |
|
1898 | |||
1873 | #------------------------------------------------------------------------- |
|
1899 | #------------------------------------------------------------------------- | |
1874 | # Things related to extensions and plugins |
|
1900 | # Things related to extensions and plugins | |
1875 | #------------------------------------------------------------------------- |
|
1901 | #------------------------------------------------------------------------- | |
1876 |
|
1902 | |||
1877 | def init_extension_manager(self): |
|
1903 | def init_extension_manager(self): | |
1878 | self.extension_manager = ExtensionManager(shell=self, config=self.config) |
|
1904 | self.extension_manager = ExtensionManager(shell=self, config=self.config) | |
1879 |
|
1905 | |||
1880 | def init_plugin_manager(self): |
|
1906 | def init_plugin_manager(self): | |
1881 | self.plugin_manager = PluginManager(config=self.config) |
|
1907 | self.plugin_manager = PluginManager(config=self.config) | |
1882 |
|
1908 | |||
1883 | #------------------------------------------------------------------------- |
|
1909 | #------------------------------------------------------------------------- | |
1884 | # Things related to payloads |
|
1910 | # Things related to payloads | |
1885 | #------------------------------------------------------------------------- |
|
1911 | #------------------------------------------------------------------------- | |
1886 |
|
1912 | |||
1887 | def init_payload(self): |
|
1913 | def init_payload(self): | |
1888 | self.payload_manager = PayloadManager(config=self.config) |
|
1914 | self.payload_manager = PayloadManager(config=self.config) | |
1889 |
|
1915 | |||
1890 | #------------------------------------------------------------------------- |
|
1916 | #------------------------------------------------------------------------- | |
1891 | # Things related to the prefilter |
|
1917 | # Things related to the prefilter | |
1892 | #------------------------------------------------------------------------- |
|
1918 | #------------------------------------------------------------------------- | |
1893 |
|
1919 | |||
1894 | def init_prefilter(self): |
|
1920 | def init_prefilter(self): | |
1895 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) |
|
1921 | self.prefilter_manager = PrefilterManager(shell=self, config=self.config) | |
1896 | # Ultimately this will be refactored in the new interpreter code, but |
|
1922 | # Ultimately this will be refactored in the new interpreter code, but | |
1897 | # for now, we should expose the main prefilter method (there's legacy |
|
1923 | # for now, we should expose the main prefilter method (there's legacy | |
1898 | # code out there that may rely on this). |
|
1924 | # code out there that may rely on this). | |
1899 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
1925 | self.prefilter = self.prefilter_manager.prefilter_lines | |
1900 |
|
1926 | |||
1901 |
|
1927 | |||
1902 | def auto_rewrite_input(self, cmd): |
|
1928 | def auto_rewrite_input(self, cmd): | |
1903 | """Print to the screen the rewritten form of the user's command. |
|
1929 | """Print to the screen the rewritten form of the user's command. | |
1904 |
|
1930 | |||
1905 | This shows visual feedback by rewriting input lines that cause |
|
1931 | This shows visual feedback by rewriting input lines that cause | |
1906 | automatic calling to kick in, like:: |
|
1932 | automatic calling to kick in, like:: | |
1907 |
|
1933 | |||
1908 | /f x |
|
1934 | /f x | |
1909 |
|
1935 | |||
1910 | into:: |
|
1936 | into:: | |
1911 |
|
1937 | |||
1912 | ------> f(x) |
|
1938 | ------> f(x) | |
1913 |
|
1939 | |||
1914 | after the user's input prompt. This helps the user understand that the |
|
1940 | after the user's input prompt. This helps the user understand that the | |
1915 | input line was transformed automatically by IPython. |
|
1941 | input line was transformed automatically by IPython. | |
1916 | """ |
|
1942 | """ | |
1917 | rw = self.displayhook.prompt1.auto_rewrite() + cmd |
|
1943 | rw = self.displayhook.prompt1.auto_rewrite() + cmd | |
1918 |
|
1944 | |||
1919 | try: |
|
1945 | try: | |
1920 | # plain ascii works better w/ pyreadline, on some machines, so |
|
1946 | # plain ascii works better w/ pyreadline, on some machines, so | |
1921 | # we use it and only print uncolored rewrite if we have unicode |
|
1947 | # we use it and only print uncolored rewrite if we have unicode | |
1922 | rw = str(rw) |
|
1948 | rw = str(rw) | |
1923 | print >> IPython.utils.io.Term.cout, rw |
|
1949 | print >> IPython.utils.io.Term.cout, rw | |
1924 | except UnicodeEncodeError: |
|
1950 | except UnicodeEncodeError: | |
1925 | print "------> " + cmd |
|
1951 | print "------> " + cmd | |
1926 |
|
1952 | |||
1927 | #------------------------------------------------------------------------- |
|
1953 | #------------------------------------------------------------------------- | |
1928 | # Things related to extracting values/expressions from kernel and user_ns |
|
1954 | # Things related to extracting values/expressions from kernel and user_ns | |
1929 | #------------------------------------------------------------------------- |
|
1955 | #------------------------------------------------------------------------- | |
1930 |
|
1956 | |||
1931 | def _simple_error(self): |
|
1957 | def _simple_error(self): | |
1932 | etype, value = sys.exc_info()[:2] |
|
1958 | etype, value = sys.exc_info()[:2] | |
1933 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) |
|
1959 | return u'[ERROR] {e.__name__}: {v}'.format(e=etype, v=value) | |
1934 |
|
1960 | |||
1935 | def get_user_variables(self, names): |
|
1961 | def get_user_variables(self, names): | |
1936 | """Get a list of variable names from the user's namespace. |
|
1962 | """Get a list of variable names from the user's namespace. | |
1937 |
|
1963 | |||
1938 | The return value is a dict with the repr() of each value. |
|
1964 | The return value is a dict with the repr() of each value. | |
1939 | """ |
|
1965 | """ | |
1940 | out = {} |
|
1966 | out = {} | |
1941 | user_ns = self.user_ns |
|
1967 | user_ns = self.user_ns | |
1942 | for varname in names: |
|
1968 | for varname in names: | |
1943 | try: |
|
1969 | try: | |
1944 | value = repr(user_ns[varname]) |
|
1970 | value = repr(user_ns[varname]) | |
1945 | except: |
|
1971 | except: | |
1946 | value = self._simple_error() |
|
1972 | value = self._simple_error() | |
1947 | out[varname] = value |
|
1973 | out[varname] = value | |
1948 | return out |
|
1974 | return out | |
1949 |
|
1975 | |||
1950 | def eval_expressions(self, expressions): |
|
1976 | def eval_expressions(self, expressions): | |
1951 | """Evaluate a dict of expressions in the user's namespace. |
|
1977 | """Evaluate a dict of expressions in the user's namespace. | |
1952 |
|
1978 | |||
1953 | The return value is a dict with the repr() of each value. |
|
1979 | The return value is a dict with the repr() of each value. | |
1954 | """ |
|
1980 | """ | |
1955 | out = {} |
|
1981 | out = {} | |
1956 | user_ns = self.user_ns |
|
1982 | user_ns = self.user_ns | |
1957 | global_ns = self.user_global_ns |
|
1983 | global_ns = self.user_global_ns | |
1958 | for key, expr in expressions.iteritems(): |
|
1984 | for key, expr in expressions.iteritems(): | |
1959 | try: |
|
1985 | try: | |
1960 | value = repr(eval(expr, global_ns, user_ns)) |
|
1986 | value = repr(eval(expr, global_ns, user_ns)) | |
1961 | except: |
|
1987 | except: | |
1962 | value = self._simple_error() |
|
1988 | value = self._simple_error() | |
1963 | out[key] = value |
|
1989 | out[key] = value | |
1964 | return out |
|
1990 | return out | |
1965 |
|
1991 | |||
1966 | #------------------------------------------------------------------------- |
|
1992 | #------------------------------------------------------------------------- | |
1967 | # Things related to the running of code |
|
1993 | # Things related to the running of code | |
1968 | #------------------------------------------------------------------------- |
|
1994 | #------------------------------------------------------------------------- | |
1969 |
|
1995 | |||
1970 | def ex(self, cmd): |
|
1996 | def ex(self, cmd): | |
1971 | """Execute a normal python statement in user namespace.""" |
|
1997 | """Execute a normal python statement in user namespace.""" | |
1972 | with nested(self.builtin_trap,): |
|
1998 | with nested(self.builtin_trap,): | |
1973 | exec cmd in self.user_global_ns, self.user_ns |
|
1999 | exec cmd in self.user_global_ns, self.user_ns | |
1974 |
|
2000 | |||
1975 | def ev(self, expr): |
|
2001 | def ev(self, expr): | |
1976 | """Evaluate python expression expr in user namespace. |
|
2002 | """Evaluate python expression expr in user namespace. | |
1977 |
|
2003 | |||
1978 | Returns the result of evaluation |
|
2004 | Returns the result of evaluation | |
1979 | """ |
|
2005 | """ | |
1980 | with nested(self.builtin_trap,): |
|
2006 | with nested(self.builtin_trap,): | |
1981 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2007 | return eval(expr, self.user_global_ns, self.user_ns) | |
1982 |
|
2008 | |||
1983 | def safe_execfile(self, fname, *where, **kw): |
|
2009 | def safe_execfile(self, fname, *where, **kw): | |
1984 | """A safe version of the builtin execfile(). |
|
2010 | """A safe version of the builtin execfile(). | |
1985 |
|
2011 | |||
1986 | This version will never throw an exception, but instead print |
|
2012 | This version will never throw an exception, but instead print | |
1987 | helpful error messages to the screen. This only works on pure |
|
2013 | helpful error messages to the screen. This only works on pure | |
1988 | Python files with the .py extension. |
|
2014 | Python files with the .py extension. | |
1989 |
|
2015 | |||
1990 | Parameters |
|
2016 | Parameters | |
1991 | ---------- |
|
2017 | ---------- | |
1992 | fname : string |
|
2018 | fname : string | |
1993 | The name of the file to be executed. |
|
2019 | The name of the file to be executed. | |
1994 | where : tuple |
|
2020 | where : tuple | |
1995 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2021 | One or two namespaces, passed to execfile() as (globals,locals). | |
1996 | If only one is given, it is passed as both. |
|
2022 | If only one is given, it is passed as both. | |
1997 | exit_ignore : bool (False) |
|
2023 | exit_ignore : bool (False) | |
1998 | If True, then silence SystemExit for non-zero status (it is always |
|
2024 | If True, then silence SystemExit for non-zero status (it is always | |
1999 | silenced for zero status, as it is so common). |
|
2025 | silenced for zero status, as it is so common). | |
2000 | """ |
|
2026 | """ | |
2001 | kw.setdefault('exit_ignore', False) |
|
2027 | kw.setdefault('exit_ignore', False) | |
2002 |
|
2028 | |||
2003 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2029 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2004 |
|
2030 | |||
2005 | # Make sure we have a .py file |
|
2031 | # Make sure we have a .py file | |
2006 | if not fname.endswith('.py'): |
|
2032 | if not fname.endswith('.py'): | |
2007 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2033 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2008 |
|
2034 | |||
2009 | # Make sure we can open the file |
|
2035 | # Make sure we can open the file | |
2010 | try: |
|
2036 | try: | |
2011 | with open(fname) as thefile: |
|
2037 | with open(fname) as thefile: | |
2012 | pass |
|
2038 | pass | |
2013 | except: |
|
2039 | except: | |
2014 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2040 | warn('Could not open file <%s> for safe execution.' % fname) | |
2015 | return |
|
2041 | return | |
2016 |
|
2042 | |||
2017 | # Find things also in current directory. This is needed to mimic the |
|
2043 | # Find things also in current directory. This is needed to mimic the | |
2018 | # behavior of running a script from the system command line, where |
|
2044 | # behavior of running a script from the system command line, where | |
2019 | # Python inserts the script's directory into sys.path |
|
2045 | # Python inserts the script's directory into sys.path | |
2020 | dname = os.path.dirname(fname) |
|
2046 | dname = os.path.dirname(fname) | |
2021 |
|
2047 | |||
2022 | with prepended_to_syspath(dname): |
|
2048 | with prepended_to_syspath(dname): | |
2023 | try: |
|
2049 | try: | |
2024 | execfile(fname,*where) |
|
2050 | execfile(fname,*where) | |
2025 | except SystemExit, status: |
|
2051 | except SystemExit, status: | |
2026 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2052 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2027 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2053 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2028 | # these are considered normal by the OS: |
|
2054 | # these are considered normal by the OS: | |
2029 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2055 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2030 | # 0 |
|
2056 | # 0 | |
2031 | # > python -c'import sys;sys.exit()'; echo $? |
|
2057 | # > python -c'import sys;sys.exit()'; echo $? | |
2032 | # 0 |
|
2058 | # 0 | |
2033 | # For other exit status, we show the exception unless |
|
2059 | # For other exit status, we show the exception unless | |
2034 | # explicitly silenced, but only in short form. |
|
2060 | # explicitly silenced, but only in short form. | |
2035 | if status.code not in (0, None) and not kw['exit_ignore']: |
|
2061 | if status.code not in (0, None) and not kw['exit_ignore']: | |
2036 | self.showtraceback(exception_only=True) |
|
2062 | self.showtraceback(exception_only=True) | |
2037 | except: |
|
2063 | except: | |
2038 | self.showtraceback() |
|
2064 | self.showtraceback() | |
2039 |
|
2065 | |||
2040 | def safe_execfile_ipy(self, fname): |
|
2066 | def safe_execfile_ipy(self, fname): | |
2041 | """Like safe_execfile, but for .ipy files with IPython syntax. |
|
2067 | """Like safe_execfile, but for .ipy files with IPython syntax. | |
2042 |
|
2068 | |||
2043 | Parameters |
|
2069 | Parameters | |
2044 | ---------- |
|
2070 | ---------- | |
2045 | fname : str |
|
2071 | fname : str | |
2046 | The name of the file to execute. The filename must have a |
|
2072 | The name of the file to execute. The filename must have a | |
2047 | .ipy extension. |
|
2073 | .ipy extension. | |
2048 | """ |
|
2074 | """ | |
2049 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2075 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2050 |
|
2076 | |||
2051 | # Make sure we have a .py file |
|
2077 | # Make sure we have a .py file | |
2052 | if not fname.endswith('.ipy'): |
|
2078 | if not fname.endswith('.ipy'): | |
2053 | warn('File must end with .py to be run using execfile: <%s>' % fname) |
|
2079 | warn('File must end with .py to be run using execfile: <%s>' % fname) | |
2054 |
|
2080 | |||
2055 | # Make sure we can open the file |
|
2081 | # Make sure we can open the file | |
2056 | try: |
|
2082 | try: | |
2057 | with open(fname) as thefile: |
|
2083 | with open(fname) as thefile: | |
2058 | pass |
|
2084 | pass | |
2059 | except: |
|
2085 | except: | |
2060 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2086 | warn('Could not open file <%s> for safe execution.' % fname) | |
2061 | return |
|
2087 | return | |
2062 |
|
2088 | |||
2063 | # Find things also in current directory. This is needed to mimic the |
|
2089 | # Find things also in current directory. This is needed to mimic the | |
2064 | # behavior of running a script from the system command line, where |
|
2090 | # behavior of running a script from the system command line, where | |
2065 | # Python inserts the script's directory into sys.path |
|
2091 | # Python inserts the script's directory into sys.path | |
2066 | dname = os.path.dirname(fname) |
|
2092 | dname = os.path.dirname(fname) | |
2067 |
|
2093 | |||
2068 | with prepended_to_syspath(dname): |
|
2094 | with prepended_to_syspath(dname): | |
2069 | try: |
|
2095 | try: | |
2070 | with open(fname) as thefile: |
|
2096 | with open(fname) as thefile: | |
2071 | script = thefile.read() |
|
2097 | script = thefile.read() | |
2072 | # self.runlines currently captures all exceptions |
|
2098 | # self.runlines currently captures all exceptions | |
2073 | # raise in user code. It would be nice if there were |
|
2099 | # raise in user code. It would be nice if there were | |
2074 | # versions of runlines, execfile that did raise, so |
|
2100 | # versions of runlines, execfile that did raise, so | |
2075 | # we could catch the errors. |
|
2101 | # we could catch the errors. | |
2076 | self.runlines(script, clean=True) |
|
2102 | self.runlines(script, clean=True) | |
2077 | except: |
|
2103 | except: | |
2078 | self.showtraceback() |
|
2104 | self.showtraceback() | |
2079 | warn('Unknown failure executing file: <%s>' % fname) |
|
2105 | warn('Unknown failure executing file: <%s>' % fname) | |
2080 |
|
2106 | |||
2081 | def run_cell(self, cell): |
|
2107 | def run_cell(self, cell): | |
2082 | """Run the contents of an entire multiline 'cell' of code. |
|
2108 | """Run the contents of an entire multiline 'cell' of code. | |
2083 |
|
2109 | |||
2084 | The cell is split into separate blocks which can be executed |
|
2110 | The cell is split into separate blocks which can be executed | |
2085 | individually. Then, based on how many blocks there are, they are |
|
2111 | individually. Then, based on how many blocks there are, they are | |
2086 | executed as follows: |
|
2112 | executed as follows: | |
2087 |
|
2113 | |||
2088 | - A single block: 'single' mode. |
|
2114 | - A single block: 'single' mode. | |
2089 |
|
2115 | |||
2090 | If there's more than one block, it depends: |
|
2116 | If there's more than one block, it depends: | |
2091 |
|
2117 | |||
2092 | - if the last one is a single line long, run all but the last in |
|
2118 | - if the last one is a single line long, run all but the last in | |
2093 | 'exec' mode and the very last one in 'single' mode. This makes it |
|
2119 | 'exec' mode and the very last one in 'single' mode. This makes it | |
2094 | easy to type simple expressions at the end to see computed values. |
|
2120 | easy to type simple expressions at the end to see computed values. | |
2095 | - otherwise (last one is also multiline), run all in 'exec' mode |
|
2121 | - otherwise (last one is also multiline), run all in 'exec' mode | |
2096 |
|
2122 | |||
2097 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, |
|
2123 | When code is executed in 'single' mode, :func:`sys.displayhook` fires, | |
2098 | results are displayed and output prompts are computed. In 'exec' mode, |
|
2124 | results are displayed and output prompts are computed. In 'exec' mode, | |
2099 | no results are displayed unless :func:`print` is called explicitly; |
|
2125 | no results are displayed unless :func:`print` is called explicitly; | |
2100 | this mode is more akin to running a script. |
|
2126 | this mode is more akin to running a script. | |
2101 |
|
2127 | |||
2102 | Parameters |
|
2128 | Parameters | |
2103 | ---------- |
|
2129 | ---------- | |
2104 | cell : str |
|
2130 | cell : str | |
2105 | A single or multiline string. |
|
2131 | A single or multiline string. | |
2106 | """ |
|
2132 | """ | |
2107 | # We need to break up the input into executable blocks that can be run |
|
2133 | # We need to break up the input into executable blocks that can be run | |
2108 | # in 'single' mode, to provide comfortable user behavior. |
|
2134 | # in 'single' mode, to provide comfortable user behavior. | |
2109 | blocks = self.input_splitter.split_blocks(cell) |
|
2135 | blocks = self.input_splitter.split_blocks(cell) | |
2110 |
|
2136 | |||
2111 | if not blocks: |
|
2137 | if not blocks: | |
2112 | return |
|
2138 | return | |
2113 |
|
2139 | |||
2114 | # Single-block input should behave like an interactive prompt |
|
2140 | # Single-block input should behave like an interactive prompt | |
2115 | if len(blocks) == 1: |
|
2141 | if len(blocks) == 1: | |
2116 | self.runlines(blocks[0]) |
|
2142 | self.runlines(blocks[0]) | |
2117 | return |
|
2143 | return | |
2118 |
|
2144 | |||
2119 | # In multi-block input, if the last block is a simple (one-two lines) |
|
2145 | # In multi-block input, if the last block is a simple (one-two lines) | |
2120 | # expression, run it in single mode so it produces output. Otherwise |
|
2146 | # expression, run it in single mode so it produces output. Otherwise | |
2121 | # just feed the whole thing to runcode. |
|
2147 | # just feed the whole thing to runcode. | |
2122 | # This seems like a reasonable usability design. |
|
2148 | # This seems like a reasonable usability design. | |
2123 | last = blocks[-1] |
|
2149 | last = blocks[-1] | |
2124 |
|
2150 | |||
2125 | # Note: below, whenever we call runcode, we must sync history |
|
2151 | # Note: below, whenever we call runcode, we must sync history | |
2126 | # ourselves, because runcode is NOT meant to manage history at all. |
|
2152 | # ourselves, because runcode is NOT meant to manage history at all. | |
2127 | if len(last.splitlines()) < 2: |
|
2153 | if len(last.splitlines()) < 2: | |
2128 | # Get the main body to run as a cell |
|
2154 | # Get the main body to run as a cell | |
2129 | body = ''.join(blocks[:-1]) |
|
2155 | body = ''.join(blocks[:-1]) | |
2130 | self.input_hist.append(body) |
|
2156 | self.input_hist.append(body) | |
2131 | self.input_hist_raw.append(body) |
|
2157 | self.input_hist_raw.append(body) | |
2132 | self.runcode(body, post_execute=False) |
|
2158 | self.runcode(body, post_execute=False) | |
2133 | # And the last expression via runlines so it produces output |
|
2159 | # And the last expression via runlines so it produces output | |
2134 | self.runlines(last) |
|
2160 | self.runlines(last) | |
2135 | else: |
|
2161 | else: | |
2136 | # Run the whole cell as one entity |
|
2162 | # Run the whole cell as one entity | |
2137 | self.input_hist.append(cell) |
|
2163 | self.input_hist.append(cell) | |
2138 | self.input_hist_raw.append(cell) |
|
2164 | self.input_hist_raw.append(cell) | |
2139 | self.runcode(cell) |
|
2165 | self.runcode(cell) | |
2140 |
|
2166 | |||
2141 | def runlines(self, lines, clean=False): |
|
2167 | def runlines(self, lines, clean=False): | |
2142 | """Run a string of one or more lines of source. |
|
2168 | """Run a string of one or more lines of source. | |
2143 |
|
2169 | |||
2144 | This method is capable of running a string containing multiple source |
|
2170 | This method is capable of running a string containing multiple source | |
2145 | lines, as if they had been entered at the IPython prompt. Since it |
|
2171 | lines, as if they had been entered at the IPython prompt. Since it | |
2146 | exposes IPython's processing machinery, the given strings can contain |
|
2172 | exposes IPython's processing machinery, the given strings can contain | |
2147 | magic calls (%magic), special shell access (!cmd), etc. |
|
2173 | magic calls (%magic), special shell access (!cmd), etc. | |
2148 | """ |
|
2174 | """ | |
2149 |
|
2175 | |||
2150 | if isinstance(lines, (list, tuple)): |
|
2176 | if isinstance(lines, (list, tuple)): | |
2151 | lines = '\n'.join(lines) |
|
2177 | lines = '\n'.join(lines) | |
2152 |
|
2178 | |||
2153 | if clean: |
|
2179 | if clean: | |
2154 | lines = self._cleanup_ipy_script(lines) |
|
2180 | lines = self._cleanup_ipy_script(lines) | |
2155 |
|
2181 | |||
2156 | # We must start with a clean buffer, in case this is run from an |
|
2182 | # We must start with a clean buffer, in case this is run from an | |
2157 | # interactive IPython session (via a magic, for example). |
|
2183 | # interactive IPython session (via a magic, for example). | |
2158 | self.resetbuffer() |
|
2184 | self.resetbuffer() | |
2159 | lines = lines.splitlines() |
|
2185 | lines = lines.splitlines() | |
2160 | more = 0 |
|
2186 | more = 0 | |
2161 | with nested(self.builtin_trap, self.display_trap): |
|
2187 | with nested(self.builtin_trap, self.display_trap): | |
2162 | for line in lines: |
|
2188 | for line in lines: | |
2163 | # skip blank lines so we don't mess up the prompt counter, but |
|
2189 | # skip blank lines so we don't mess up the prompt counter, but | |
2164 | # do NOT skip even a blank line if we are in a code block (more |
|
2190 | # do NOT skip even a blank line if we are in a code block (more | |
2165 | # is true) |
|
2191 | # is true) | |
2166 |
|
2192 | |||
2167 | if line or more: |
|
2193 | if line or more: | |
2168 | # push to raw history, so hist line numbers stay in sync |
|
2194 | # push to raw history, so hist line numbers stay in sync | |
2169 | self.input_hist_raw.append(line + '\n') |
|
2195 | self.input_hist_raw.append(line + '\n') | |
2170 | prefiltered = self.prefilter_manager.prefilter_lines(line, |
|
2196 | prefiltered = self.prefilter_manager.prefilter_lines(line, | |
2171 | more) |
|
2197 | more) | |
2172 | more = self.push_line(prefiltered) |
|
2198 | more = self.push_line(prefiltered) | |
2173 | # IPython's runsource returns None if there was an error |
|
2199 | # IPython's runsource returns None if there was an error | |
2174 | # compiling the code. This allows us to stop processing |
|
2200 | # compiling the code. This allows us to stop processing | |
2175 | # right away, so the user gets the error message at the |
|
2201 | # right away, so the user gets the error message at the | |
2176 | # right place. |
|
2202 | # right place. | |
2177 | if more is None: |
|
2203 | if more is None: | |
2178 | break |
|
2204 | break | |
2179 | else: |
|
2205 | else: | |
2180 | self.input_hist_raw.append("\n") |
|
2206 | self.input_hist_raw.append("\n") | |
2181 | # final newline in case the input didn't have it, so that the code |
|
2207 | # final newline in case the input didn't have it, so that the code | |
2182 | # actually does get executed |
|
2208 | # actually does get executed | |
2183 | if more: |
|
2209 | if more: | |
2184 | self.push_line('\n') |
|
2210 | self.push_line('\n') | |
2185 |
|
2211 | |||
2186 | def runsource(self, source, filename='<input>', symbol='single'): |
|
2212 | def runsource(self, source, filename='<input>', symbol='single'): | |
2187 | """Compile and run some source in the interpreter. |
|
2213 | """Compile and run some source in the interpreter. | |
2188 |
|
2214 | |||
2189 | Arguments are as for compile_command(). |
|
2215 | Arguments are as for compile_command(). | |
2190 |
|
2216 | |||
2191 | One several things can happen: |
|
2217 | One several things can happen: | |
2192 |
|
2218 | |||
2193 | 1) The input is incorrect; compile_command() raised an |
|
2219 | 1) The input is incorrect; compile_command() raised an | |
2194 | exception (SyntaxError or OverflowError). A syntax traceback |
|
2220 | exception (SyntaxError or OverflowError). A syntax traceback | |
2195 | will be printed by calling the showsyntaxerror() method. |
|
2221 | will be printed by calling the showsyntaxerror() method. | |
2196 |
|
2222 | |||
2197 | 2) The input is incomplete, and more input is required; |
|
2223 | 2) The input is incomplete, and more input is required; | |
2198 | compile_command() returned None. Nothing happens. |
|
2224 | compile_command() returned None. Nothing happens. | |
2199 |
|
2225 | |||
2200 | 3) The input is complete; compile_command() returned a code |
|
2226 | 3) The input is complete; compile_command() returned a code | |
2201 | object. The code is executed by calling self.runcode() (which |
|
2227 | object. The code is executed by calling self.runcode() (which | |
2202 | also handles run-time exceptions, except for SystemExit). |
|
2228 | also handles run-time exceptions, except for SystemExit). | |
2203 |
|
2229 | |||
2204 | The return value is: |
|
2230 | The return value is: | |
2205 |
|
2231 | |||
2206 | - True in case 2 |
|
2232 | - True in case 2 | |
2207 |
|
2233 | |||
2208 | - False in the other cases, unless an exception is raised, where |
|
2234 | - False in the other cases, unless an exception is raised, where | |
2209 | None is returned instead. This can be used by external callers to |
|
2235 | None is returned instead. This can be used by external callers to | |
2210 | know whether to continue feeding input or not. |
|
2236 | know whether to continue feeding input or not. | |
2211 |
|
2237 | |||
2212 | The return value can be used to decide whether to use sys.ps1 or |
|
2238 | The return value can be used to decide whether to use sys.ps1 or | |
2213 | sys.ps2 to prompt the next line.""" |
|
2239 | sys.ps2 to prompt the next line.""" | |
2214 |
|
2240 | |||
2215 | # if the source code has leading blanks, add 'if 1:\n' to it |
|
2241 | # if the source code has leading blanks, add 'if 1:\n' to it | |
2216 | # this allows execution of indented pasted code. It is tempting |
|
2242 | # this allows execution of indented pasted code. It is tempting | |
2217 | # to add '\n' at the end of source to run commands like ' a=1' |
|
2243 | # to add '\n' at the end of source to run commands like ' a=1' | |
2218 | # directly, but this fails for more complicated scenarios |
|
2244 | # directly, but this fails for more complicated scenarios | |
2219 | source=source.encode(self.stdin_encoding) |
|
2245 | source=source.encode(self.stdin_encoding) | |
2220 | if source[:1] in [' ', '\t']: |
|
2246 | if source[:1] in [' ', '\t']: | |
2221 | source = 'if 1:\n%s' % source |
|
2247 | source = 'if 1:\n%s' % source | |
2222 |
|
2248 | |||
2223 | try: |
|
2249 | try: | |
2224 | code = self.compile(source,filename,symbol) |
|
2250 | code = self.compile(source,filename,symbol) | |
2225 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): |
|
2251 | except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError): | |
2226 | # Case 1 |
|
2252 | # Case 1 | |
2227 | self.showsyntaxerror(filename) |
|
2253 | self.showsyntaxerror(filename) | |
2228 | return None |
|
2254 | return None | |
2229 |
|
2255 | |||
2230 | if code is None: |
|
2256 | if code is None: | |
2231 | # Case 2 |
|
2257 | # Case 2 | |
2232 | return True |
|
2258 | return True | |
2233 |
|
2259 | |||
2234 | # Case 3 |
|
2260 | # Case 3 | |
2235 | # We store the code object so that threaded shells and |
|
2261 | # We store the code object so that threaded shells and | |
2236 | # custom exception handlers can access all this info if needed. |
|
2262 | # custom exception handlers can access all this info if needed. | |
2237 | # The source corresponding to this can be obtained from the |
|
2263 | # The source corresponding to this can be obtained from the | |
2238 | # buffer attribute as '\n'.join(self.buffer). |
|
2264 | # buffer attribute as '\n'.join(self.buffer). | |
2239 | self.code_to_run = code |
|
2265 | self.code_to_run = code | |
2240 | # now actually execute the code object |
|
2266 | # now actually execute the code object | |
2241 | if self.runcode(code) == 0: |
|
2267 | if self.runcode(code) == 0: | |
2242 | return False |
|
2268 | return False | |
2243 | else: |
|
2269 | else: | |
2244 | return None |
|
2270 | return None | |
2245 |
|
2271 | |||
2246 | def runcode(self, code_obj, post_execute=True): |
|
2272 | def runcode(self, code_obj, post_execute=True): | |
2247 | """Execute a code object. |
|
2273 | """Execute a code object. | |
2248 |
|
2274 | |||
2249 | When an exception occurs, self.showtraceback() is called to display a |
|
2275 | When an exception occurs, self.showtraceback() is called to display a | |
2250 | traceback. |
|
2276 | traceback. | |
2251 |
|
2277 | |||
2252 | Return value: a flag indicating whether the code to be run completed |
|
2278 | Return value: a flag indicating whether the code to be run completed | |
2253 | successfully: |
|
2279 | successfully: | |
2254 |
|
2280 | |||
2255 | - 0: successful execution. |
|
2281 | - 0: successful execution. | |
2256 | - 1: an error occurred. |
|
2282 | - 1: an error occurred. | |
2257 | """ |
|
2283 | """ | |
2258 |
|
2284 | |||
2259 | # Set our own excepthook in case the user code tries to call it |
|
2285 | # Set our own excepthook in case the user code tries to call it | |
2260 | # directly, so that the IPython crash handler doesn't get triggered |
|
2286 | # directly, so that the IPython crash handler doesn't get triggered | |
2261 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook |
|
2287 | old_excepthook,sys.excepthook = sys.excepthook, self.excepthook | |
2262 |
|
2288 | |||
2263 | # we save the original sys.excepthook in the instance, in case config |
|
2289 | # we save the original sys.excepthook in the instance, in case config | |
2264 | # code (such as magics) needs access to it. |
|
2290 | # code (such as magics) needs access to it. | |
2265 | self.sys_excepthook = old_excepthook |
|
2291 | self.sys_excepthook = old_excepthook | |
2266 | outflag = 1 # happens in more places, so it's easier as default |
|
2292 | outflag = 1 # happens in more places, so it's easier as default | |
2267 | try: |
|
2293 | try: | |
2268 | try: |
|
2294 | try: | |
2269 | self.hooks.pre_runcode_hook() |
|
2295 | self.hooks.pre_runcode_hook() | |
2270 | #rprint('Running code') # dbg |
|
2296 | #rprint('Running code') # dbg | |
2271 | exec code_obj in self.user_global_ns, self.user_ns |
|
2297 | exec code_obj in self.user_global_ns, self.user_ns | |
2272 | finally: |
|
2298 | finally: | |
2273 | # Reset our crash handler in place |
|
2299 | # Reset our crash handler in place | |
2274 | sys.excepthook = old_excepthook |
|
2300 | sys.excepthook = old_excepthook | |
2275 | except SystemExit: |
|
2301 | except SystemExit: | |
2276 | self.resetbuffer() |
|
2302 | self.resetbuffer() | |
2277 | self.showtraceback(exception_only=True) |
|
2303 | self.showtraceback(exception_only=True) | |
2278 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) |
|
2304 | warn("To exit: use any of 'exit', 'quit', %Exit or Ctrl-D.", level=1) | |
2279 | except self.custom_exceptions: |
|
2305 | except self.custom_exceptions: | |
2280 | etype,value,tb = sys.exc_info() |
|
2306 | etype,value,tb = sys.exc_info() | |
2281 | self.CustomTB(etype,value,tb) |
|
2307 | self.CustomTB(etype,value,tb) | |
2282 | except: |
|
2308 | except: | |
2283 | self.showtraceback() |
|
2309 | self.showtraceback() | |
2284 | else: |
|
2310 | else: | |
2285 | outflag = 0 |
|
2311 | outflag = 0 | |
2286 | if softspace(sys.stdout, 0): |
|
2312 | if softspace(sys.stdout, 0): | |
2287 |
|
2313 | |||
2288 |
|
2314 | |||
2289 | # Execute any registered post-execution functions. Here, any errors |
|
2315 | # Execute any registered post-execution functions. Here, any errors | |
2290 | # are reported only minimally and just on the terminal, because the |
|
2316 | # are reported only minimally and just on the terminal, because the | |
2291 | # main exception channel may be occupied with a user traceback. |
|
2317 | # main exception channel may be occupied with a user traceback. | |
2292 | # FIXME: we need to think this mechanism a little more carefully. |
|
2318 | # FIXME: we need to think this mechanism a little more carefully. | |
2293 | if post_execute: |
|
2319 | if post_execute: | |
2294 | for func in self._post_execute: |
|
2320 | for func in self._post_execute: | |
2295 | try: |
|
2321 | try: | |
2296 | func() |
|
2322 | func() | |
2297 | except: |
|
2323 | except: | |
2298 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ |
|
2324 | head = '[ ERROR ] Evaluating post_execute function: %s' % \ | |
2299 | func |
|
2325 | func | |
2300 | print >> io.Term.cout, head |
|
2326 | print >> io.Term.cout, head | |
2301 | print >> io.Term.cout, self._simple_error() |
|
2327 | print >> io.Term.cout, self._simple_error() | |
2302 | print >> io.Term.cout, 'Removing from post_execute' |
|
2328 | print >> io.Term.cout, 'Removing from post_execute' | |
2303 | self._post_execute.remove(func) |
|
2329 | self._post_execute.remove(func) | |
2304 |
|
2330 | |||
2305 | # Flush out code object which has been run (and source) |
|
2331 | # Flush out code object which has been run (and source) | |
2306 | self.code_to_run = None |
|
2332 | self.code_to_run = None | |
2307 | return outflag |
|
2333 | return outflag | |
2308 |
|
2334 | |||
2309 | def push_line(self, line): |
|
2335 | def push_line(self, line): | |
2310 | """Push a line to the interpreter. |
|
2336 | """Push a line to the interpreter. | |
2311 |
|
2337 | |||
2312 | The line should not have a trailing newline; it may have |
|
2338 | The line should not have a trailing newline; it may have | |
2313 | internal newlines. The line is appended to a buffer and the |
|
2339 | internal newlines. The line is appended to a buffer and the | |
2314 | interpreter's runsource() method is called with the |
|
2340 | interpreter's runsource() method is called with the | |
2315 | concatenated contents of the buffer as source. If this |
|
2341 | concatenated contents of the buffer as source. If this | |
2316 | indicates that the command was executed or invalid, the buffer |
|
2342 | indicates that the command was executed or invalid, the buffer | |
2317 | is reset; otherwise, the command is incomplete, and the buffer |
|
2343 | is reset; otherwise, the command is incomplete, and the buffer | |
2318 | is left as it was after the line was appended. The return |
|
2344 | is left as it was after the line was appended. The return | |
2319 | value is 1 if more input is required, 0 if the line was dealt |
|
2345 | value is 1 if more input is required, 0 if the line was dealt | |
2320 | with in some way (this is the same as runsource()). |
|
2346 | with in some way (this is the same as runsource()). | |
2321 | """ |
|
2347 | """ | |
2322 |
|
2348 | |||
2323 | # autoindent management should be done here, and not in the |
|
2349 | # autoindent management should be done here, and not in the | |
2324 | # interactive loop, since that one is only seen by keyboard input. We |
|
2350 | # interactive loop, since that one is only seen by keyboard input. We | |
2325 | # need this done correctly even for code run via runlines (which uses |
|
2351 | # need this done correctly even for code run via runlines (which uses | |
2326 | # push). |
|
2352 | # push). | |
2327 |
|
2353 | |||
2328 | #print 'push line: <%s>' % line # dbg |
|
2354 | #print 'push line: <%s>' % line # dbg | |
2329 | for subline in line.splitlines(): |
|
2355 | for subline in line.splitlines(): | |
2330 | self._autoindent_update(subline) |
|
2356 | self._autoindent_update(subline) | |
2331 | self.buffer.append(line) |
|
2357 | self.buffer.append(line) | |
2332 | more = self.runsource('\n'.join(self.buffer), self.filename) |
|
2358 | more = self.runsource('\n'.join(self.buffer), self.filename) | |
2333 | if not more: |
|
2359 | if not more: | |
2334 | self.resetbuffer() |
|
2360 | self.resetbuffer() | |
2335 | return more |
|
2361 | return more | |
2336 |
|
2362 | |||
2337 | def resetbuffer(self): |
|
2363 | def resetbuffer(self): | |
2338 | """Reset the input buffer.""" |
|
2364 | """Reset the input buffer.""" | |
2339 | self.buffer[:] = [] |
|
2365 | self.buffer[:] = [] | |
2340 |
|
2366 | |||
2341 | def _is_secondary_block_start(self, s): |
|
2367 | def _is_secondary_block_start(self, s): | |
2342 | if not s.endswith(':'): |
|
2368 | if not s.endswith(':'): | |
2343 | return False |
|
2369 | return False | |
2344 | if (s.startswith('elif') or |
|
2370 | if (s.startswith('elif') or | |
2345 | s.startswith('else') or |
|
2371 | s.startswith('else') or | |
2346 | s.startswith('except') or |
|
2372 | s.startswith('except') or | |
2347 | s.startswith('finally')): |
|
2373 | s.startswith('finally')): | |
2348 | return True |
|
2374 | return True | |
2349 |
|
2375 | |||
2350 | def _cleanup_ipy_script(self, script): |
|
2376 | def _cleanup_ipy_script(self, script): | |
2351 | """Make a script safe for self.runlines() |
|
2377 | """Make a script safe for self.runlines() | |
2352 |
|
2378 | |||
2353 | Currently, IPython is lines based, with blocks being detected by |
|
2379 | Currently, IPython is lines based, with blocks being detected by | |
2354 | empty lines. This is a problem for block based scripts that may |
|
2380 | empty lines. This is a problem for block based scripts that may | |
2355 | not have empty lines after blocks. This script adds those empty |
|
2381 | not have empty lines after blocks. This script adds those empty | |
2356 | lines to make scripts safe for running in the current line based |
|
2382 | lines to make scripts safe for running in the current line based | |
2357 | IPython. |
|
2383 | IPython. | |
2358 | """ |
|
2384 | """ | |
2359 | res = [] |
|
2385 | res = [] | |
2360 | lines = script.splitlines() |
|
2386 | lines = script.splitlines() | |
2361 | level = 0 |
|
2387 | level = 0 | |
2362 |
|
2388 | |||
2363 | for l in lines: |
|
2389 | for l in lines: | |
2364 | lstripped = l.lstrip() |
|
2390 | lstripped = l.lstrip() | |
2365 | stripped = l.strip() |
|
2391 | stripped = l.strip() | |
2366 | if not stripped: |
|
2392 | if not stripped: | |
2367 | continue |
|
2393 | continue | |
2368 | newlevel = len(l) - len(lstripped) |
|
2394 | newlevel = len(l) - len(lstripped) | |
2369 | if level > 0 and newlevel == 0 and \ |
|
2395 | if level > 0 and newlevel == 0 and \ | |
2370 | not self._is_secondary_block_start(stripped): |
|
2396 | not self._is_secondary_block_start(stripped): | |
2371 | # add empty line |
|
2397 | # add empty line | |
2372 | res.append('') |
|
2398 | res.append('') | |
2373 | res.append(l) |
|
2399 | res.append(l) | |
2374 | level = newlevel |
|
2400 | level = newlevel | |
2375 |
|
2401 | |||
2376 | return '\n'.join(res) + '\n' |
|
2402 | return '\n'.join(res) + '\n' | |
2377 |
|
2403 | |||
2378 | def _autoindent_update(self,line): |
|
2404 | def _autoindent_update(self,line): | |
2379 | """Keep track of the indent level.""" |
|
2405 | """Keep track of the indent level.""" | |
2380 |
|
2406 | |||
2381 | #debugx('line') |
|
2407 | #debugx('line') | |
2382 | #debugx('self.indent_current_nsp') |
|
2408 | #debugx('self.indent_current_nsp') | |
2383 | if self.autoindent: |
|
2409 | if self.autoindent: | |
2384 | if line: |
|
2410 | if line: | |
2385 | inisp = num_ini_spaces(line) |
|
2411 | inisp = num_ini_spaces(line) | |
2386 | if inisp < self.indent_current_nsp: |
|
2412 | if inisp < self.indent_current_nsp: | |
2387 | self.indent_current_nsp = inisp |
|
2413 | self.indent_current_nsp = inisp | |
2388 |
|
2414 | |||
2389 | if line[-1] == ':': |
|
2415 | if line[-1] == ':': | |
2390 | self.indent_current_nsp += 4 |
|
2416 | self.indent_current_nsp += 4 | |
2391 | elif dedent_re.match(line): |
|
2417 | elif dedent_re.match(line): | |
2392 | self.indent_current_nsp -= 4 |
|
2418 | self.indent_current_nsp -= 4 | |
2393 | else: |
|
2419 | else: | |
2394 | self.indent_current_nsp = 0 |
|
2420 | self.indent_current_nsp = 0 | |
2395 |
|
2421 | |||
2396 | #------------------------------------------------------------------------- |
|
2422 | #------------------------------------------------------------------------- | |
2397 | # Things related to GUI support and pylab |
|
2423 | # Things related to GUI support and pylab | |
2398 | #------------------------------------------------------------------------- |
|
2424 | #------------------------------------------------------------------------- | |
2399 |
|
2425 | |||
2400 | def enable_pylab(self, gui=None): |
|
2426 | def enable_pylab(self, gui=None): | |
2401 | raise NotImplementedError('Implement enable_pylab in a subclass') |
|
2427 | raise NotImplementedError('Implement enable_pylab in a subclass') | |
2402 |
|
2428 | |||
2403 | #------------------------------------------------------------------------- |
|
2429 | #------------------------------------------------------------------------- | |
2404 | # Utilities |
|
2430 | # Utilities | |
2405 | #------------------------------------------------------------------------- |
|
2431 | #------------------------------------------------------------------------- | |
2406 |
|
2432 | |||
2407 | def var_expand(self,cmd,depth=0): |
|
2433 | def var_expand(self,cmd,depth=0): | |
2408 | """Expand python variables in a string. |
|
2434 | """Expand python variables in a string. | |
2409 |
|
2435 | |||
2410 | The depth argument indicates how many frames above the caller should |
|
2436 | The depth argument indicates how many frames above the caller should | |
2411 | be walked to look for the local namespace where to expand variables. |
|
2437 | be walked to look for the local namespace where to expand variables. | |
2412 |
|
2438 | |||
2413 | The global namespace for expansion is always the user's interactive |
|
2439 | The global namespace for expansion is always the user's interactive | |
2414 | namespace. |
|
2440 | namespace. | |
2415 | """ |
|
2441 | """ | |
2416 |
|
2442 | |||
2417 | return str(ItplNS(cmd, |
|
2443 | return str(ItplNS(cmd, | |
2418 | self.user_ns, # globals |
|
2444 | self.user_ns, # globals | |
2419 | # Skip our own frame in searching for locals: |
|
2445 | # Skip our own frame in searching for locals: | |
2420 | sys._getframe(depth+1).f_locals # locals |
|
2446 | sys._getframe(depth+1).f_locals # locals | |
2421 | )) |
|
2447 | )) | |
2422 |
|
2448 | |||
2423 | def mktempfile(self,data=None): |
|
2449 | def mktempfile(self,data=None): | |
2424 | """Make a new tempfile and return its filename. |
|
2450 | """Make a new tempfile and return its filename. | |
2425 |
|
2451 | |||
2426 | This makes a call to tempfile.mktemp, but it registers the created |
|
2452 | This makes a call to tempfile.mktemp, but it registers the created | |
2427 | filename internally so ipython cleans it up at exit time. |
|
2453 | filename internally so ipython cleans it up at exit time. | |
2428 |
|
2454 | |||
2429 | Optional inputs: |
|
2455 | Optional inputs: | |
2430 |
|
2456 | |||
2431 | - data(None): if data is given, it gets written out to the temp file |
|
2457 | - data(None): if data is given, it gets written out to the temp file | |
2432 | immediately, and the file is closed again.""" |
|
2458 | immediately, and the file is closed again.""" | |
2433 |
|
2459 | |||
2434 | filename = tempfile.mktemp('.py','ipython_edit_') |
|
2460 | filename = tempfile.mktemp('.py','ipython_edit_') | |
2435 | self.tempfiles.append(filename) |
|
2461 | self.tempfiles.append(filename) | |
2436 |
|
2462 | |||
2437 | if data: |
|
2463 | if data: | |
2438 | tmp_file = open(filename,'w') |
|
2464 | tmp_file = open(filename,'w') | |
2439 | tmp_file.write(data) |
|
2465 | tmp_file.write(data) | |
2440 | tmp_file.close() |
|
2466 | tmp_file.close() | |
2441 | return filename |
|
2467 | return filename | |
2442 |
|
2468 | |||
2443 | # TODO: This should be removed when Term is refactored. |
|
2469 | # TODO: This should be removed when Term is refactored. | |
2444 | def write(self,data): |
|
2470 | def write(self,data): | |
2445 | """Write a string to the default output""" |
|
2471 | """Write a string to the default output""" | |
2446 | io.Term.cout.write(data) |
|
2472 | io.Term.cout.write(data) | |
2447 |
|
2473 | |||
2448 | # TODO: This should be removed when Term is refactored. |
|
2474 | # TODO: This should be removed when Term is refactored. | |
2449 | def write_err(self,data): |
|
2475 | def write_err(self,data): | |
2450 | """Write a string to the default error output""" |
|
2476 | """Write a string to the default error output""" | |
2451 | io.Term.cerr.write(data) |
|
2477 | io.Term.cerr.write(data) | |
2452 |
|
2478 | |||
2453 | def ask_yes_no(self,prompt,default=True): |
|
2479 | def ask_yes_no(self,prompt,default=True): | |
2454 | if self.quiet: |
|
2480 | if self.quiet: | |
2455 | return True |
|
2481 | return True | |
2456 | return ask_yes_no(prompt,default) |
|
2482 | return ask_yes_no(prompt,default) | |
2457 |
|
2483 | |||
2458 | def show_usage(self): |
|
2484 | def show_usage(self): | |
2459 | """Show a usage message""" |
|
2485 | """Show a usage message""" | |
2460 | page.page(IPython.core.usage.interactive_usage) |
|
2486 | page.page(IPython.core.usage.interactive_usage) | |
2461 |
|
2487 | |||
2462 | #------------------------------------------------------------------------- |
|
2488 | #------------------------------------------------------------------------- | |
2463 | # Things related to IPython exiting |
|
2489 | # Things related to IPython exiting | |
2464 | #------------------------------------------------------------------------- |
|
2490 | #------------------------------------------------------------------------- | |
2465 | def atexit_operations(self): |
|
2491 | def atexit_operations(self): | |
2466 | """This will be executed at the time of exit. |
|
2492 | """This will be executed at the time of exit. | |
2467 |
|
2493 | |||
2468 | Cleanup operations and saving of persistent data that is done |
|
2494 | Cleanup operations and saving of persistent data that is done | |
2469 | unconditionally by IPython should be performed here. |
|
2495 | unconditionally by IPython should be performed here. | |
2470 |
|
2496 | |||
2471 | For things that may depend on startup flags or platform specifics (such |
|
2497 | For things that may depend on startup flags or platform specifics (such | |
2472 | as having readline or not), register a separate atexit function in the |
|
2498 | as having readline or not), register a separate atexit function in the | |
2473 | code that has the appropriate information, rather than trying to |
|
2499 | code that has the appropriate information, rather than trying to | |
2474 | clutter |
|
2500 | clutter | |
2475 | """ |
|
2501 | """ | |
2476 | # Cleanup all tempfiles left around |
|
2502 | # Cleanup all tempfiles left around | |
2477 | for tfile in self.tempfiles: |
|
2503 | for tfile in self.tempfiles: | |
2478 | try: |
|
2504 | try: | |
2479 | os.unlink(tfile) |
|
2505 | os.unlink(tfile) | |
2480 | except OSError: |
|
2506 | except OSError: | |
2481 | pass |
|
2507 | pass | |
2482 |
|
2508 | |||
2483 | # Clear all user namespaces to release all references cleanly. |
|
2509 | # Clear all user namespaces to release all references cleanly. | |
2484 | self.reset() |
|
2510 | self.reset() | |
2485 |
|
2511 | |||
2486 | # Run user hooks |
|
2512 | # Run user hooks | |
2487 | self.hooks.shutdown_hook() |
|
2513 | self.hooks.shutdown_hook() | |
2488 |
|
2514 | |||
2489 | def cleanup(self): |
|
2515 | def cleanup(self): | |
2490 | self.restore_sys_module_state() |
|
2516 | self.restore_sys_module_state() | |
2491 |
|
2517 | |||
2492 |
|
2518 | |||
2493 | class InteractiveShellABC(object): |
|
2519 | class InteractiveShellABC(object): | |
2494 | """An abstract base class for InteractiveShell.""" |
|
2520 | """An abstract base class for InteractiveShell.""" | |
2495 | __metaclass__ = abc.ABCMeta |
|
2521 | __metaclass__ = abc.ABCMeta | |
2496 |
|
2522 | |||
2497 | InteractiveShellABC.register(InteractiveShell) |
|
2523 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,3377 +1,3377 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Magic functions for InteractiveShell. |
|
2 | """Magic functions for InteractiveShell. | |
3 | """ |
|
3 | """ | |
4 |
|
4 | |||
5 | #----------------------------------------------------------------------------- |
|
5 | #----------------------------------------------------------------------------- | |
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and |
|
6 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> and | |
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> |
|
7 | # Copyright (C) 2001-2007 Fernando Perez <fperez@colorado.edu> | |
8 | # Copyright (C) 2008-2009 The IPython Development Team |
|
8 | # Copyright (C) 2008-2009 The IPython Development Team | |
9 |
|
9 | |||
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 |
|
17 | |||
18 | import __builtin__ |
|
18 | import __builtin__ | |
19 | import __future__ |
|
19 | import __future__ | |
20 | import bdb |
|
20 | import bdb | |
21 | import inspect |
|
21 | import inspect | |
22 | import os |
|
22 | import os | |
23 | import sys |
|
23 | import sys | |
24 | import shutil |
|
24 | import shutil | |
25 | import re |
|
25 | import re | |
26 | import time |
|
26 | import time | |
27 | import textwrap |
|
27 | import textwrap | |
28 | import types |
|
28 | import types | |
29 | from cStringIO import StringIO |
|
29 | from cStringIO import StringIO | |
30 | from getopt import getopt,GetoptError |
|
30 | from getopt import getopt,GetoptError | |
31 | from pprint import pformat |
|
31 | from pprint import pformat | |
32 |
|
32 | |||
33 | # cProfile was added in Python2.5 |
|
33 | # cProfile was added in Python2.5 | |
34 | try: |
|
34 | try: | |
35 | import cProfile as profile |
|
35 | import cProfile as profile | |
36 | import pstats |
|
36 | import pstats | |
37 | except ImportError: |
|
37 | except ImportError: | |
38 | # profile isn't bundled by default in Debian for license reasons |
|
38 | # profile isn't bundled by default in Debian for license reasons | |
39 | try: |
|
39 | try: | |
40 | import profile,pstats |
|
40 | import profile,pstats | |
41 | except ImportError: |
|
41 | except ImportError: | |
42 | profile = pstats = None |
|
42 | profile = pstats = None | |
43 |
|
43 | |||
44 | # print_function was added to __future__ in Python2.6, remove this when we drop |
|
44 | # print_function was added to __future__ in Python2.6, remove this when we drop | |
45 | # 2.5 compatibility |
|
45 | # 2.5 compatibility | |
46 | if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'): |
|
46 | if not hasattr(__future__,'CO_FUTURE_PRINT_FUNCTION'): | |
47 | __future__.CO_FUTURE_PRINT_FUNCTION = 65536 |
|
47 | __future__.CO_FUTURE_PRINT_FUNCTION = 65536 | |
48 |
|
48 | |||
49 | import IPython |
|
49 | import IPython | |
50 | from IPython.core import debugger, oinspect |
|
50 | from IPython.core import debugger, oinspect | |
51 | from IPython.core.error import TryNext |
|
51 | from IPython.core.error import TryNext | |
52 | from IPython.core.error import UsageError |
|
52 | from IPython.core.error import UsageError | |
53 | from IPython.core.fakemodule import FakeModule |
|
53 | from IPython.core.fakemodule import FakeModule | |
54 | from IPython.core.macro import Macro |
|
54 | from IPython.core.macro import Macro | |
55 | from IPython.core import page |
|
55 | from IPython.core import page | |
56 | from IPython.core.prefilter import ESC_MAGIC |
|
56 | from IPython.core.prefilter import ESC_MAGIC | |
57 | from IPython.lib.pylabtools import mpl_runner |
|
57 | from IPython.lib.pylabtools import mpl_runner | |
58 | from IPython.external.Itpl import itpl, printpl |
|
58 | from IPython.external.Itpl import itpl, printpl | |
59 | from IPython.testing import decorators as testdec |
|
59 | from IPython.testing import decorators as testdec | |
60 | from IPython.utils.io import file_read, nlprint |
|
60 | from IPython.utils.io import file_read, nlprint | |
61 | import IPython.utils.io |
|
61 | import IPython.utils.io | |
62 | from IPython.utils.path import get_py_filename |
|
62 | from IPython.utils.path import get_py_filename | |
63 | from IPython.utils.process import arg_split, abbrev_cwd |
|
63 | from IPython.utils.process import arg_split, abbrev_cwd | |
64 | from IPython.utils.terminal import set_term_title |
|
64 | from IPython.utils.terminal import set_term_title | |
65 | from IPython.utils.text import LSString, SList, StringTypes, format_screen |
|
65 | from IPython.utils.text import LSString, SList, StringTypes, format_screen | |
66 | from IPython.utils.timing import clock, clock2 |
|
66 | from IPython.utils.timing import clock, clock2 | |
67 | from IPython.utils.warn import warn, error |
|
67 | from IPython.utils.warn import warn, error | |
68 | from IPython.utils.ipstruct import Struct |
|
68 | from IPython.utils.ipstruct import Struct | |
69 | import IPython.utils.generics |
|
69 | import IPython.utils.generics | |
70 |
|
70 | |||
71 | #----------------------------------------------------------------------------- |
|
71 | #----------------------------------------------------------------------------- | |
72 | # Utility functions |
|
72 | # Utility functions | |
73 | #----------------------------------------------------------------------------- |
|
73 | #----------------------------------------------------------------------------- | |
74 |
|
74 | |||
75 | def on_off(tag): |
|
75 | def on_off(tag): | |
76 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" |
|
76 | """Return an ON/OFF string for a 1/0 input. Simple utility function.""" | |
77 | return ['OFF','ON'][tag] |
|
77 | return ['OFF','ON'][tag] | |
78 |
|
78 | |||
79 | class Bunch: pass |
|
79 | class Bunch: pass | |
80 |
|
80 | |||
81 | def compress_dhist(dh): |
|
81 | def compress_dhist(dh): | |
82 | head, tail = dh[:-10], dh[-10:] |
|
82 | head, tail = dh[:-10], dh[-10:] | |
83 |
|
83 | |||
84 | newhead = [] |
|
84 | newhead = [] | |
85 | done = set() |
|
85 | done = set() | |
86 | for h in head: |
|
86 | for h in head: | |
87 | if h in done: |
|
87 | if h in done: | |
88 | continue |
|
88 | continue | |
89 | newhead.append(h) |
|
89 | newhead.append(h) | |
90 | done.add(h) |
|
90 | done.add(h) | |
91 |
|
91 | |||
92 | return newhead + tail |
|
92 | return newhead + tail | |
93 |
|
93 | |||
94 |
|
94 | |||
95 | #*************************************************************************** |
|
95 | #*************************************************************************** | |
96 | # Main class implementing Magic functionality |
|
96 | # Main class implementing Magic functionality | |
97 |
|
97 | |||
98 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors |
|
98 | # XXX - for some odd reason, if Magic is made a new-style class, we get errors | |
99 | # on construction of the main InteractiveShell object. Something odd is going |
|
99 | # on construction of the main InteractiveShell object. Something odd is going | |
100 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but |
|
100 | # on with super() calls, Configurable and the MRO... For now leave it as-is, but | |
101 | # eventually this needs to be clarified. |
|
101 | # eventually this needs to be clarified. | |
102 | # BG: This is because InteractiveShell inherits from this, but is itself a |
|
102 | # BG: This is because InteractiveShell inherits from this, but is itself a | |
103 | # Configurable. This messes up the MRO in some way. The fix is that we need to |
|
103 | # Configurable. This messes up the MRO in some way. The fix is that we need to | |
104 | # make Magic a configurable that InteractiveShell does not subclass. |
|
104 | # make Magic a configurable that InteractiveShell does not subclass. | |
105 |
|
105 | |||
106 | class Magic: |
|
106 | class Magic: | |
107 | """Magic functions for InteractiveShell. |
|
107 | """Magic functions for InteractiveShell. | |
108 |
|
108 | |||
109 | Shell functions which can be reached as %function_name. All magic |
|
109 | Shell functions which can be reached as %function_name. All magic | |
110 | functions should accept a string, which they can parse for their own |
|
110 | functions should accept a string, which they can parse for their own | |
111 | needs. This can make some functions easier to type, eg `%cd ../` |
|
111 | needs. This can make some functions easier to type, eg `%cd ../` | |
112 | vs. `%cd("../")` |
|
112 | vs. `%cd("../")` | |
113 |
|
113 | |||
114 | ALL definitions MUST begin with the prefix magic_. The user won't need it |
|
114 | ALL definitions MUST begin with the prefix magic_. The user won't need it | |
115 | at the command line, but it is is needed in the definition. """ |
|
115 | at the command line, but it is is needed in the definition. """ | |
116 |
|
116 | |||
117 | # class globals |
|
117 | # class globals | |
118 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', |
|
118 | auto_status = ['Automagic is OFF, % prefix IS needed for magic functions.', | |
119 | 'Automagic is ON, % prefix NOT needed for magic functions.'] |
|
119 | 'Automagic is ON, % prefix NOT needed for magic functions.'] | |
120 |
|
120 | |||
121 | #...................................................................... |
|
121 | #...................................................................... | |
122 | # some utility functions |
|
122 | # some utility functions | |
123 |
|
123 | |||
124 | def __init__(self,shell): |
|
124 | def __init__(self,shell): | |
125 |
|
125 | |||
126 | self.options_table = {} |
|
126 | self.options_table = {} | |
127 | if profile is None: |
|
127 | if profile is None: | |
128 | self.magic_prun = self.profile_missing_notice |
|
128 | self.magic_prun = self.profile_missing_notice | |
129 | self.shell = shell |
|
129 | self.shell = shell | |
130 |
|
130 | |||
131 | # namespace for holding state we may need |
|
131 | # namespace for holding state we may need | |
132 | self._magic_state = Bunch() |
|
132 | self._magic_state = Bunch() | |
133 |
|
133 | |||
134 | def profile_missing_notice(self, *args, **kwargs): |
|
134 | def profile_missing_notice(self, *args, **kwargs): | |
135 | error("""\ |
|
135 | error("""\ | |
136 | The profile module could not be found. It has been removed from the standard |
|
136 | The profile module could not be found. It has been removed from the standard | |
137 | python packages because of its non-free license. To use profiling, install the |
|
137 | python packages because of its non-free license. To use profiling, install the | |
138 | python-profiler package from non-free.""") |
|
138 | python-profiler package from non-free.""") | |
139 |
|
139 | |||
140 | def default_option(self,fn,optstr): |
|
140 | def default_option(self,fn,optstr): | |
141 | """Make an entry in the options_table for fn, with value optstr""" |
|
141 | """Make an entry in the options_table for fn, with value optstr""" | |
142 |
|
142 | |||
143 | if fn not in self.lsmagic(): |
|
143 | if fn not in self.lsmagic(): | |
144 | error("%s is not a magic function" % fn) |
|
144 | error("%s is not a magic function" % fn) | |
145 | self.options_table[fn] = optstr |
|
145 | self.options_table[fn] = optstr | |
146 |
|
146 | |||
147 | def lsmagic(self): |
|
147 | def lsmagic(self): | |
148 | """Return a list of currently available magic functions. |
|
148 | """Return a list of currently available magic functions. | |
149 |
|
149 | |||
150 | Gives a list of the bare names after mangling (['ls','cd', ...], not |
|
150 | Gives a list of the bare names after mangling (['ls','cd', ...], not | |
151 | ['magic_ls','magic_cd',...]""" |
|
151 | ['magic_ls','magic_cd',...]""" | |
152 |
|
152 | |||
153 | # FIXME. This needs a cleanup, in the way the magics list is built. |
|
153 | # FIXME. This needs a cleanup, in the way the magics list is built. | |
154 |
|
154 | |||
155 | # magics in class definition |
|
155 | # magics in class definition | |
156 | class_magic = lambda fn: fn.startswith('magic_') and \ |
|
156 | class_magic = lambda fn: fn.startswith('magic_') and \ | |
157 | callable(Magic.__dict__[fn]) |
|
157 | callable(Magic.__dict__[fn]) | |
158 | # in instance namespace (run-time user additions) |
|
158 | # in instance namespace (run-time user additions) | |
159 | inst_magic = lambda fn: fn.startswith('magic_') and \ |
|
159 | inst_magic = lambda fn: fn.startswith('magic_') and \ | |
160 | callable(self.__dict__[fn]) |
|
160 | callable(self.__dict__[fn]) | |
161 | # and bound magics by user (so they can access self): |
|
161 | # and bound magics by user (so they can access self): | |
162 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ |
|
162 | inst_bound_magic = lambda fn: fn.startswith('magic_') and \ | |
163 | callable(self.__class__.__dict__[fn]) |
|
163 | callable(self.__class__.__dict__[fn]) | |
164 | magics = filter(class_magic,Magic.__dict__.keys()) + \ |
|
164 | magics = filter(class_magic,Magic.__dict__.keys()) + \ | |
165 | filter(inst_magic,self.__dict__.keys()) + \ |
|
165 | filter(inst_magic,self.__dict__.keys()) + \ | |
166 | filter(inst_bound_magic,self.__class__.__dict__.keys()) |
|
166 | filter(inst_bound_magic,self.__class__.__dict__.keys()) | |
167 | out = [] |
|
167 | out = [] | |
168 | for fn in set(magics): |
|
168 | for fn in set(magics): | |
169 | out.append(fn.replace('magic_','',1)) |
|
169 | out.append(fn.replace('magic_','',1)) | |
170 | out.sort() |
|
170 | out.sort() | |
171 | return out |
|
171 | return out | |
172 |
|
172 | |||
173 | def extract_input_slices(self,slices,raw=False): |
|
173 | def extract_input_slices(self,slices,raw=False): | |
174 | """Return as a string a set of input history slices. |
|
174 | """Return as a string a set of input history slices. | |
175 |
|
175 | |||
176 | Inputs: |
|
176 | Inputs: | |
177 |
|
177 | |||
178 | - slices: the set of slices is given as a list of strings (like |
|
178 | - slices: the set of slices is given as a list of strings (like | |
179 | ['1','4:8','9'], since this function is for use by magic functions |
|
179 | ['1','4:8','9'], since this function is for use by magic functions | |
180 | which get their arguments as strings. |
|
180 | which get their arguments as strings. | |
181 |
|
181 | |||
182 | Optional inputs: |
|
182 | Optional inputs: | |
183 |
|
183 | |||
184 | - raw(False): by default, the processed input is used. If this is |
|
184 | - raw(False): by default, the processed input is used. If this is | |
185 | true, the raw input history is used instead. |
|
185 | true, the raw input history is used instead. | |
186 |
|
186 | |||
187 | Note that slices can be called with two notations: |
|
187 | Note that slices can be called with two notations: | |
188 |
|
188 | |||
189 | N:M -> standard python form, means including items N...(M-1). |
|
189 | N:M -> standard python form, means including items N...(M-1). | |
190 |
|
190 | |||
191 | N-M -> include items N..M (closed endpoint).""" |
|
191 | N-M -> include items N..M (closed endpoint).""" | |
192 |
|
192 | |||
193 | if raw: |
|
193 | if raw: | |
194 | hist = self.shell.input_hist_raw |
|
194 | hist = self.shell.input_hist_raw | |
195 | else: |
|
195 | else: | |
196 | hist = self.shell.input_hist |
|
196 | hist = self.shell.input_hist | |
197 |
|
197 | |||
198 | cmds = [] |
|
198 | cmds = [] | |
199 | for chunk in slices: |
|
199 | for chunk in slices: | |
200 | if ':' in chunk: |
|
200 | if ':' in chunk: | |
201 | ini,fin = map(int,chunk.split(':')) |
|
201 | ini,fin = map(int,chunk.split(':')) | |
202 | elif '-' in chunk: |
|
202 | elif '-' in chunk: | |
203 | ini,fin = map(int,chunk.split('-')) |
|
203 | ini,fin = map(int,chunk.split('-')) | |
204 | fin += 1 |
|
204 | fin += 1 | |
205 | else: |
|
205 | else: | |
206 | ini = int(chunk) |
|
206 | ini = int(chunk) | |
207 | fin = ini+1 |
|
207 | fin = ini+1 | |
208 | cmds.append(hist[ini:fin]) |
|
208 | cmds.append(hist[ini:fin]) | |
209 | return cmds |
|
209 | return cmds | |
210 |
|
210 | |||
211 | def arg_err(self,func): |
|
211 | def arg_err(self,func): | |
212 | """Print docstring if incorrect arguments were passed""" |
|
212 | """Print docstring if incorrect arguments were passed""" | |
213 | print 'Error in arguments:' |
|
213 | print 'Error in arguments:' | |
214 | print oinspect.getdoc(func) |
|
214 | print oinspect.getdoc(func) | |
215 |
|
215 | |||
216 | def format_latex(self,strng): |
|
216 | def format_latex(self,strng): | |
217 | """Format a string for latex inclusion.""" |
|
217 | """Format a string for latex inclusion.""" | |
218 |
|
218 | |||
219 | # Characters that need to be escaped for latex: |
|
219 | # Characters that need to be escaped for latex: | |
220 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) |
|
220 | escape_re = re.compile(r'(%|_|\$|#|&)',re.MULTILINE) | |
221 | # Magic command names as headers: |
|
221 | # Magic command names as headers: | |
222 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, |
|
222 | cmd_name_re = re.compile(r'^(%s.*?):' % ESC_MAGIC, | |
223 | re.MULTILINE) |
|
223 | re.MULTILINE) | |
224 | # Magic commands |
|
224 | # Magic commands | |
225 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, |
|
225 | cmd_re = re.compile(r'(?P<cmd>%s.+?\b)(?!\}\}:)' % ESC_MAGIC, | |
226 | re.MULTILINE) |
|
226 | re.MULTILINE) | |
227 | # Paragraph continue |
|
227 | # Paragraph continue | |
228 | par_re = re.compile(r'\\$',re.MULTILINE) |
|
228 | par_re = re.compile(r'\\$',re.MULTILINE) | |
229 |
|
229 | |||
230 | # The "\n" symbol |
|
230 | # The "\n" symbol | |
231 | newline_re = re.compile(r'\\n') |
|
231 | newline_re = re.compile(r'\\n') | |
232 |
|
232 | |||
233 | # Now build the string for output: |
|
233 | # Now build the string for output: | |
234 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) |
|
234 | #strng = cmd_name_re.sub(r'\n\\texttt{\\textsl{\\large \1}}:',strng) | |
235 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', |
|
235 | strng = cmd_name_re.sub(r'\n\\bigskip\n\\texttt{\\textbf{ \1}}:', | |
236 | strng) |
|
236 | strng) | |
237 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) |
|
237 | strng = cmd_re.sub(r'\\texttt{\g<cmd>}',strng) | |
238 | strng = par_re.sub(r'\\\\',strng) |
|
238 | strng = par_re.sub(r'\\\\',strng) | |
239 | strng = escape_re.sub(r'\\\1',strng) |
|
239 | strng = escape_re.sub(r'\\\1',strng) | |
240 | strng = newline_re.sub(r'\\textbackslash{}n',strng) |
|
240 | strng = newline_re.sub(r'\\textbackslash{}n',strng) | |
241 | return strng |
|
241 | return strng | |
242 |
|
242 | |||
243 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): |
|
243 | def parse_options(self,arg_str,opt_str,*long_opts,**kw): | |
244 | """Parse options passed to an argument string. |
|
244 | """Parse options passed to an argument string. | |
245 |
|
245 | |||
246 | The interface is similar to that of getopt(), but it returns back a |
|
246 | The interface is similar to that of getopt(), but it returns back a | |
247 | Struct with the options as keys and the stripped argument string still |
|
247 | Struct with the options as keys and the stripped argument string still | |
248 | as a string. |
|
248 | as a string. | |
249 |
|
249 | |||
250 | arg_str is quoted as a true sys.argv vector by using shlex.split. |
|
250 | arg_str is quoted as a true sys.argv vector by using shlex.split. | |
251 | This allows us to easily expand variables, glob files, quote |
|
251 | This allows us to easily expand variables, glob files, quote | |
252 | arguments, etc. |
|
252 | arguments, etc. | |
253 |
|
253 | |||
254 | Options: |
|
254 | Options: | |
255 | -mode: default 'string'. If given as 'list', the argument string is |
|
255 | -mode: default 'string'. If given as 'list', the argument string is | |
256 | returned as a list (split on whitespace) instead of a string. |
|
256 | returned as a list (split on whitespace) instead of a string. | |
257 |
|
257 | |||
258 | -list_all: put all option values in lists. Normally only options |
|
258 | -list_all: put all option values in lists. Normally only options | |
259 | appearing more than once are put in a list. |
|
259 | appearing more than once are put in a list. | |
260 |
|
260 | |||
261 | -posix (True): whether to split the input line in POSIX mode or not, |
|
261 | -posix (True): whether to split the input line in POSIX mode or not, | |
262 | as per the conventions outlined in the shlex module from the |
|
262 | as per the conventions outlined in the shlex module from the | |
263 | standard library.""" |
|
263 | standard library.""" | |
264 |
|
264 | |||
265 | # inject default options at the beginning of the input line |
|
265 | # inject default options at the beginning of the input line | |
266 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') |
|
266 | caller = sys._getframe(1).f_code.co_name.replace('magic_','') | |
267 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) |
|
267 | arg_str = '%s %s' % (self.options_table.get(caller,''),arg_str) | |
268 |
|
268 | |||
269 | mode = kw.get('mode','string') |
|
269 | mode = kw.get('mode','string') | |
270 | if mode not in ['string','list']: |
|
270 | if mode not in ['string','list']: | |
271 | raise ValueError,'incorrect mode given: %s' % mode |
|
271 | raise ValueError,'incorrect mode given: %s' % mode | |
272 | # Get options |
|
272 | # Get options | |
273 | list_all = kw.get('list_all',0) |
|
273 | list_all = kw.get('list_all',0) | |
274 | posix = kw.get('posix', os.name == 'posix') |
|
274 | posix = kw.get('posix', os.name == 'posix') | |
275 |
|
275 | |||
276 | # Check if we have more than one argument to warrant extra processing: |
|
276 | # Check if we have more than one argument to warrant extra processing: | |
277 | odict = {} # Dictionary with options |
|
277 | odict = {} # Dictionary with options | |
278 | args = arg_str.split() |
|
278 | args = arg_str.split() | |
279 | if len(args) >= 1: |
|
279 | if len(args) >= 1: | |
280 | # If the list of inputs only has 0 or 1 thing in it, there's no |
|
280 | # If the list of inputs only has 0 or 1 thing in it, there's no | |
281 | # need to look for options |
|
281 | # need to look for options | |
282 | argv = arg_split(arg_str,posix) |
|
282 | argv = arg_split(arg_str,posix) | |
283 | # Do regular option processing |
|
283 | # Do regular option processing | |
284 | try: |
|
284 | try: | |
285 | opts,args = getopt(argv,opt_str,*long_opts) |
|
285 | opts,args = getopt(argv,opt_str,*long_opts) | |
286 | except GetoptError,e: |
|
286 | except GetoptError,e: | |
287 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, |
|
287 | raise UsageError('%s ( allowed: "%s" %s)' % (e.msg,opt_str, | |
288 | " ".join(long_opts))) |
|
288 | " ".join(long_opts))) | |
289 | for o,a in opts: |
|
289 | for o,a in opts: | |
290 | if o.startswith('--'): |
|
290 | if o.startswith('--'): | |
291 | o = o[2:] |
|
291 | o = o[2:] | |
292 | else: |
|
292 | else: | |
293 | o = o[1:] |
|
293 | o = o[1:] | |
294 | try: |
|
294 | try: | |
295 | odict[o].append(a) |
|
295 | odict[o].append(a) | |
296 | except AttributeError: |
|
296 | except AttributeError: | |
297 | odict[o] = [odict[o],a] |
|
297 | odict[o] = [odict[o],a] | |
298 | except KeyError: |
|
298 | except KeyError: | |
299 | if list_all: |
|
299 | if list_all: | |
300 | odict[o] = [a] |
|
300 | odict[o] = [a] | |
301 | else: |
|
301 | else: | |
302 | odict[o] = a |
|
302 | odict[o] = a | |
303 |
|
303 | |||
304 | # Prepare opts,args for return |
|
304 | # Prepare opts,args for return | |
305 | opts = Struct(odict) |
|
305 | opts = Struct(odict) | |
306 | if mode == 'string': |
|
306 | if mode == 'string': | |
307 | args = ' '.join(args) |
|
307 | args = ' '.join(args) | |
308 |
|
308 | |||
309 | return opts,args |
|
309 | return opts,args | |
310 |
|
310 | |||
311 | #...................................................................... |
|
311 | #...................................................................... | |
312 | # And now the actual magic functions |
|
312 | # And now the actual magic functions | |
313 |
|
313 | |||
314 | # Functions for IPython shell work (vars,funcs, config, etc) |
|
314 | # Functions for IPython shell work (vars,funcs, config, etc) | |
315 | def magic_lsmagic(self, parameter_s = ''): |
|
315 | def magic_lsmagic(self, parameter_s = ''): | |
316 | """List currently available magic functions.""" |
|
316 | """List currently available magic functions.""" | |
317 | mesc = ESC_MAGIC |
|
317 | mesc = ESC_MAGIC | |
318 | print 'Available magic functions:\n'+mesc+\ |
|
318 | print 'Available magic functions:\n'+mesc+\ | |
319 | (' '+mesc).join(self.lsmagic()) |
|
319 | (' '+mesc).join(self.lsmagic()) | |
320 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
320 | print '\n' + Magic.auto_status[self.shell.automagic] | |
321 | return None |
|
321 | return None | |
322 |
|
322 | |||
323 | def magic_magic(self, parameter_s = ''): |
|
323 | def magic_magic(self, parameter_s = ''): | |
324 | """Print information about the magic function system. |
|
324 | """Print information about the magic function system. | |
325 |
|
325 | |||
326 | Supported formats: -latex, -brief, -rest |
|
326 | Supported formats: -latex, -brief, -rest | |
327 | """ |
|
327 | """ | |
328 |
|
328 | |||
329 | mode = '' |
|
329 | mode = '' | |
330 | try: |
|
330 | try: | |
331 | if parameter_s.split()[0] == '-latex': |
|
331 | if parameter_s.split()[0] == '-latex': | |
332 | mode = 'latex' |
|
332 | mode = 'latex' | |
333 | if parameter_s.split()[0] == '-brief': |
|
333 | if parameter_s.split()[0] == '-brief': | |
334 | mode = 'brief' |
|
334 | mode = 'brief' | |
335 | if parameter_s.split()[0] == '-rest': |
|
335 | if parameter_s.split()[0] == '-rest': | |
336 | mode = 'rest' |
|
336 | mode = 'rest' | |
337 | rest_docs = [] |
|
337 | rest_docs = [] | |
338 | except: |
|
338 | except: | |
339 | pass |
|
339 | pass | |
340 |
|
340 | |||
341 | magic_docs = [] |
|
341 | magic_docs = [] | |
342 | for fname in self.lsmagic(): |
|
342 | for fname in self.lsmagic(): | |
343 | mname = 'magic_' + fname |
|
343 | mname = 'magic_' + fname | |
344 | for space in (Magic,self,self.__class__): |
|
344 | for space in (Magic,self,self.__class__): | |
345 | try: |
|
345 | try: | |
346 | fn = space.__dict__[mname] |
|
346 | fn = space.__dict__[mname] | |
347 | except KeyError: |
|
347 | except KeyError: | |
348 | pass |
|
348 | pass | |
349 | else: |
|
349 | else: | |
350 | break |
|
350 | break | |
351 | if mode == 'brief': |
|
351 | if mode == 'brief': | |
352 | # only first line |
|
352 | # only first line | |
353 | if fn.__doc__: |
|
353 | if fn.__doc__: | |
354 | fndoc = fn.__doc__.split('\n',1)[0] |
|
354 | fndoc = fn.__doc__.split('\n',1)[0] | |
355 | else: |
|
355 | else: | |
356 | fndoc = 'No documentation' |
|
356 | fndoc = 'No documentation' | |
357 | else: |
|
357 | else: | |
358 | if fn.__doc__: |
|
358 | if fn.__doc__: | |
359 | fndoc = fn.__doc__.rstrip() |
|
359 | fndoc = fn.__doc__.rstrip() | |
360 | else: |
|
360 | else: | |
361 | fndoc = 'No documentation' |
|
361 | fndoc = 'No documentation' | |
362 |
|
362 | |||
363 |
|
363 | |||
364 | if mode == 'rest': |
|
364 | if mode == 'rest': | |
365 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, |
|
365 | rest_docs.append('**%s%s**::\n\n\t%s\n\n' %(ESC_MAGIC, | |
366 | fname,fndoc)) |
|
366 | fname,fndoc)) | |
367 |
|
367 | |||
368 | else: |
|
368 | else: | |
369 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, |
|
369 | magic_docs.append('%s%s:\n\t%s\n' %(ESC_MAGIC, | |
370 | fname,fndoc)) |
|
370 | fname,fndoc)) | |
371 |
|
371 | |||
372 | magic_docs = ''.join(magic_docs) |
|
372 | magic_docs = ''.join(magic_docs) | |
373 |
|
373 | |||
374 | if mode == 'rest': |
|
374 | if mode == 'rest': | |
375 | return "".join(rest_docs) |
|
375 | return "".join(rest_docs) | |
376 |
|
376 | |||
377 | if mode == 'latex': |
|
377 | if mode == 'latex': | |
378 | print self.format_latex(magic_docs) |
|
378 | print self.format_latex(magic_docs) | |
379 | return |
|
379 | return | |
380 | else: |
|
380 | else: | |
381 | magic_docs = format_screen(magic_docs) |
|
381 | magic_docs = format_screen(magic_docs) | |
382 | if mode == 'brief': |
|
382 | if mode == 'brief': | |
383 | return magic_docs |
|
383 | return magic_docs | |
384 |
|
384 | |||
385 | outmsg = """ |
|
385 | outmsg = """ | |
386 | IPython's 'magic' functions |
|
386 | IPython's 'magic' functions | |
387 | =========================== |
|
387 | =========================== | |
388 |
|
388 | |||
389 | The magic function system provides a series of functions which allow you to |
|
389 | The magic function system provides a series of functions which allow you to | |
390 | control the behavior of IPython itself, plus a lot of system-type |
|
390 | control the behavior of IPython itself, plus a lot of system-type | |
391 | features. All these functions are prefixed with a % character, but parameters |
|
391 | features. All these functions are prefixed with a % character, but parameters | |
392 | are given without parentheses or quotes. |
|
392 | are given without parentheses or quotes. | |
393 |
|
393 | |||
394 | NOTE: If you have 'automagic' enabled (via the command line option or with the |
|
394 | NOTE: If you have 'automagic' enabled (via the command line option or with the | |
395 | %automagic function), you don't need to type in the % explicitly. By default, |
|
395 | %automagic function), you don't need to type in the % explicitly. By default, | |
396 | IPython ships with automagic on, so you should only rarely need the % escape. |
|
396 | IPython ships with automagic on, so you should only rarely need the % escape. | |
397 |
|
397 | |||
398 | Example: typing '%cd mydir' (without the quotes) changes you working directory |
|
398 | Example: typing '%cd mydir' (without the quotes) changes you working directory | |
399 | to 'mydir', if it exists. |
|
399 | to 'mydir', if it exists. | |
400 |
|
400 | |||
401 | You can define your own magic functions to extend the system. See the supplied |
|
401 | You can define your own magic functions to extend the system. See the supplied | |
402 | ipythonrc and example-magic.py files for details (in your ipython |
|
402 | ipythonrc and example-magic.py files for details (in your ipython | |
403 | configuration directory, typically $HOME/.ipython/). |
|
403 | configuration directory, typically $HOME/.ipython/). | |
404 |
|
404 | |||
405 | You can also define your own aliased names for magic functions. In your |
|
405 | You can also define your own aliased names for magic functions. In your | |
406 | ipythonrc file, placing a line like: |
|
406 | ipythonrc file, placing a line like: | |
407 |
|
407 | |||
408 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile |
|
408 | execute __IPYTHON__.magic_pf = __IPYTHON__.magic_profile | |
409 |
|
409 | |||
410 | will define %pf as a new name for %profile. |
|
410 | will define %pf as a new name for %profile. | |
411 |
|
411 | |||
412 | You can also call magics in code using the magic() function, which IPython |
|
412 | You can also call magics in code using the magic() function, which IPython | |
413 | automatically adds to the builtin namespace. Type 'magic?' for details. |
|
413 | automatically adds to the builtin namespace. Type 'magic?' for details. | |
414 |
|
414 | |||
415 | For a list of the available magic functions, use %lsmagic. For a description |
|
415 | For a list of the available magic functions, use %lsmagic. For a description | |
416 | of any of them, type %magic_name?, e.g. '%cd?'. |
|
416 | of any of them, type %magic_name?, e.g. '%cd?'. | |
417 |
|
417 | |||
418 | Currently the magic system has the following functions:\n""" |
|
418 | Currently the magic system has the following functions:\n""" | |
419 |
|
419 | |||
420 | mesc = ESC_MAGIC |
|
420 | mesc = ESC_MAGIC | |
421 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" |
|
421 | outmsg = ("%s\n%s\n\nSummary of magic functions (from %slsmagic):" | |
422 | "\n\n%s%s\n\n%s" % (outmsg, |
|
422 | "\n\n%s%s\n\n%s" % (outmsg, | |
423 | magic_docs,mesc,mesc, |
|
423 | magic_docs,mesc,mesc, | |
424 | (' '+mesc).join(self.lsmagic()), |
|
424 | (' '+mesc).join(self.lsmagic()), | |
425 | Magic.auto_status[self.shell.automagic] ) ) |
|
425 | Magic.auto_status[self.shell.automagic] ) ) | |
426 | page.page(outmsg) |
|
426 | page.page(outmsg) | |
427 |
|
427 | |||
428 | def magic_automagic(self, parameter_s = ''): |
|
428 | def magic_automagic(self, parameter_s = ''): | |
429 | """Make magic functions callable without having to type the initial %. |
|
429 | """Make magic functions callable without having to type the initial %. | |
430 |
|
430 | |||
431 | Without argumentsl toggles on/off (when off, you must call it as |
|
431 | Without argumentsl toggles on/off (when off, you must call it as | |
432 | %automagic, of course). With arguments it sets the value, and you can |
|
432 | %automagic, of course). With arguments it sets the value, and you can | |
433 | use any of (case insensitive): |
|
433 | use any of (case insensitive): | |
434 |
|
434 | |||
435 | - on,1,True: to activate |
|
435 | - on,1,True: to activate | |
436 |
|
436 | |||
437 | - off,0,False: to deactivate. |
|
437 | - off,0,False: to deactivate. | |
438 |
|
438 | |||
439 | Note that magic functions have lowest priority, so if there's a |
|
439 | Note that magic functions have lowest priority, so if there's a | |
440 | variable whose name collides with that of a magic fn, automagic won't |
|
440 | variable whose name collides with that of a magic fn, automagic won't | |
441 | work for that function (you get the variable instead). However, if you |
|
441 | work for that function (you get the variable instead). However, if you | |
442 | delete the variable (del var), the previously shadowed magic function |
|
442 | delete the variable (del var), the previously shadowed magic function | |
443 | becomes visible to automagic again.""" |
|
443 | becomes visible to automagic again.""" | |
444 |
|
444 | |||
445 | arg = parameter_s.lower() |
|
445 | arg = parameter_s.lower() | |
446 | if parameter_s in ('on','1','true'): |
|
446 | if parameter_s in ('on','1','true'): | |
447 | self.shell.automagic = True |
|
447 | self.shell.automagic = True | |
448 | elif parameter_s in ('off','0','false'): |
|
448 | elif parameter_s in ('off','0','false'): | |
449 | self.shell.automagic = False |
|
449 | self.shell.automagic = False | |
450 | else: |
|
450 | else: | |
451 | self.shell.automagic = not self.shell.automagic |
|
451 | self.shell.automagic = not self.shell.automagic | |
452 | print '\n' + Magic.auto_status[self.shell.automagic] |
|
452 | print '\n' + Magic.auto_status[self.shell.automagic] | |
453 |
|
453 | |||
454 | @testdec.skip_doctest |
|
454 | @testdec.skip_doctest | |
455 | def magic_autocall(self, parameter_s = ''): |
|
455 | def magic_autocall(self, parameter_s = ''): | |
456 | """Make functions callable without having to type parentheses. |
|
456 | """Make functions callable without having to type parentheses. | |
457 |
|
457 | |||
458 | Usage: |
|
458 | Usage: | |
459 |
|
459 | |||
460 | %autocall [mode] |
|
460 | %autocall [mode] | |
461 |
|
461 | |||
462 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the |
|
462 | The mode can be one of: 0->Off, 1->Smart, 2->Full. If not given, the | |
463 | value is toggled on and off (remembering the previous state). |
|
463 | value is toggled on and off (remembering the previous state). | |
464 |
|
464 | |||
465 | In more detail, these values mean: |
|
465 | In more detail, these values mean: | |
466 |
|
466 | |||
467 | 0 -> fully disabled |
|
467 | 0 -> fully disabled | |
468 |
|
468 | |||
469 | 1 -> active, but do not apply if there are no arguments on the line. |
|
469 | 1 -> active, but do not apply if there are no arguments on the line. | |
470 |
|
470 | |||
471 | In this mode, you get: |
|
471 | In this mode, you get: | |
472 |
|
472 | |||
473 | In [1]: callable |
|
473 | In [1]: callable | |
474 | Out[1]: <built-in function callable> |
|
474 | Out[1]: <built-in function callable> | |
475 |
|
475 | |||
476 | In [2]: callable 'hello' |
|
476 | In [2]: callable 'hello' | |
477 | ------> callable('hello') |
|
477 | ------> callable('hello') | |
478 | Out[2]: False |
|
478 | Out[2]: False | |
479 |
|
479 | |||
480 | 2 -> Active always. Even if no arguments are present, the callable |
|
480 | 2 -> Active always. Even if no arguments are present, the callable | |
481 | object is called: |
|
481 | object is called: | |
482 |
|
482 | |||
483 | In [2]: float |
|
483 | In [2]: float | |
484 | ------> float() |
|
484 | ------> float() | |
485 | Out[2]: 0.0 |
|
485 | Out[2]: 0.0 | |
486 |
|
486 | |||
487 | Note that even with autocall off, you can still use '/' at the start of |
|
487 | Note that even with autocall off, you can still use '/' at the start of | |
488 | a line to treat the first argument on the command line as a function |
|
488 | a line to treat the first argument on the command line as a function | |
489 | and add parentheses to it: |
|
489 | and add parentheses to it: | |
490 |
|
490 | |||
491 | In [8]: /str 43 |
|
491 | In [8]: /str 43 | |
492 | ------> str(43) |
|
492 | ------> str(43) | |
493 | Out[8]: '43' |
|
493 | Out[8]: '43' | |
494 |
|
494 | |||
495 | # all-random (note for auto-testing) |
|
495 | # all-random (note for auto-testing) | |
496 | """ |
|
496 | """ | |
497 |
|
497 | |||
498 | if parameter_s: |
|
498 | if parameter_s: | |
499 | arg = int(parameter_s) |
|
499 | arg = int(parameter_s) | |
500 | else: |
|
500 | else: | |
501 | arg = 'toggle' |
|
501 | arg = 'toggle' | |
502 |
|
502 | |||
503 | if not arg in (0,1,2,'toggle'): |
|
503 | if not arg in (0,1,2,'toggle'): | |
504 | error('Valid modes: (0->Off, 1->Smart, 2->Full') |
|
504 | error('Valid modes: (0->Off, 1->Smart, 2->Full') | |
505 | return |
|
505 | return | |
506 |
|
506 | |||
507 | if arg in (0,1,2): |
|
507 | if arg in (0,1,2): | |
508 | self.shell.autocall = arg |
|
508 | self.shell.autocall = arg | |
509 | else: # toggle |
|
509 | else: # toggle | |
510 | if self.shell.autocall: |
|
510 | if self.shell.autocall: | |
511 | self._magic_state.autocall_save = self.shell.autocall |
|
511 | self._magic_state.autocall_save = self.shell.autocall | |
512 | self.shell.autocall = 0 |
|
512 | self.shell.autocall = 0 | |
513 | else: |
|
513 | else: | |
514 | try: |
|
514 | try: | |
515 | self.shell.autocall = self._magic_state.autocall_save |
|
515 | self.shell.autocall = self._magic_state.autocall_save | |
516 | except AttributeError: |
|
516 | except AttributeError: | |
517 | self.shell.autocall = self._magic_state.autocall_save = 1 |
|
517 | self.shell.autocall = self._magic_state.autocall_save = 1 | |
518 |
|
518 | |||
519 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] |
|
519 | print "Automatic calling is:",['OFF','Smart','Full'][self.shell.autocall] | |
520 |
|
520 | |||
521 |
|
521 | |||
522 | def magic_page(self, parameter_s=''): |
|
522 | def magic_page(self, parameter_s=''): | |
523 | """Pretty print the object and display it through a pager. |
|
523 | """Pretty print the object and display it through a pager. | |
524 |
|
524 | |||
525 | %page [options] OBJECT |
|
525 | %page [options] OBJECT | |
526 |
|
526 | |||
527 | If no object is given, use _ (last output). |
|
527 | If no object is given, use _ (last output). | |
528 |
|
528 | |||
529 | Options: |
|
529 | Options: | |
530 |
|
530 | |||
531 | -r: page str(object), don't pretty-print it.""" |
|
531 | -r: page str(object), don't pretty-print it.""" | |
532 |
|
532 | |||
533 | # After a function contributed by Olivier Aubert, slightly modified. |
|
533 | # After a function contributed by Olivier Aubert, slightly modified. | |
534 |
|
534 | |||
535 | # Process options/args |
|
535 | # Process options/args | |
536 | opts,args = self.parse_options(parameter_s,'r') |
|
536 | opts,args = self.parse_options(parameter_s,'r') | |
537 | raw = 'r' in opts |
|
537 | raw = 'r' in opts | |
538 |
|
538 | |||
539 | oname = args and args or '_' |
|
539 | oname = args and args or '_' | |
540 | info = self._ofind(oname) |
|
540 | info = self._ofind(oname) | |
541 | if info['found']: |
|
541 | if info['found']: | |
542 | txt = (raw and str or pformat)( info['obj'] ) |
|
542 | txt = (raw and str or pformat)( info['obj'] ) | |
543 | page.page(txt) |
|
543 | page.page(txt) | |
544 | else: |
|
544 | else: | |
545 | print 'Object `%s` not found' % oname |
|
545 | print 'Object `%s` not found' % oname | |
546 |
|
546 | |||
547 | def magic_profile(self, parameter_s=''): |
|
547 | def magic_profile(self, parameter_s=''): | |
548 | """Print your currently active IPython profile.""" |
|
548 | """Print your currently active IPython profile.""" | |
549 | if self.shell.profile: |
|
549 | if self.shell.profile: | |
550 | printpl('Current IPython profile: $self.shell.profile.') |
|
550 | printpl('Current IPython profile: $self.shell.profile.') | |
551 | else: |
|
551 | else: | |
552 | print 'No profile active.' |
|
552 | print 'No profile active.' | |
553 |
|
553 | |||
554 | def magic_pinfo(self, parameter_s='', namespaces=None): |
|
554 | def magic_pinfo(self, parameter_s='', namespaces=None): | |
555 | """Provide detailed information about an object. |
|
555 | """Provide detailed information about an object. | |
556 |
|
556 | |||
557 | '%pinfo object' is just a synonym for object? or ?object.""" |
|
557 | '%pinfo object' is just a synonym for object? or ?object.""" | |
558 |
|
558 | |||
559 | #print 'pinfo par: <%s>' % parameter_s # dbg |
|
559 | #print 'pinfo par: <%s>' % parameter_s # dbg | |
560 |
|
560 | |||
561 |
|
561 | |||
562 | # detail_level: 0 -> obj? , 1 -> obj?? |
|
562 | # detail_level: 0 -> obj? , 1 -> obj?? | |
563 | detail_level = 0 |
|
563 | detail_level = 0 | |
564 | # We need to detect if we got called as 'pinfo pinfo foo', which can |
|
564 | # We need to detect if we got called as 'pinfo pinfo foo', which can | |
565 | # happen if the user types 'pinfo foo?' at the cmd line. |
|
565 | # happen if the user types 'pinfo foo?' at the cmd line. | |
566 | pinfo,qmark1,oname,qmark2 = \ |
|
566 | pinfo,qmark1,oname,qmark2 = \ | |
567 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() |
|
567 | re.match('(pinfo )?(\?*)(.*?)(\??$)',parameter_s).groups() | |
568 | if pinfo or qmark1 or qmark2: |
|
568 | if pinfo or qmark1 or qmark2: | |
569 | detail_level = 1 |
|
569 | detail_level = 1 | |
570 | if "*" in oname: |
|
570 | if "*" in oname: | |
571 | self.magic_psearch(oname) |
|
571 | self.magic_psearch(oname) | |
572 | else: |
|
572 | else: | |
573 | self.shell._inspect('pinfo', oname, detail_level=detail_level, |
|
573 | self.shell._inspect('pinfo', oname, detail_level=detail_level, | |
574 | namespaces=namespaces) |
|
574 | namespaces=namespaces) | |
575 |
|
575 | |||
576 | def magic_pinfo2(self, parameter_s='', namespaces=None): |
|
576 | def magic_pinfo2(self, parameter_s='', namespaces=None): | |
577 | """Provide extra detailed information about an object. |
|
577 | """Provide extra detailed information about an object. | |
578 |
|
578 | |||
579 | '%pinfo2 object' is just a synonym for object?? or ??object.""" |
|
579 | '%pinfo2 object' is just a synonym for object?? or ??object.""" | |
580 | print 'pinfo2 par: <%s>' % parameter_s # dbg |
|
580 | print 'pinfo2 par: <%s>' % parameter_s # dbg | |
581 | self.shell._inspect('pinfo', parameter_s, detail_level=1, |
|
581 | self.shell._inspect('pinfo', parameter_s, detail_level=1, | |
582 | namespaces=namespaces) |
|
582 | namespaces=namespaces) | |
583 |
|
583 | |||
584 | def magic_pdef(self, parameter_s='', namespaces=None): |
|
584 | def magic_pdef(self, parameter_s='', namespaces=None): | |
585 | """Print the definition header for any callable object. |
|
585 | """Print the definition header for any callable object. | |
586 |
|
586 | |||
587 | If the object is a class, print the constructor information.""" |
|
587 | If the object is a class, print the constructor information.""" | |
588 | self._inspect('pdef',parameter_s, namespaces) |
|
588 | self._inspect('pdef',parameter_s, namespaces) | |
589 |
|
589 | |||
590 | def magic_pdoc(self, parameter_s='', namespaces=None): |
|
590 | def magic_pdoc(self, parameter_s='', namespaces=None): | |
591 | """Print the docstring for an object. |
|
591 | """Print the docstring for an object. | |
592 |
|
592 | |||
593 | If the given object is a class, it will print both the class and the |
|
593 | If the given object is a class, it will print both the class and the | |
594 | constructor docstrings.""" |
|
594 | constructor docstrings.""" | |
595 | self._inspect('pdoc',parameter_s, namespaces) |
|
595 | self._inspect('pdoc',parameter_s, namespaces) | |
596 |
|
596 | |||
597 | def magic_psource(self, parameter_s='', namespaces=None): |
|
597 | def magic_psource(self, parameter_s='', namespaces=None): | |
598 | """Print (or run through pager) the source code for an object.""" |
|
598 | """Print (or run through pager) the source code for an object.""" | |
599 | self._inspect('psource',parameter_s, namespaces) |
|
599 | self._inspect('psource',parameter_s, namespaces) | |
600 |
|
600 | |||
601 | def magic_pfile(self, parameter_s=''): |
|
601 | def magic_pfile(self, parameter_s=''): | |
602 | """Print (or run through pager) the file where an object is defined. |
|
602 | """Print (or run through pager) the file where an object is defined. | |
603 |
|
603 | |||
604 | The file opens at the line where the object definition begins. IPython |
|
604 | The file opens at the line where the object definition begins. IPython | |
605 | will honor the environment variable PAGER if set, and otherwise will |
|
605 | will honor the environment variable PAGER if set, and otherwise will | |
606 | do its best to print the file in a convenient form. |
|
606 | do its best to print the file in a convenient form. | |
607 |
|
607 | |||
608 | If the given argument is not an object currently defined, IPython will |
|
608 | If the given argument is not an object currently defined, IPython will | |
609 | try to interpret it as a filename (automatically adding a .py extension |
|
609 | try to interpret it as a filename (automatically adding a .py extension | |
610 | if needed). You can thus use %pfile as a syntax highlighting code |
|
610 | if needed). You can thus use %pfile as a syntax highlighting code | |
611 | viewer.""" |
|
611 | viewer.""" | |
612 |
|
612 | |||
613 | # first interpret argument as an object name |
|
613 | # first interpret argument as an object name | |
614 | out = self._inspect('pfile',parameter_s) |
|
614 | out = self._inspect('pfile',parameter_s) | |
615 | # if not, try the input as a filename |
|
615 | # if not, try the input as a filename | |
616 | if out == 'not found': |
|
616 | if out == 'not found': | |
617 | try: |
|
617 | try: | |
618 | filename = get_py_filename(parameter_s) |
|
618 | filename = get_py_filename(parameter_s) | |
619 | except IOError,msg: |
|
619 | except IOError,msg: | |
620 | print msg |
|
620 | print msg | |
621 | return |
|
621 | return | |
622 | page.page(self.shell.inspector.format(file(filename).read())) |
|
622 | page.page(self.shell.inspector.format(file(filename).read())) | |
623 |
|
623 | |||
624 | def magic_psearch(self, parameter_s=''): |
|
624 | def magic_psearch(self, parameter_s=''): | |
625 | """Search for object in namespaces by wildcard. |
|
625 | """Search for object in namespaces by wildcard. | |
626 |
|
626 | |||
627 | %psearch [options] PATTERN [OBJECT TYPE] |
|
627 | %psearch [options] PATTERN [OBJECT TYPE] | |
628 |
|
628 | |||
629 | Note: ? can be used as a synonym for %psearch, at the beginning or at |
|
629 | Note: ? can be used as a synonym for %psearch, at the beginning or at | |
630 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the |
|
630 | the end: both a*? and ?a* are equivalent to '%psearch a*'. Still, the | |
631 | rest of the command line must be unchanged (options come first), so |
|
631 | rest of the command line must be unchanged (options come first), so | |
632 | for example the following forms are equivalent |
|
632 | for example the following forms are equivalent | |
633 |
|
633 | |||
634 | %psearch -i a* function |
|
634 | %psearch -i a* function | |
635 | -i a* function? |
|
635 | -i a* function? | |
636 | ?-i a* function |
|
636 | ?-i a* function | |
637 |
|
637 | |||
638 | Arguments: |
|
638 | Arguments: | |
639 |
|
639 | |||
640 | PATTERN |
|
640 | PATTERN | |
641 |
|
641 | |||
642 | where PATTERN is a string containing * as a wildcard similar to its |
|
642 | where PATTERN is a string containing * as a wildcard similar to its | |
643 | use in a shell. The pattern is matched in all namespaces on the |
|
643 | use in a shell. The pattern is matched in all namespaces on the | |
644 | search path. By default objects starting with a single _ are not |
|
644 | search path. By default objects starting with a single _ are not | |
645 | matched, many IPython generated objects have a single |
|
645 | matched, many IPython generated objects have a single | |
646 | underscore. The default is case insensitive matching. Matching is |
|
646 | underscore. The default is case insensitive matching. Matching is | |
647 | also done on the attributes of objects and not only on the objects |
|
647 | also done on the attributes of objects and not only on the objects | |
648 | in a module. |
|
648 | in a module. | |
649 |
|
649 | |||
650 | [OBJECT TYPE] |
|
650 | [OBJECT TYPE] | |
651 |
|
651 | |||
652 | Is the name of a python type from the types module. The name is |
|
652 | Is the name of a python type from the types module. The name is | |
653 | given in lowercase without the ending type, ex. StringType is |
|
653 | given in lowercase without the ending type, ex. StringType is | |
654 | written string. By adding a type here only objects matching the |
|
654 | written string. By adding a type here only objects matching the | |
655 | given type are matched. Using all here makes the pattern match all |
|
655 | given type are matched. Using all here makes the pattern match all | |
656 | types (this is the default). |
|
656 | types (this is the default). | |
657 |
|
657 | |||
658 | Options: |
|
658 | Options: | |
659 |
|
659 | |||
660 | -a: makes the pattern match even objects whose names start with a |
|
660 | -a: makes the pattern match even objects whose names start with a | |
661 | single underscore. These names are normally ommitted from the |
|
661 | single underscore. These names are normally ommitted from the | |
662 | search. |
|
662 | search. | |
663 |
|
663 | |||
664 | -i/-c: make the pattern case insensitive/sensitive. If neither of |
|
664 | -i/-c: make the pattern case insensitive/sensitive. If neither of | |
665 | these options is given, the default is read from your ipythonrc |
|
665 | these options is given, the default is read from your ipythonrc | |
666 | file. The option name which sets this value is |
|
666 | file. The option name which sets this value is | |
667 | 'wildcards_case_sensitive'. If this option is not specified in your |
|
667 | 'wildcards_case_sensitive'. If this option is not specified in your | |
668 | ipythonrc file, IPython's internal default is to do a case sensitive |
|
668 | ipythonrc file, IPython's internal default is to do a case sensitive | |
669 | search. |
|
669 | search. | |
670 |
|
670 | |||
671 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you |
|
671 | -e/-s NAMESPACE: exclude/search a given namespace. The pattern you | |
672 | specifiy can be searched in any of the following namespaces: |
|
672 | specifiy can be searched in any of the following namespaces: | |
673 | 'builtin', 'user', 'user_global','internal', 'alias', where |
|
673 | 'builtin', 'user', 'user_global','internal', 'alias', where | |
674 | 'builtin' and 'user' are the search defaults. Note that you should |
|
674 | 'builtin' and 'user' are the search defaults. Note that you should | |
675 | not use quotes when specifying namespaces. |
|
675 | not use quotes when specifying namespaces. | |
676 |
|
676 | |||
677 | 'Builtin' contains the python module builtin, 'user' contains all |
|
677 | 'Builtin' contains the python module builtin, 'user' contains all | |
678 | user data, 'alias' only contain the shell aliases and no python |
|
678 | user data, 'alias' only contain the shell aliases and no python | |
679 | objects, 'internal' contains objects used by IPython. The |
|
679 | objects, 'internal' contains objects used by IPython. The | |
680 | 'user_global' namespace is only used by embedded IPython instances, |
|
680 | 'user_global' namespace is only used by embedded IPython instances, | |
681 | and it contains module-level globals. You can add namespaces to the |
|
681 | and it contains module-level globals. You can add namespaces to the | |
682 | search with -s or exclude them with -e (these options can be given |
|
682 | search with -s or exclude them with -e (these options can be given | |
683 | more than once). |
|
683 | more than once). | |
684 |
|
684 | |||
685 | Examples: |
|
685 | Examples: | |
686 |
|
686 | |||
687 | %psearch a* -> objects beginning with an a |
|
687 | %psearch a* -> objects beginning with an a | |
688 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a |
|
688 | %psearch -e builtin a* -> objects NOT in the builtin space starting in a | |
689 | %psearch a* function -> all functions beginning with an a |
|
689 | %psearch a* function -> all functions beginning with an a | |
690 | %psearch re.e* -> objects beginning with an e in module re |
|
690 | %psearch re.e* -> objects beginning with an e in module re | |
691 | %psearch r*.e* -> objects that start with e in modules starting in r |
|
691 | %psearch r*.e* -> objects that start with e in modules starting in r | |
692 | %psearch r*.* string -> all strings in modules beginning with r |
|
692 | %psearch r*.* string -> all strings in modules beginning with r | |
693 |
|
693 | |||
694 | Case sensitve search: |
|
694 | Case sensitve search: | |
695 |
|
695 | |||
696 | %psearch -c a* list all object beginning with lower case a |
|
696 | %psearch -c a* list all object beginning with lower case a | |
697 |
|
697 | |||
698 | Show objects beginning with a single _: |
|
698 | Show objects beginning with a single _: | |
699 |
|
699 | |||
700 | %psearch -a _* list objects beginning with a single underscore""" |
|
700 | %psearch -a _* list objects beginning with a single underscore""" | |
701 | try: |
|
701 | try: | |
702 | parameter_s = parameter_s.encode('ascii') |
|
702 | parameter_s = parameter_s.encode('ascii') | |
703 | except UnicodeEncodeError: |
|
703 | except UnicodeEncodeError: | |
704 | print 'Python identifiers can only contain ascii characters.' |
|
704 | print 'Python identifiers can only contain ascii characters.' | |
705 | return |
|
705 | return | |
706 |
|
706 | |||
707 | # default namespaces to be searched |
|
707 | # default namespaces to be searched | |
708 | def_search = ['user','builtin'] |
|
708 | def_search = ['user','builtin'] | |
709 |
|
709 | |||
710 | # Process options/args |
|
710 | # Process options/args | |
711 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) |
|
711 | opts,args = self.parse_options(parameter_s,'cias:e:',list_all=True) | |
712 | opt = opts.get |
|
712 | opt = opts.get | |
713 | shell = self.shell |
|
713 | shell = self.shell | |
714 | psearch = shell.inspector.psearch |
|
714 | psearch = shell.inspector.psearch | |
715 |
|
715 | |||
716 | # select case options |
|
716 | # select case options | |
717 | if opts.has_key('i'): |
|
717 | if opts.has_key('i'): | |
718 | ignore_case = True |
|
718 | ignore_case = True | |
719 | elif opts.has_key('c'): |
|
719 | elif opts.has_key('c'): | |
720 | ignore_case = False |
|
720 | ignore_case = False | |
721 | else: |
|
721 | else: | |
722 | ignore_case = not shell.wildcards_case_sensitive |
|
722 | ignore_case = not shell.wildcards_case_sensitive | |
723 |
|
723 | |||
724 | # Build list of namespaces to search from user options |
|
724 | # Build list of namespaces to search from user options | |
725 | def_search.extend(opt('s',[])) |
|
725 | def_search.extend(opt('s',[])) | |
726 | ns_exclude = ns_exclude=opt('e',[]) |
|
726 | ns_exclude = ns_exclude=opt('e',[]) | |
727 | ns_search = [nm for nm in def_search if nm not in ns_exclude] |
|
727 | ns_search = [nm for nm in def_search if nm not in ns_exclude] | |
728 |
|
728 | |||
729 | # Call the actual search |
|
729 | # Call the actual search | |
730 | try: |
|
730 | try: | |
731 | psearch(args,shell.ns_table,ns_search, |
|
731 | psearch(args,shell.ns_table,ns_search, | |
732 | show_all=opt('a'),ignore_case=ignore_case) |
|
732 | show_all=opt('a'),ignore_case=ignore_case) | |
733 | except: |
|
733 | except: | |
734 | shell.showtraceback() |
|
734 | shell.showtraceback() | |
735 |
|
735 | |||
736 | def magic_who_ls(self, parameter_s=''): |
|
736 | def magic_who_ls(self, parameter_s=''): | |
737 | """Return a sorted list of all interactive variables. |
|
737 | """Return a sorted list of all interactive variables. | |
738 |
|
738 | |||
739 | If arguments are given, only variables of types matching these |
|
739 | If arguments are given, only variables of types matching these | |
740 | arguments are returned.""" |
|
740 | arguments are returned.""" | |
741 |
|
741 | |||
742 | user_ns = self.shell.user_ns |
|
742 | user_ns = self.shell.user_ns | |
743 | internal_ns = self.shell.internal_ns |
|
743 | internal_ns = self.shell.internal_ns | |
744 | user_ns_hidden = self.shell.user_ns_hidden |
|
744 | user_ns_hidden = self.shell.user_ns_hidden | |
745 | out = [ i for i in user_ns |
|
745 | out = [ i for i in user_ns | |
746 | if not i.startswith('_') \ |
|
746 | if not i.startswith('_') \ | |
747 | and not (i in internal_ns or i in user_ns_hidden) ] |
|
747 | and not (i in internal_ns or i in user_ns_hidden) ] | |
748 |
|
748 | |||
749 | typelist = parameter_s.split() |
|
749 | typelist = parameter_s.split() | |
750 | if typelist: |
|
750 | if typelist: | |
751 | typeset = set(typelist) |
|
751 | typeset = set(typelist) | |
752 | out = [i for i in out if type(i).__name__ in typeset] |
|
752 | out = [i for i in out if type(i).__name__ in typeset] | |
753 |
|
753 | |||
754 | out.sort() |
|
754 | out.sort() | |
755 | return out |
|
755 | return out | |
756 |
|
756 | |||
757 | def magic_who(self, parameter_s=''): |
|
757 | def magic_who(self, parameter_s=''): | |
758 | """Print all interactive variables, with some minimal formatting. |
|
758 | """Print all interactive variables, with some minimal formatting. | |
759 |
|
759 | |||
760 | If any arguments are given, only variables whose type matches one of |
|
760 | If any arguments are given, only variables whose type matches one of | |
761 | these are printed. For example: |
|
761 | these are printed. For example: | |
762 |
|
762 | |||
763 | %who function str |
|
763 | %who function str | |
764 |
|
764 | |||
765 | will only list functions and strings, excluding all other types of |
|
765 | will only list functions and strings, excluding all other types of | |
766 | variables. To find the proper type names, simply use type(var) at a |
|
766 | variables. To find the proper type names, simply use type(var) at a | |
767 | command line to see how python prints type names. For example: |
|
767 | command line to see how python prints type names. For example: | |
768 |
|
768 | |||
769 | In [1]: type('hello')\\ |
|
769 | In [1]: type('hello')\\ | |
770 | Out[1]: <type 'str'> |
|
770 | Out[1]: <type 'str'> | |
771 |
|
771 | |||
772 | indicates that the type name for strings is 'str'. |
|
772 | indicates that the type name for strings is 'str'. | |
773 |
|
773 | |||
774 | %who always excludes executed names loaded through your configuration |
|
774 | %who always excludes executed names loaded through your configuration | |
775 | file and things which are internal to IPython. |
|
775 | file and things which are internal to IPython. | |
776 |
|
776 | |||
777 | This is deliberate, as typically you may load many modules and the |
|
777 | This is deliberate, as typically you may load many modules and the | |
778 | purpose of %who is to show you only what you've manually defined.""" |
|
778 | purpose of %who is to show you only what you've manually defined.""" | |
779 |
|
779 | |||
780 | varlist = self.magic_who_ls(parameter_s) |
|
780 | varlist = self.magic_who_ls(parameter_s) | |
781 | if not varlist: |
|
781 | if not varlist: | |
782 | if parameter_s: |
|
782 | if parameter_s: | |
783 | print 'No variables match your requested type.' |
|
783 | print 'No variables match your requested type.' | |
784 | else: |
|
784 | else: | |
785 | print 'Interactive namespace is empty.' |
|
785 | print 'Interactive namespace is empty.' | |
786 | return |
|
786 | return | |
787 |
|
787 | |||
788 | # if we have variables, move on... |
|
788 | # if we have variables, move on... | |
789 | count = 0 |
|
789 | count = 0 | |
790 | for i in varlist: |
|
790 | for i in varlist: | |
791 | print i+'\t', |
|
791 | print i+'\t', | |
792 | count += 1 |
|
792 | count += 1 | |
793 | if count > 8: |
|
793 | if count > 8: | |
794 | count = 0 |
|
794 | count = 0 | |
795 |
|
795 | |||
796 |
|
796 | |||
797 |
|
797 | |||
798 | def magic_whos(self, parameter_s=''): |
|
798 | def magic_whos(self, parameter_s=''): | |
799 | """Like %who, but gives some extra information about each variable. |
|
799 | """Like %who, but gives some extra information about each variable. | |
800 |
|
800 | |||
801 | The same type filtering of %who can be applied here. |
|
801 | The same type filtering of %who can be applied here. | |
802 |
|
802 | |||
803 | For all variables, the type is printed. Additionally it prints: |
|
803 | For all variables, the type is printed. Additionally it prints: | |
804 |
|
804 | |||
805 | - For {},[],(): their length. |
|
805 | - For {},[],(): their length. | |
806 |
|
806 | |||
807 | - For numpy and Numeric arrays, a summary with shape, number of |
|
807 | - For numpy and Numeric arrays, a summary with shape, number of | |
808 | elements, typecode and size in memory. |
|
808 | elements, typecode and size in memory. | |
809 |
|
809 | |||
810 | - Everything else: a string representation, snipping their middle if |
|
810 | - Everything else: a string representation, snipping their middle if | |
811 | too long.""" |
|
811 | too long.""" | |
812 |
|
812 | |||
813 | varnames = self.magic_who_ls(parameter_s) |
|
813 | varnames = self.magic_who_ls(parameter_s) | |
814 | if not varnames: |
|
814 | if not varnames: | |
815 | if parameter_s: |
|
815 | if parameter_s: | |
816 | print 'No variables match your requested type.' |
|
816 | print 'No variables match your requested type.' | |
817 | else: |
|
817 | else: | |
818 | print 'Interactive namespace is empty.' |
|
818 | print 'Interactive namespace is empty.' | |
819 | return |
|
819 | return | |
820 |
|
820 | |||
821 | # if we have variables, move on... |
|
821 | # if we have variables, move on... | |
822 |
|
822 | |||
823 | # for these types, show len() instead of data: |
|
823 | # for these types, show len() instead of data: | |
824 | seq_types = [types.DictType,types.ListType,types.TupleType] |
|
824 | seq_types = [types.DictType,types.ListType,types.TupleType] | |
825 |
|
825 | |||
826 | # for numpy/Numeric arrays, display summary info |
|
826 | # for numpy/Numeric arrays, display summary info | |
827 | try: |
|
827 | try: | |
828 | import numpy |
|
828 | import numpy | |
829 | except ImportError: |
|
829 | except ImportError: | |
830 | ndarray_type = None |
|
830 | ndarray_type = None | |
831 | else: |
|
831 | else: | |
832 | ndarray_type = numpy.ndarray.__name__ |
|
832 | ndarray_type = numpy.ndarray.__name__ | |
833 | try: |
|
833 | try: | |
834 | import Numeric |
|
834 | import Numeric | |
835 | except ImportError: |
|
835 | except ImportError: | |
836 | array_type = None |
|
836 | array_type = None | |
837 | else: |
|
837 | else: | |
838 | array_type = Numeric.ArrayType.__name__ |
|
838 | array_type = Numeric.ArrayType.__name__ | |
839 |
|
839 | |||
840 | # Find all variable names and types so we can figure out column sizes |
|
840 | # Find all variable names and types so we can figure out column sizes | |
841 | def get_vars(i): |
|
841 | def get_vars(i): | |
842 | return self.shell.user_ns[i] |
|
842 | return self.shell.user_ns[i] | |
843 |
|
843 | |||
844 | # some types are well known and can be shorter |
|
844 | # some types are well known and can be shorter | |
845 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} |
|
845 | abbrevs = {'IPython.core.macro.Macro' : 'Macro'} | |
846 | def type_name(v): |
|
846 | def type_name(v): | |
847 | tn = type(v).__name__ |
|
847 | tn = type(v).__name__ | |
848 | return abbrevs.get(tn,tn) |
|
848 | return abbrevs.get(tn,tn) | |
849 |
|
849 | |||
850 | varlist = map(get_vars,varnames) |
|
850 | varlist = map(get_vars,varnames) | |
851 |
|
851 | |||
852 | typelist = [] |
|
852 | typelist = [] | |
853 | for vv in varlist: |
|
853 | for vv in varlist: | |
854 | tt = type_name(vv) |
|
854 | tt = type_name(vv) | |
855 |
|
855 | |||
856 | if tt=='instance': |
|
856 | if tt=='instance': | |
857 | typelist.append( abbrevs.get(str(vv.__class__), |
|
857 | typelist.append( abbrevs.get(str(vv.__class__), | |
858 | str(vv.__class__))) |
|
858 | str(vv.__class__))) | |
859 | else: |
|
859 | else: | |
860 | typelist.append(tt) |
|
860 | typelist.append(tt) | |
861 |
|
861 | |||
862 | # column labels and # of spaces as separator |
|
862 | # column labels and # of spaces as separator | |
863 | varlabel = 'Variable' |
|
863 | varlabel = 'Variable' | |
864 | typelabel = 'Type' |
|
864 | typelabel = 'Type' | |
865 | datalabel = 'Data/Info' |
|
865 | datalabel = 'Data/Info' | |
866 | colsep = 3 |
|
866 | colsep = 3 | |
867 | # variable format strings |
|
867 | # variable format strings | |
868 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" |
|
868 | vformat = "$vname.ljust(varwidth)$vtype.ljust(typewidth)" | |
869 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' |
|
869 | vfmt_short = '$vstr[:25]<...>$vstr[-25:]' | |
870 | aformat = "%s: %s elems, type `%s`, %s bytes" |
|
870 | aformat = "%s: %s elems, type `%s`, %s bytes" | |
871 | # find the size of the columns to format the output nicely |
|
871 | # find the size of the columns to format the output nicely | |
872 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep |
|
872 | varwidth = max(max(map(len,varnames)), len(varlabel)) + colsep | |
873 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep |
|
873 | typewidth = max(max(map(len,typelist)), len(typelabel)) + colsep | |
874 | # table header |
|
874 | # table header | |
875 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ |
|
875 | print varlabel.ljust(varwidth) + typelabel.ljust(typewidth) + \ | |
876 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) |
|
876 | ' '+datalabel+'\n' + '-'*(varwidth+typewidth+len(datalabel)+1) | |
877 | # and the table itself |
|
877 | # and the table itself | |
878 | kb = 1024 |
|
878 | kb = 1024 | |
879 | Mb = 1048576 # kb**2 |
|
879 | Mb = 1048576 # kb**2 | |
880 | for vname,var,vtype in zip(varnames,varlist,typelist): |
|
880 | for vname,var,vtype in zip(varnames,varlist,typelist): | |
881 | print itpl(vformat), |
|
881 | print itpl(vformat), | |
882 | if vtype in seq_types: |
|
882 | if vtype in seq_types: | |
883 | print len(var) |
|
883 | print len(var) | |
884 | elif vtype in [array_type,ndarray_type]: |
|
884 | elif vtype in [array_type,ndarray_type]: | |
885 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] |
|
885 | vshape = str(var.shape).replace(',','').replace(' ','x')[1:-1] | |
886 | if vtype==ndarray_type: |
|
886 | if vtype==ndarray_type: | |
887 | # numpy |
|
887 | # numpy | |
888 | vsize = var.size |
|
888 | vsize = var.size | |
889 | vbytes = vsize*var.itemsize |
|
889 | vbytes = vsize*var.itemsize | |
890 | vdtype = var.dtype |
|
890 | vdtype = var.dtype | |
891 | else: |
|
891 | else: | |
892 | # Numeric |
|
892 | # Numeric | |
893 | vsize = Numeric.size(var) |
|
893 | vsize = Numeric.size(var) | |
894 | vbytes = vsize*var.itemsize() |
|
894 | vbytes = vsize*var.itemsize() | |
895 | vdtype = var.typecode() |
|
895 | vdtype = var.typecode() | |
896 |
|
896 | |||
897 | if vbytes < 100000: |
|
897 | if vbytes < 100000: | |
898 | print aformat % (vshape,vsize,vdtype,vbytes) |
|
898 | print aformat % (vshape,vsize,vdtype,vbytes) | |
899 | else: |
|
899 | else: | |
900 | print aformat % (vshape,vsize,vdtype,vbytes), |
|
900 | print aformat % (vshape,vsize,vdtype,vbytes), | |
901 | if vbytes < Mb: |
|
901 | if vbytes < Mb: | |
902 | print '(%s kb)' % (vbytes/kb,) |
|
902 | print '(%s kb)' % (vbytes/kb,) | |
903 | else: |
|
903 | else: | |
904 | print '(%s Mb)' % (vbytes/Mb,) |
|
904 | print '(%s Mb)' % (vbytes/Mb,) | |
905 | else: |
|
905 | else: | |
906 | try: |
|
906 | try: | |
907 | vstr = str(var) |
|
907 | vstr = str(var) | |
908 | except UnicodeEncodeError: |
|
908 | except UnicodeEncodeError: | |
909 | vstr = unicode(var).encode(sys.getdefaultencoding(), |
|
909 | vstr = unicode(var).encode(sys.getdefaultencoding(), | |
910 | 'backslashreplace') |
|
910 | 'backslashreplace') | |
911 | vstr = vstr.replace('\n','\\n') |
|
911 | vstr = vstr.replace('\n','\\n') | |
912 | if len(vstr) < 50: |
|
912 | if len(vstr) < 50: | |
913 | print vstr |
|
913 | print vstr | |
914 | else: |
|
914 | else: | |
915 | printpl(vfmt_short) |
|
915 | printpl(vfmt_short) | |
916 |
|
916 | |||
917 | def magic_reset(self, parameter_s=''): |
|
917 | def magic_reset(self, parameter_s=''): | |
918 | """Resets the namespace by removing all names defined by the user. |
|
918 | """Resets the namespace by removing all names defined by the user. | |
919 |
|
919 | |||
920 | Input/Output history are left around in case you need them. |
|
920 | Input/Output history are left around in case you need them. | |
921 |
|
921 | |||
922 | Parameters |
|
922 | Parameters | |
923 | ---------- |
|
923 | ---------- | |
924 | -y : force reset without asking for confirmation. |
|
924 | -y : force reset without asking for confirmation. | |
925 |
|
925 | |||
926 | Examples |
|
926 | Examples | |
927 | -------- |
|
927 | -------- | |
928 | In [6]: a = 1 |
|
928 | In [6]: a = 1 | |
929 |
|
929 | |||
930 | In [7]: a |
|
930 | In [7]: a | |
931 | Out[7]: 1 |
|
931 | Out[7]: 1 | |
932 |
|
932 | |||
933 | In [8]: 'a' in _ip.user_ns |
|
933 | In [8]: 'a' in _ip.user_ns | |
934 | Out[8]: True |
|
934 | Out[8]: True | |
935 |
|
935 | |||
936 | In [9]: %reset -f |
|
936 | In [9]: %reset -f | |
937 |
|
937 | |||
938 | In [10]: 'a' in _ip.user_ns |
|
938 | In [10]: 'a' in _ip.user_ns | |
939 | Out[10]: False |
|
939 | Out[10]: False | |
940 | """ |
|
940 | """ | |
941 |
|
941 | |||
942 | if parameter_s == '-f': |
|
942 | if parameter_s == '-f': | |
943 | ans = True |
|
943 | ans = True | |
944 | else: |
|
944 | else: | |
945 | ans = self.shell.ask_yes_no( |
|
945 | ans = self.shell.ask_yes_no( | |
946 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
946 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
947 | if not ans: |
|
947 | if not ans: | |
948 | print 'Nothing done.' |
|
948 | print 'Nothing done.' | |
949 | return |
|
949 | return | |
950 | user_ns = self.shell.user_ns |
|
950 | user_ns = self.shell.user_ns | |
951 | for i in self.magic_who_ls(): |
|
951 | for i in self.magic_who_ls(): | |
952 | del(user_ns[i]) |
|
952 | del(user_ns[i]) | |
953 |
|
953 | |||
954 | # Also flush the private list of module references kept for script |
|
954 | # Also flush the private list of module references kept for script | |
955 | # execution protection |
|
955 | # execution protection | |
956 | self.shell.clear_main_mod_cache() |
|
956 | self.shell.clear_main_mod_cache() | |
957 |
|
957 | |||
958 | def magic_reset_selective(self, parameter_s=''): |
|
958 | def magic_reset_selective(self, parameter_s=''): | |
959 | """Resets the namespace by removing names defined by the user. |
|
959 | """Resets the namespace by removing names defined by the user. | |
960 |
|
960 | |||
961 | Input/Output history are left around in case you need them. |
|
961 | Input/Output history are left around in case you need them. | |
962 |
|
962 | |||
963 | %reset_selective [-f] regex |
|
963 | %reset_selective [-f] regex | |
964 |
|
964 | |||
965 | No action is taken if regex is not included |
|
965 | No action is taken if regex is not included | |
966 |
|
966 | |||
967 | Options |
|
967 | Options | |
968 | -f : force reset without asking for confirmation. |
|
968 | -f : force reset without asking for confirmation. | |
969 |
|
969 | |||
970 | Examples |
|
970 | Examples | |
971 | -------- |
|
971 | -------- | |
972 |
|
972 | |||
973 | We first fully reset the namespace so your output looks identical to |
|
973 | We first fully reset the namespace so your output looks identical to | |
974 | this example for pedagogical reasons; in practice you do not need a |
|
974 | this example for pedagogical reasons; in practice you do not need a | |
975 | full reset. |
|
975 | full reset. | |
976 |
|
976 | |||
977 | In [1]: %reset -f |
|
977 | In [1]: %reset -f | |
978 |
|
978 | |||
979 | Now, with a clean namespace we can make a few variables and use |
|
979 | Now, with a clean namespace we can make a few variables and use | |
980 | %reset_selective to only delete names that match our regexp: |
|
980 | %reset_selective to only delete names that match our regexp: | |
981 |
|
981 | |||
982 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 |
|
982 | In [2]: a=1; b=2; c=3; b1m=4; b2m=5; b3m=6; b4m=7; b2s=8 | |
983 |
|
983 | |||
984 | In [3]: who_ls |
|
984 | In [3]: who_ls | |
985 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] |
|
985 | Out[3]: ['a', 'b', 'b1m', 'b2m', 'b2s', 'b3m', 'b4m', 'c'] | |
986 |
|
986 | |||
987 | In [4]: %reset_selective -f b[2-3]m |
|
987 | In [4]: %reset_selective -f b[2-3]m | |
988 |
|
988 | |||
989 | In [5]: who_ls |
|
989 | In [5]: who_ls | |
990 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
990 | Out[5]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
991 |
|
991 | |||
992 | In [6]: %reset_selective -f d |
|
992 | In [6]: %reset_selective -f d | |
993 |
|
993 | |||
994 | In [7]: who_ls |
|
994 | In [7]: who_ls | |
995 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] |
|
995 | Out[7]: ['a', 'b', 'b1m', 'b2s', 'b4m', 'c'] | |
996 |
|
996 | |||
997 | In [8]: %reset_selective -f c |
|
997 | In [8]: %reset_selective -f c | |
998 |
|
998 | |||
999 | In [9]: who_ls |
|
999 | In [9]: who_ls | |
1000 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] |
|
1000 | Out[9]: ['a', 'b', 'b1m', 'b2s', 'b4m'] | |
1001 |
|
1001 | |||
1002 | In [10]: %reset_selective -f b |
|
1002 | In [10]: %reset_selective -f b | |
1003 |
|
1003 | |||
1004 | In [11]: who_ls |
|
1004 | In [11]: who_ls | |
1005 | Out[11]: ['a'] |
|
1005 | Out[11]: ['a'] | |
1006 | """ |
|
1006 | """ | |
1007 |
|
1007 | |||
1008 | opts, regex = self.parse_options(parameter_s,'f') |
|
1008 | opts, regex = self.parse_options(parameter_s,'f') | |
1009 |
|
1009 | |||
1010 | if opts.has_key('f'): |
|
1010 | if opts.has_key('f'): | |
1011 | ans = True |
|
1011 | ans = True | |
1012 | else: |
|
1012 | else: | |
1013 | ans = self.shell.ask_yes_no( |
|
1013 | ans = self.shell.ask_yes_no( | |
1014 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") |
|
1014 | "Once deleted, variables cannot be recovered. Proceed (y/[n])? ") | |
1015 | if not ans: |
|
1015 | if not ans: | |
1016 | print 'Nothing done.' |
|
1016 | print 'Nothing done.' | |
1017 | return |
|
1017 | return | |
1018 | user_ns = self.shell.user_ns |
|
1018 | user_ns = self.shell.user_ns | |
1019 | if not regex: |
|
1019 | if not regex: | |
1020 | print 'No regex pattern specified. Nothing done.' |
|
1020 | print 'No regex pattern specified. Nothing done.' | |
1021 | return |
|
1021 | return | |
1022 | else: |
|
1022 | else: | |
1023 | try: |
|
1023 | try: | |
1024 | m = re.compile(regex) |
|
1024 | m = re.compile(regex) | |
1025 | except TypeError: |
|
1025 | except TypeError: | |
1026 | raise TypeError('regex must be a string or compiled pattern') |
|
1026 | raise TypeError('regex must be a string or compiled pattern') | |
1027 | for i in self.magic_who_ls(): |
|
1027 | for i in self.magic_who_ls(): | |
1028 | if m.search(i): |
|
1028 | if m.search(i): | |
1029 | del(user_ns[i]) |
|
1029 | del(user_ns[i]) | |
1030 |
|
1030 | |||
1031 | def magic_logstart(self,parameter_s=''): |
|
1031 | def magic_logstart(self,parameter_s=''): | |
1032 | """Start logging anywhere in a session. |
|
1032 | """Start logging anywhere in a session. | |
1033 |
|
1033 | |||
1034 | %logstart [-o|-r|-t] [log_name [log_mode]] |
|
1034 | %logstart [-o|-r|-t] [log_name [log_mode]] | |
1035 |
|
1035 | |||
1036 | If no name is given, it defaults to a file named 'ipython_log.py' in your |
|
1036 | If no name is given, it defaults to a file named 'ipython_log.py' in your | |
1037 | current directory, in 'rotate' mode (see below). |
|
1037 | current directory, in 'rotate' mode (see below). | |
1038 |
|
1038 | |||
1039 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your |
|
1039 | '%logstart name' saves to file 'name' in 'backup' mode. It saves your | |
1040 | history up to that point and then continues logging. |
|
1040 | history up to that point and then continues logging. | |
1041 |
|
1041 | |||
1042 | %logstart takes a second optional parameter: logging mode. This can be one |
|
1042 | %logstart takes a second optional parameter: logging mode. This can be one | |
1043 | of (note that the modes are given unquoted):\\ |
|
1043 | of (note that the modes are given unquoted):\\ | |
1044 | append: well, that says it.\\ |
|
1044 | append: well, that says it.\\ | |
1045 | backup: rename (if exists) to name~ and start name.\\ |
|
1045 | backup: rename (if exists) to name~ and start name.\\ | |
1046 | global: single logfile in your home dir, appended to.\\ |
|
1046 | global: single logfile in your home dir, appended to.\\ | |
1047 | over : overwrite existing log.\\ |
|
1047 | over : overwrite existing log.\\ | |
1048 | rotate: create rotating logs name.1~, name.2~, etc. |
|
1048 | rotate: create rotating logs name.1~, name.2~, etc. | |
1049 |
|
1049 | |||
1050 | Options: |
|
1050 | Options: | |
1051 |
|
1051 | |||
1052 | -o: log also IPython's output. In this mode, all commands which |
|
1052 | -o: log also IPython's output. In this mode, all commands which | |
1053 | generate an Out[NN] prompt are recorded to the logfile, right after |
|
1053 | generate an Out[NN] prompt are recorded to the logfile, right after | |
1054 | their corresponding input line. The output lines are always |
|
1054 | their corresponding input line. The output lines are always | |
1055 | prepended with a '#[Out]# ' marker, so that the log remains valid |
|
1055 | prepended with a '#[Out]# ' marker, so that the log remains valid | |
1056 | Python code. |
|
1056 | Python code. | |
1057 |
|
1057 | |||
1058 | Since this marker is always the same, filtering only the output from |
|
1058 | Since this marker is always the same, filtering only the output from | |
1059 | a log is very easy, using for example a simple awk call: |
|
1059 | a log is very easy, using for example a simple awk call: | |
1060 |
|
1060 | |||
1061 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py |
|
1061 | awk -F'#\\[Out\\]# ' '{if($2) {print $2}}' ipython_log.py | |
1062 |
|
1062 | |||
1063 | -r: log 'raw' input. Normally, IPython's logs contain the processed |
|
1063 | -r: log 'raw' input. Normally, IPython's logs contain the processed | |
1064 | input, so that user lines are logged in their final form, converted |
|
1064 | input, so that user lines are logged in their final form, converted | |
1065 | into valid Python. For example, %Exit is logged as |
|
1065 | into valid Python. For example, %Exit is logged as | |
1066 | '_ip.magic("Exit"). If the -r flag is given, all input is logged |
|
1066 | '_ip.magic("Exit"). If the -r flag is given, all input is logged | |
1067 | exactly as typed, with no transformations applied. |
|
1067 | exactly as typed, with no transformations applied. | |
1068 |
|
1068 | |||
1069 | -t: put timestamps before each input line logged (these are put in |
|
1069 | -t: put timestamps before each input line logged (these are put in | |
1070 | comments).""" |
|
1070 | comments).""" | |
1071 |
|
1071 | |||
1072 | opts,par = self.parse_options(parameter_s,'ort') |
|
1072 | opts,par = self.parse_options(parameter_s,'ort') | |
1073 | log_output = 'o' in opts |
|
1073 | log_output = 'o' in opts | |
1074 | log_raw_input = 'r' in opts |
|
1074 | log_raw_input = 'r' in opts | |
1075 | timestamp = 't' in opts |
|
1075 | timestamp = 't' in opts | |
1076 |
|
1076 | |||
1077 | logger = self.shell.logger |
|
1077 | logger = self.shell.logger | |
1078 |
|
1078 | |||
1079 | # if no args are given, the defaults set in the logger constructor by |
|
1079 | # if no args are given, the defaults set in the logger constructor by | |
1080 | # ipytohn remain valid |
|
1080 | # ipytohn remain valid | |
1081 | if par: |
|
1081 | if par: | |
1082 | try: |
|
1082 | try: | |
1083 | logfname,logmode = par.split() |
|
1083 | logfname,logmode = par.split() | |
1084 | except: |
|
1084 | except: | |
1085 | logfname = par |
|
1085 | logfname = par | |
1086 | logmode = 'backup' |
|
1086 | logmode = 'backup' | |
1087 | else: |
|
1087 | else: | |
1088 | logfname = logger.logfname |
|
1088 | logfname = logger.logfname | |
1089 | logmode = logger.logmode |
|
1089 | logmode = logger.logmode | |
1090 | # put logfname into rc struct as if it had been called on the command |
|
1090 | # put logfname into rc struct as if it had been called on the command | |
1091 | # line, so it ends up saved in the log header Save it in case we need |
|
1091 | # line, so it ends up saved in the log header Save it in case we need | |
1092 | # to restore it... |
|
1092 | # to restore it... | |
1093 | old_logfile = self.shell.logfile |
|
1093 | old_logfile = self.shell.logfile | |
1094 | if logfname: |
|
1094 | if logfname: | |
1095 | logfname = os.path.expanduser(logfname) |
|
1095 | logfname = os.path.expanduser(logfname) | |
1096 | self.shell.logfile = logfname |
|
1096 | self.shell.logfile = logfname | |
1097 |
|
1097 | |||
1098 | loghead = '# IPython log file\n\n' |
|
1098 | loghead = '# IPython log file\n\n' | |
1099 | try: |
|
1099 | try: | |
1100 | started = logger.logstart(logfname,loghead,logmode, |
|
1100 | started = logger.logstart(logfname,loghead,logmode, | |
1101 | log_output,timestamp,log_raw_input) |
|
1101 | log_output,timestamp,log_raw_input) | |
1102 | except: |
|
1102 | except: | |
1103 | self.shell.logfile = old_logfile |
|
1103 | self.shell.logfile = old_logfile | |
1104 | warn("Couldn't start log: %s" % sys.exc_info()[1]) |
|
1104 | warn("Couldn't start log: %s" % sys.exc_info()[1]) | |
1105 | else: |
|
1105 | else: | |
1106 | # log input history up to this point, optionally interleaving |
|
1106 | # log input history up to this point, optionally interleaving | |
1107 | # output if requested |
|
1107 | # output if requested | |
1108 |
|
1108 | |||
1109 | if timestamp: |
|
1109 | if timestamp: | |
1110 | # disable timestamping for the previous history, since we've |
|
1110 | # disable timestamping for the previous history, since we've | |
1111 | # lost those already (no time machine here). |
|
1111 | # lost those already (no time machine here). | |
1112 | logger.timestamp = False |
|
1112 | logger.timestamp = False | |
1113 |
|
1113 | |||
1114 | if log_raw_input: |
|
1114 | if log_raw_input: | |
1115 | input_hist = self.shell.input_hist_raw |
|
1115 | input_hist = self.shell.input_hist_raw | |
1116 | else: |
|
1116 | else: | |
1117 | input_hist = self.shell.input_hist |
|
1117 | input_hist = self.shell.input_hist | |
1118 |
|
1118 | |||
1119 | if log_output: |
|
1119 | if log_output: | |
1120 | log_write = logger.log_write |
|
1120 | log_write = logger.log_write | |
1121 | output_hist = self.shell.output_hist |
|
1121 | output_hist = self.shell.output_hist | |
1122 | for n in range(1,len(input_hist)-1): |
|
1122 | for n in range(1,len(input_hist)-1): | |
1123 | log_write(input_hist[n].rstrip()) |
|
1123 | log_write(input_hist[n].rstrip()) | |
1124 | if n in output_hist: |
|
1124 | if n in output_hist: | |
1125 | log_write(repr(output_hist[n]),'output') |
|
1125 | log_write(repr(output_hist[n]),'output') | |
1126 | else: |
|
1126 | else: | |
1127 | logger.log_write(input_hist[1:]) |
|
1127 | logger.log_write(input_hist[1:]) | |
1128 | if timestamp: |
|
1128 | if timestamp: | |
1129 | # re-enable timestamping |
|
1129 | # re-enable timestamping | |
1130 | logger.timestamp = True |
|
1130 | logger.timestamp = True | |
1131 |
|
1131 | |||
1132 | print ('Activating auto-logging. ' |
|
1132 | print ('Activating auto-logging. ' | |
1133 | 'Current session state plus future input saved.') |
|
1133 | 'Current session state plus future input saved.') | |
1134 | logger.logstate() |
|
1134 | logger.logstate() | |
1135 |
|
1135 | |||
1136 | def magic_logstop(self,parameter_s=''): |
|
1136 | def magic_logstop(self,parameter_s=''): | |
1137 | """Fully stop logging and close log file. |
|
1137 | """Fully stop logging and close log file. | |
1138 |
|
1138 | |||
1139 | In order to start logging again, a new %logstart call needs to be made, |
|
1139 | In order to start logging again, a new %logstart call needs to be made, | |
1140 | possibly (though not necessarily) with a new filename, mode and other |
|
1140 | possibly (though not necessarily) with a new filename, mode and other | |
1141 | options.""" |
|
1141 | options.""" | |
1142 | self.logger.logstop() |
|
1142 | self.logger.logstop() | |
1143 |
|
1143 | |||
1144 | def magic_logoff(self,parameter_s=''): |
|
1144 | def magic_logoff(self,parameter_s=''): | |
1145 | """Temporarily stop logging. |
|
1145 | """Temporarily stop logging. | |
1146 |
|
1146 | |||
1147 | You must have previously started logging.""" |
|
1147 | You must have previously started logging.""" | |
1148 | self.shell.logger.switch_log(0) |
|
1148 | self.shell.logger.switch_log(0) | |
1149 |
|
1149 | |||
1150 | def magic_logon(self,parameter_s=''): |
|
1150 | def magic_logon(self,parameter_s=''): | |
1151 | """Restart logging. |
|
1151 | """Restart logging. | |
1152 |
|
1152 | |||
1153 | This function is for restarting logging which you've temporarily |
|
1153 | This function is for restarting logging which you've temporarily | |
1154 | stopped with %logoff. For starting logging for the first time, you |
|
1154 | stopped with %logoff. For starting logging for the first time, you | |
1155 | must use the %logstart function, which allows you to specify an |
|
1155 | must use the %logstart function, which allows you to specify an | |
1156 | optional log filename.""" |
|
1156 | optional log filename.""" | |
1157 |
|
1157 | |||
1158 | self.shell.logger.switch_log(1) |
|
1158 | self.shell.logger.switch_log(1) | |
1159 |
|
1159 | |||
1160 | def magic_logstate(self,parameter_s=''): |
|
1160 | def magic_logstate(self,parameter_s=''): | |
1161 | """Print the status of the logging system.""" |
|
1161 | """Print the status of the logging system.""" | |
1162 |
|
1162 | |||
1163 | self.shell.logger.logstate() |
|
1163 | self.shell.logger.logstate() | |
1164 |
|
1164 | |||
1165 | def magic_pdb(self, parameter_s=''): |
|
1165 | def magic_pdb(self, parameter_s=''): | |
1166 | """Control the automatic calling of the pdb interactive debugger. |
|
1166 | """Control the automatic calling of the pdb interactive debugger. | |
1167 |
|
1167 | |||
1168 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without |
|
1168 | Call as '%pdb on', '%pdb 1', '%pdb off' or '%pdb 0'. If called without | |
1169 | argument it works as a toggle. |
|
1169 | argument it works as a toggle. | |
1170 |
|
1170 | |||
1171 | When an exception is triggered, IPython can optionally call the |
|
1171 | When an exception is triggered, IPython can optionally call the | |
1172 | interactive pdb debugger after the traceback printout. %pdb toggles |
|
1172 | interactive pdb debugger after the traceback printout. %pdb toggles | |
1173 | this feature on and off. |
|
1173 | this feature on and off. | |
1174 |
|
1174 | |||
1175 | The initial state of this feature is set in your ipythonrc |
|
1175 | The initial state of this feature is set in your ipythonrc | |
1176 | configuration file (the variable is called 'pdb'). |
|
1176 | configuration file (the variable is called 'pdb'). | |
1177 |
|
1177 | |||
1178 | If you want to just activate the debugger AFTER an exception has fired, |
|
1178 | If you want to just activate the debugger AFTER an exception has fired, | |
1179 | without having to type '%pdb on' and rerunning your code, you can use |
|
1179 | without having to type '%pdb on' and rerunning your code, you can use | |
1180 | the %debug magic.""" |
|
1180 | the %debug magic.""" | |
1181 |
|
1181 | |||
1182 | par = parameter_s.strip().lower() |
|
1182 | par = parameter_s.strip().lower() | |
1183 |
|
1183 | |||
1184 | if par: |
|
1184 | if par: | |
1185 | try: |
|
1185 | try: | |
1186 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] |
|
1186 | new_pdb = {'off':0,'0':0,'on':1,'1':1}[par] | |
1187 | except KeyError: |
|
1187 | except KeyError: | |
1188 | print ('Incorrect argument. Use on/1, off/0, ' |
|
1188 | print ('Incorrect argument. Use on/1, off/0, ' | |
1189 | 'or nothing for a toggle.') |
|
1189 | 'or nothing for a toggle.') | |
1190 | return |
|
1190 | return | |
1191 | else: |
|
1191 | else: | |
1192 | # toggle |
|
1192 | # toggle | |
1193 | new_pdb = not self.shell.call_pdb |
|
1193 | new_pdb = not self.shell.call_pdb | |
1194 |
|
1194 | |||
1195 | # set on the shell |
|
1195 | # set on the shell | |
1196 | self.shell.call_pdb = new_pdb |
|
1196 | self.shell.call_pdb = new_pdb | |
1197 | print 'Automatic pdb calling has been turned',on_off(new_pdb) |
|
1197 | print 'Automatic pdb calling has been turned',on_off(new_pdb) | |
1198 |
|
1198 | |||
1199 | def magic_debug(self, parameter_s=''): |
|
1199 | def magic_debug(self, parameter_s=''): | |
1200 | """Activate the interactive debugger in post-mortem mode. |
|
1200 | """Activate the interactive debugger in post-mortem mode. | |
1201 |
|
1201 | |||
1202 | If an exception has just occurred, this lets you inspect its stack |
|
1202 | If an exception has just occurred, this lets you inspect its stack | |
1203 | frames interactively. Note that this will always work only on the last |
|
1203 | frames interactively. Note that this will always work only on the last | |
1204 | traceback that occurred, so you must call this quickly after an |
|
1204 | traceback that occurred, so you must call this quickly after an | |
1205 | exception that you wish to inspect has fired, because if another one |
|
1205 | exception that you wish to inspect has fired, because if another one | |
1206 | occurs, it clobbers the previous one. |
|
1206 | occurs, it clobbers the previous one. | |
1207 |
|
1207 | |||
1208 | If you want IPython to automatically do this on every exception, see |
|
1208 | If you want IPython to automatically do this on every exception, see | |
1209 | the %pdb magic for more details. |
|
1209 | the %pdb magic for more details. | |
1210 | """ |
|
1210 | """ | |
1211 | self.shell.debugger(force=True) |
|
1211 | self.shell.debugger(force=True) | |
1212 |
|
1212 | |||
1213 | @testdec.skip_doctest |
|
1213 | @testdec.skip_doctest | |
1214 | def magic_prun(self, parameter_s ='',user_mode=1, |
|
1214 | def magic_prun(self, parameter_s ='',user_mode=1, | |
1215 | opts=None,arg_lst=None,prog_ns=None): |
|
1215 | opts=None,arg_lst=None,prog_ns=None): | |
1216 |
|
1216 | |||
1217 | """Run a statement through the python code profiler. |
|
1217 | """Run a statement through the python code profiler. | |
1218 |
|
1218 | |||
1219 | Usage: |
|
1219 | Usage: | |
1220 | %prun [options] statement |
|
1220 | %prun [options] statement | |
1221 |
|
1221 | |||
1222 | The given statement (which doesn't require quote marks) is run via the |
|
1222 | The given statement (which doesn't require quote marks) is run via the | |
1223 | python profiler in a manner similar to the profile.run() function. |
|
1223 | python profiler in a manner similar to the profile.run() function. | |
1224 | Namespaces are internally managed to work correctly; profile.run |
|
1224 | Namespaces are internally managed to work correctly; profile.run | |
1225 | cannot be used in IPython because it makes certain assumptions about |
|
1225 | cannot be used in IPython because it makes certain assumptions about | |
1226 | namespaces which do not hold under IPython. |
|
1226 | namespaces which do not hold under IPython. | |
1227 |
|
1227 | |||
1228 | Options: |
|
1228 | Options: | |
1229 |
|
1229 | |||
1230 | -l <limit>: you can place restrictions on what or how much of the |
|
1230 | -l <limit>: you can place restrictions on what or how much of the | |
1231 | profile gets printed. The limit value can be: |
|
1231 | profile gets printed. The limit value can be: | |
1232 |
|
1232 | |||
1233 | * A string: only information for function names containing this string |
|
1233 | * A string: only information for function names containing this string | |
1234 | is printed. |
|
1234 | is printed. | |
1235 |
|
1235 | |||
1236 | * An integer: only these many lines are printed. |
|
1236 | * An integer: only these many lines are printed. | |
1237 |
|
1237 | |||
1238 | * A float (between 0 and 1): this fraction of the report is printed |
|
1238 | * A float (between 0 and 1): this fraction of the report is printed | |
1239 | (for example, use a limit of 0.4 to see the topmost 40% only). |
|
1239 | (for example, use a limit of 0.4 to see the topmost 40% only). | |
1240 |
|
1240 | |||
1241 | You can combine several limits with repeated use of the option. For |
|
1241 | You can combine several limits with repeated use of the option. For | |
1242 | example, '-l __init__ -l 5' will print only the topmost 5 lines of |
|
1242 | example, '-l __init__ -l 5' will print only the topmost 5 lines of | |
1243 | information about class constructors. |
|
1243 | information about class constructors. | |
1244 |
|
1244 | |||
1245 | -r: return the pstats.Stats object generated by the profiling. This |
|
1245 | -r: return the pstats.Stats object generated by the profiling. This | |
1246 | object has all the information about the profile in it, and you can |
|
1246 | object has all the information about the profile in it, and you can | |
1247 | later use it for further analysis or in other functions. |
|
1247 | later use it for further analysis or in other functions. | |
1248 |
|
1248 | |||
1249 | -s <key>: sort profile by given key. You can provide more than one key |
|
1249 | -s <key>: sort profile by given key. You can provide more than one key | |
1250 | by using the option several times: '-s key1 -s key2 -s key3...'. The |
|
1250 | by using the option several times: '-s key1 -s key2 -s key3...'. The | |
1251 | default sorting key is 'time'. |
|
1251 | default sorting key is 'time'. | |
1252 |
|
1252 | |||
1253 | The following is copied verbatim from the profile documentation |
|
1253 | The following is copied verbatim from the profile documentation | |
1254 | referenced below: |
|
1254 | referenced below: | |
1255 |
|
1255 | |||
1256 | When more than one key is provided, additional keys are used as |
|
1256 | When more than one key is provided, additional keys are used as | |
1257 | secondary criteria when the there is equality in all keys selected |
|
1257 | secondary criteria when the there is equality in all keys selected | |
1258 | before them. |
|
1258 | before them. | |
1259 |
|
1259 | |||
1260 | Abbreviations can be used for any key names, as long as the |
|
1260 | Abbreviations can be used for any key names, as long as the | |
1261 | abbreviation is unambiguous. The following are the keys currently |
|
1261 | abbreviation is unambiguous. The following are the keys currently | |
1262 | defined: |
|
1262 | defined: | |
1263 |
|
1263 | |||
1264 | Valid Arg Meaning |
|
1264 | Valid Arg Meaning | |
1265 | "calls" call count |
|
1265 | "calls" call count | |
1266 | "cumulative" cumulative time |
|
1266 | "cumulative" cumulative time | |
1267 | "file" file name |
|
1267 | "file" file name | |
1268 | "module" file name |
|
1268 | "module" file name | |
1269 | "pcalls" primitive call count |
|
1269 | "pcalls" primitive call count | |
1270 | "line" line number |
|
1270 | "line" line number | |
1271 | "name" function name |
|
1271 | "name" function name | |
1272 | "nfl" name/file/line |
|
1272 | "nfl" name/file/line | |
1273 | "stdname" standard name |
|
1273 | "stdname" standard name | |
1274 | "time" internal time |
|
1274 | "time" internal time | |
1275 |
|
1275 | |||
1276 | Note that all sorts on statistics are in descending order (placing |
|
1276 | Note that all sorts on statistics are in descending order (placing | |
1277 | most time consuming items first), where as name, file, and line number |
|
1277 | most time consuming items first), where as name, file, and line number | |
1278 | searches are in ascending order (i.e., alphabetical). The subtle |
|
1278 | searches are in ascending order (i.e., alphabetical). The subtle | |
1279 | distinction between "nfl" and "stdname" is that the standard name is a |
|
1279 | distinction between "nfl" and "stdname" is that the standard name is a | |
1280 | sort of the name as printed, which means that the embedded line |
|
1280 | sort of the name as printed, which means that the embedded line | |
1281 | numbers get compared in an odd way. For example, lines 3, 20, and 40 |
|
1281 | numbers get compared in an odd way. For example, lines 3, 20, and 40 | |
1282 | would (if the file names were the same) appear in the string order |
|
1282 | would (if the file names were the same) appear in the string order | |
1283 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the |
|
1283 | "20" "3" and "40". In contrast, "nfl" does a numeric compare of the | |
1284 | line numbers. In fact, sort_stats("nfl") is the same as |
|
1284 | line numbers. In fact, sort_stats("nfl") is the same as | |
1285 | sort_stats("name", "file", "line"). |
|
1285 | sort_stats("name", "file", "line"). | |
1286 |
|
1286 | |||
1287 | -T <filename>: save profile results as shown on screen to a text |
|
1287 | -T <filename>: save profile results as shown on screen to a text | |
1288 | file. The profile is still shown on screen. |
|
1288 | file. The profile is still shown on screen. | |
1289 |
|
1289 | |||
1290 | -D <filename>: save (via dump_stats) profile statistics to given |
|
1290 | -D <filename>: save (via dump_stats) profile statistics to given | |
1291 | filename. This data is in a format understod by the pstats module, and |
|
1291 | filename. This data is in a format understod by the pstats module, and | |
1292 | is generated by a call to the dump_stats() method of profile |
|
1292 | is generated by a call to the dump_stats() method of profile | |
1293 | objects. The profile is still shown on screen. |
|
1293 | objects. The profile is still shown on screen. | |
1294 |
|
1294 | |||
1295 | If you want to run complete programs under the profiler's control, use |
|
1295 | If you want to run complete programs under the profiler's control, use | |
1296 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts |
|
1296 | '%run -p [prof_opts] filename.py [args to program]' where prof_opts | |
1297 | contains profiler specific options as described here. |
|
1297 | contains profiler specific options as described here. | |
1298 |
|
1298 | |||
1299 | You can read the complete documentation for the profile module with:: |
|
1299 | You can read the complete documentation for the profile module with:: | |
1300 |
|
1300 | |||
1301 | In [1]: import profile; profile.help() |
|
1301 | In [1]: import profile; profile.help() | |
1302 | """ |
|
1302 | """ | |
1303 |
|
1303 | |||
1304 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) |
|
1304 | opts_def = Struct(D=[''],l=[],s=['time'],T=['']) | |
1305 | # protect user quote marks |
|
1305 | # protect user quote marks | |
1306 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") |
|
1306 | parameter_s = parameter_s.replace('"',r'\"').replace("'",r"\'") | |
1307 |
|
1307 | |||
1308 | if user_mode: # regular user call |
|
1308 | if user_mode: # regular user call | |
1309 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', |
|
1309 | opts,arg_str = self.parse_options(parameter_s,'D:l:rs:T:', | |
1310 | list_all=1) |
|
1310 | list_all=1) | |
1311 | namespace = self.shell.user_ns |
|
1311 | namespace = self.shell.user_ns | |
1312 | else: # called to run a program by %run -p |
|
1312 | else: # called to run a program by %run -p | |
1313 | try: |
|
1313 | try: | |
1314 | filename = get_py_filename(arg_lst[0]) |
|
1314 | filename = get_py_filename(arg_lst[0]) | |
1315 | except IOError,msg: |
|
1315 | except IOError,msg: | |
1316 | error(msg) |
|
1316 | error(msg) | |
1317 | return |
|
1317 | return | |
1318 |
|
1318 | |||
1319 | arg_str = 'execfile(filename,prog_ns)' |
|
1319 | arg_str = 'execfile(filename,prog_ns)' | |
1320 | namespace = locals() |
|
1320 | namespace = locals() | |
1321 |
|
1321 | |||
1322 | opts.merge(opts_def) |
|
1322 | opts.merge(opts_def) | |
1323 |
|
1323 | |||
1324 | prof = profile.Profile() |
|
1324 | prof = profile.Profile() | |
1325 | try: |
|
1325 | try: | |
1326 | prof = prof.runctx(arg_str,namespace,namespace) |
|
1326 | prof = prof.runctx(arg_str,namespace,namespace) | |
1327 | sys_exit = '' |
|
1327 | sys_exit = '' | |
1328 | except SystemExit: |
|
1328 | except SystemExit: | |
1329 | sys_exit = """*** SystemExit exception caught in code being profiled.""" |
|
1329 | sys_exit = """*** SystemExit exception caught in code being profiled.""" | |
1330 |
|
1330 | |||
1331 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) |
|
1331 | stats = pstats.Stats(prof).strip_dirs().sort_stats(*opts.s) | |
1332 |
|
1332 | |||
1333 | lims = opts.l |
|
1333 | lims = opts.l | |
1334 | if lims: |
|
1334 | if lims: | |
1335 | lims = [] # rebuild lims with ints/floats/strings |
|
1335 | lims = [] # rebuild lims with ints/floats/strings | |
1336 | for lim in opts.l: |
|
1336 | for lim in opts.l: | |
1337 | try: |
|
1337 | try: | |
1338 | lims.append(int(lim)) |
|
1338 | lims.append(int(lim)) | |
1339 | except ValueError: |
|
1339 | except ValueError: | |
1340 | try: |
|
1340 | try: | |
1341 | lims.append(float(lim)) |
|
1341 | lims.append(float(lim)) | |
1342 | except ValueError: |
|
1342 | except ValueError: | |
1343 | lims.append(lim) |
|
1343 | lims.append(lim) | |
1344 |
|
1344 | |||
1345 | # Trap output. |
|
1345 | # Trap output. | |
1346 | stdout_trap = StringIO() |
|
1346 | stdout_trap = StringIO() | |
1347 |
|
1347 | |||
1348 | if hasattr(stats,'stream'): |
|
1348 | if hasattr(stats,'stream'): | |
1349 | # In newer versions of python, the stats object has a 'stream' |
|
1349 | # In newer versions of python, the stats object has a 'stream' | |
1350 | # attribute to write into. |
|
1350 | # attribute to write into. | |
1351 | stats.stream = stdout_trap |
|
1351 | stats.stream = stdout_trap | |
1352 | stats.print_stats(*lims) |
|
1352 | stats.print_stats(*lims) | |
1353 | else: |
|
1353 | else: | |
1354 | # For older versions, we manually redirect stdout during printing |
|
1354 | # For older versions, we manually redirect stdout during printing | |
1355 | sys_stdout = sys.stdout |
|
1355 | sys_stdout = sys.stdout | |
1356 | try: |
|
1356 | try: | |
1357 | sys.stdout = stdout_trap |
|
1357 | sys.stdout = stdout_trap | |
1358 | stats.print_stats(*lims) |
|
1358 | stats.print_stats(*lims) | |
1359 | finally: |
|
1359 | finally: | |
1360 | sys.stdout = sys_stdout |
|
1360 | sys.stdout = sys_stdout | |
1361 |
|
1361 | |||
1362 | output = stdout_trap.getvalue() |
|
1362 | output = stdout_trap.getvalue() | |
1363 | output = output.rstrip() |
|
1363 | output = output.rstrip() | |
1364 |
|
1364 | |||
1365 | page.page(output) |
|
1365 | page.page(output) | |
1366 | print sys_exit, |
|
1366 | print sys_exit, | |
1367 |
|
1367 | |||
1368 | dump_file = opts.D[0] |
|
1368 | dump_file = opts.D[0] | |
1369 | text_file = opts.T[0] |
|
1369 | text_file = opts.T[0] | |
1370 | if dump_file: |
|
1370 | if dump_file: | |
1371 | prof.dump_stats(dump_file) |
|
1371 | prof.dump_stats(dump_file) | |
1372 | print '\n*** Profile stats marshalled to file',\ |
|
1372 | print '\n*** Profile stats marshalled to file',\ | |
1373 | `dump_file`+'.',sys_exit |
|
1373 | `dump_file`+'.',sys_exit | |
1374 | if text_file: |
|
1374 | if text_file: | |
1375 | pfile = file(text_file,'w') |
|
1375 | pfile = file(text_file,'w') | |
1376 | pfile.write(output) |
|
1376 | pfile.write(output) | |
1377 | pfile.close() |
|
1377 | pfile.close() | |
1378 | print '\n*** Profile printout saved to text file',\ |
|
1378 | print '\n*** Profile printout saved to text file',\ | |
1379 | `text_file`+'.',sys_exit |
|
1379 | `text_file`+'.',sys_exit | |
1380 |
|
1380 | |||
1381 | if opts.has_key('r'): |
|
1381 | if opts.has_key('r'): | |
1382 | return stats |
|
1382 | return stats | |
1383 | else: |
|
1383 | else: | |
1384 | return None |
|
1384 | return None | |
1385 |
|
1385 | |||
1386 | @testdec.skip_doctest |
|
1386 | @testdec.skip_doctest | |
1387 | def magic_run(self, parameter_s ='',runner=None, |
|
1387 | def magic_run(self, parameter_s ='',runner=None, | |
1388 | file_finder=get_py_filename): |
|
1388 | file_finder=get_py_filename): | |
1389 | """Run the named file inside IPython as a program. |
|
1389 | """Run the named file inside IPython as a program. | |
1390 |
|
1390 | |||
1391 | Usage:\\ |
|
1391 | Usage:\\ | |
1392 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] |
|
1392 | %run [-n -i -t [-N<N>] -d [-b<N>] -p [profile options]] file [args] | |
1393 |
|
1393 | |||
1394 | Parameters after the filename are passed as command-line arguments to |
|
1394 | Parameters after the filename are passed as command-line arguments to | |
1395 | the program (put in sys.argv). Then, control returns to IPython's |
|
1395 | the program (put in sys.argv). Then, control returns to IPython's | |
1396 | prompt. |
|
1396 | prompt. | |
1397 |
|
1397 | |||
1398 | This is similar to running at a system prompt:\\ |
|
1398 | This is similar to running at a system prompt:\\ | |
1399 | $ python file args\\ |
|
1399 | $ python file args\\ | |
1400 | but with the advantage of giving you IPython's tracebacks, and of |
|
1400 | but with the advantage of giving you IPython's tracebacks, and of | |
1401 | loading all variables into your interactive namespace for further use |
|
1401 | loading all variables into your interactive namespace for further use | |
1402 | (unless -p is used, see below). |
|
1402 | (unless -p is used, see below). | |
1403 |
|
1403 | |||
1404 | The file is executed in a namespace initially consisting only of |
|
1404 | The file is executed in a namespace initially consisting only of | |
1405 | __name__=='__main__' and sys.argv constructed as indicated. It thus |
|
1405 | __name__=='__main__' and sys.argv constructed as indicated. It thus | |
1406 | sees its environment as if it were being run as a stand-alone program |
|
1406 | sees its environment as if it were being run as a stand-alone program | |
1407 | (except for sharing global objects such as previously imported |
|
1407 | (except for sharing global objects such as previously imported | |
1408 | modules). But after execution, the IPython interactive namespace gets |
|
1408 | modules). But after execution, the IPython interactive namespace gets | |
1409 | updated with all variables defined in the program (except for __name__ |
|
1409 | updated with all variables defined in the program (except for __name__ | |
1410 | and sys.argv). This allows for very convenient loading of code for |
|
1410 | and sys.argv). This allows for very convenient loading of code for | |
1411 | interactive work, while giving each program a 'clean sheet' to run in. |
|
1411 | interactive work, while giving each program a 'clean sheet' to run in. | |
1412 |
|
1412 | |||
1413 | Options: |
|
1413 | Options: | |
1414 |
|
1414 | |||
1415 | -n: __name__ is NOT set to '__main__', but to the running file's name |
|
1415 | -n: __name__ is NOT set to '__main__', but to the running file's name | |
1416 | without extension (as python does under import). This allows running |
|
1416 | without extension (as python does under import). This allows running | |
1417 | scripts and reloading the definitions in them without calling code |
|
1417 | scripts and reloading the definitions in them without calling code | |
1418 | protected by an ' if __name__ == "__main__" ' clause. |
|
1418 | protected by an ' if __name__ == "__main__" ' clause. | |
1419 |
|
1419 | |||
1420 | -i: run the file in IPython's namespace instead of an empty one. This |
|
1420 | -i: run the file in IPython's namespace instead of an empty one. This | |
1421 | is useful if you are experimenting with code written in a text editor |
|
1421 | is useful if you are experimenting with code written in a text editor | |
1422 | which depends on variables defined interactively. |
|
1422 | which depends on variables defined interactively. | |
1423 |
|
1423 | |||
1424 | -e: ignore sys.exit() calls or SystemExit exceptions in the script |
|
1424 | -e: ignore sys.exit() calls or SystemExit exceptions in the script | |
1425 | being run. This is particularly useful if IPython is being used to |
|
1425 | being run. This is particularly useful if IPython is being used to | |
1426 | run unittests, which always exit with a sys.exit() call. In such |
|
1426 | run unittests, which always exit with a sys.exit() call. In such | |
1427 | cases you are interested in the output of the test results, not in |
|
1427 | cases you are interested in the output of the test results, not in | |
1428 | seeing a traceback of the unittest module. |
|
1428 | seeing a traceback of the unittest module. | |
1429 |
|
1429 | |||
1430 | -t: print timing information at the end of the run. IPython will give |
|
1430 | -t: print timing information at the end of the run. IPython will give | |
1431 | you an estimated CPU time consumption for your script, which under |
|
1431 | you an estimated CPU time consumption for your script, which under | |
1432 | Unix uses the resource module to avoid the wraparound problems of |
|
1432 | Unix uses the resource module to avoid the wraparound problems of | |
1433 | time.clock(). Under Unix, an estimate of time spent on system tasks |
|
1433 | time.clock(). Under Unix, an estimate of time spent on system tasks | |
1434 | is also given (for Windows platforms this is reported as 0.0). |
|
1434 | is also given (for Windows platforms this is reported as 0.0). | |
1435 |
|
1435 | |||
1436 | If -t is given, an additional -N<N> option can be given, where <N> |
|
1436 | If -t is given, an additional -N<N> option can be given, where <N> | |
1437 | must be an integer indicating how many times you want the script to |
|
1437 | must be an integer indicating how many times you want the script to | |
1438 | run. The final timing report will include total and per run results. |
|
1438 | run. The final timing report will include total and per run results. | |
1439 |
|
1439 | |||
1440 | For example (testing the script uniq_stable.py): |
|
1440 | For example (testing the script uniq_stable.py): | |
1441 |
|
1441 | |||
1442 | In [1]: run -t uniq_stable |
|
1442 | In [1]: run -t uniq_stable | |
1443 |
|
1443 | |||
1444 | IPython CPU timings (estimated):\\ |
|
1444 | IPython CPU timings (estimated):\\ | |
1445 | User : 0.19597 s.\\ |
|
1445 | User : 0.19597 s.\\ | |
1446 | System: 0.0 s.\\ |
|
1446 | System: 0.0 s.\\ | |
1447 |
|
1447 | |||
1448 | In [2]: run -t -N5 uniq_stable |
|
1448 | In [2]: run -t -N5 uniq_stable | |
1449 |
|
1449 | |||
1450 | IPython CPU timings (estimated):\\ |
|
1450 | IPython CPU timings (estimated):\\ | |
1451 | Total runs performed: 5\\ |
|
1451 | Total runs performed: 5\\ | |
1452 | Times : Total Per run\\ |
|
1452 | Times : Total Per run\\ | |
1453 | User : 0.910862 s, 0.1821724 s.\\ |
|
1453 | User : 0.910862 s, 0.1821724 s.\\ | |
1454 | System: 0.0 s, 0.0 s. |
|
1454 | System: 0.0 s, 0.0 s. | |
1455 |
|
1455 | |||
1456 | -d: run your program under the control of pdb, the Python debugger. |
|
1456 | -d: run your program under the control of pdb, the Python debugger. | |
1457 | This allows you to execute your program step by step, watch variables, |
|
1457 | This allows you to execute your program step by step, watch variables, | |
1458 | etc. Internally, what IPython does is similar to calling: |
|
1458 | etc. Internally, what IPython does is similar to calling: | |
1459 |
|
1459 | |||
1460 | pdb.run('execfile("YOURFILENAME")') |
|
1460 | pdb.run('execfile("YOURFILENAME")') | |
1461 |
|
1461 | |||
1462 | with a breakpoint set on line 1 of your file. You can change the line |
|
1462 | with a breakpoint set on line 1 of your file. You can change the line | |
1463 | number for this automatic breakpoint to be <N> by using the -bN option |
|
1463 | number for this automatic breakpoint to be <N> by using the -bN option | |
1464 | (where N must be an integer). For example: |
|
1464 | (where N must be an integer). For example: | |
1465 |
|
1465 | |||
1466 | %run -d -b40 myscript |
|
1466 | %run -d -b40 myscript | |
1467 |
|
1467 | |||
1468 | will set the first breakpoint at line 40 in myscript.py. Note that |
|
1468 | will set the first breakpoint at line 40 in myscript.py. Note that | |
1469 | the first breakpoint must be set on a line which actually does |
|
1469 | the first breakpoint must be set on a line which actually does | |
1470 | something (not a comment or docstring) for it to stop execution. |
|
1470 | something (not a comment or docstring) for it to stop execution. | |
1471 |
|
1471 | |||
1472 | When the pdb debugger starts, you will see a (Pdb) prompt. You must |
|
1472 | When the pdb debugger starts, you will see a (Pdb) prompt. You must | |
1473 | first enter 'c' (without qoutes) to start execution up to the first |
|
1473 | first enter 'c' (without qoutes) to start execution up to the first | |
1474 | breakpoint. |
|
1474 | breakpoint. | |
1475 |
|
1475 | |||
1476 | Entering 'help' gives information about the use of the debugger. You |
|
1476 | Entering 'help' gives information about the use of the debugger. You | |
1477 | can easily see pdb's full documentation with "import pdb;pdb.help()" |
|
1477 | can easily see pdb's full documentation with "import pdb;pdb.help()" | |
1478 | at a prompt. |
|
1478 | at a prompt. | |
1479 |
|
1479 | |||
1480 | -p: run program under the control of the Python profiler module (which |
|
1480 | -p: run program under the control of the Python profiler module (which | |
1481 | prints a detailed report of execution times, function calls, etc). |
|
1481 | prints a detailed report of execution times, function calls, etc). | |
1482 |
|
1482 | |||
1483 | You can pass other options after -p which affect the behavior of the |
|
1483 | You can pass other options after -p which affect the behavior of the | |
1484 | profiler itself. See the docs for %prun for details. |
|
1484 | profiler itself. See the docs for %prun for details. | |
1485 |
|
1485 | |||
1486 | In this mode, the program's variables do NOT propagate back to the |
|
1486 | In this mode, the program's variables do NOT propagate back to the | |
1487 | IPython interactive namespace (because they remain in the namespace |
|
1487 | IPython interactive namespace (because they remain in the namespace | |
1488 | where the profiler executes them). |
|
1488 | where the profiler executes them). | |
1489 |
|
1489 | |||
1490 | Internally this triggers a call to %prun, see its documentation for |
|
1490 | Internally this triggers a call to %prun, see its documentation for | |
1491 | details on the options available specifically for profiling. |
|
1491 | details on the options available specifically for profiling. | |
1492 |
|
1492 | |||
1493 | There is one special usage for which the text above doesn't apply: |
|
1493 | There is one special usage for which the text above doesn't apply: | |
1494 | if the filename ends with .ipy, the file is run as ipython script, |
|
1494 | if the filename ends with .ipy, the file is run as ipython script, | |
1495 | just as if the commands were written on IPython prompt. |
|
1495 | just as if the commands were written on IPython prompt. | |
1496 | """ |
|
1496 | """ | |
1497 |
|
1497 | |||
1498 | # get arguments and set sys.argv for program to be run. |
|
1498 | # get arguments and set sys.argv for program to be run. | |
1499 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', |
|
1499 | opts,arg_lst = self.parse_options(parameter_s,'nidtN:b:pD:l:rs:T:e', | |
1500 | mode='list',list_all=1) |
|
1500 | mode='list',list_all=1) | |
1501 |
|
1501 | |||
1502 | try: |
|
1502 | try: | |
1503 | filename = file_finder(arg_lst[0]) |
|
1503 | filename = file_finder(arg_lst[0]) | |
1504 | except IndexError: |
|
1504 | except IndexError: | |
1505 | warn('you must provide at least a filename.') |
|
1505 | warn('you must provide at least a filename.') | |
1506 | print '\n%run:\n',oinspect.getdoc(self.magic_run) |
|
1506 | print '\n%run:\n',oinspect.getdoc(self.magic_run) | |
1507 | return |
|
1507 | return | |
1508 | except IOError,msg: |
|
1508 | except IOError,msg: | |
1509 | error(msg) |
|
1509 | error(msg) | |
1510 | return |
|
1510 | return | |
1511 |
|
1511 | |||
1512 | if filename.lower().endswith('.ipy'): |
|
1512 | if filename.lower().endswith('.ipy'): | |
1513 | self.shell.safe_execfile_ipy(filename) |
|
1513 | self.shell.safe_execfile_ipy(filename) | |
1514 | return |
|
1514 | return | |
1515 |
|
1515 | |||
1516 | # Control the response to exit() calls made by the script being run |
|
1516 | # Control the response to exit() calls made by the script being run | |
1517 | exit_ignore = opts.has_key('e') |
|
1517 | exit_ignore = opts.has_key('e') | |
1518 |
|
1518 | |||
1519 | # Make sure that the running script gets a proper sys.argv as if it |
|
1519 | # Make sure that the running script gets a proper sys.argv as if it | |
1520 | # were run from a system shell. |
|
1520 | # were run from a system shell. | |
1521 | save_argv = sys.argv # save it for later restoring |
|
1521 | save_argv = sys.argv # save it for later restoring | |
1522 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename |
|
1522 | sys.argv = [filename]+ arg_lst[1:] # put in the proper filename | |
1523 |
|
1523 | |||
1524 | if opts.has_key('i'): |
|
1524 | if opts.has_key('i'): | |
1525 | # Run in user's interactive namespace |
|
1525 | # Run in user's interactive namespace | |
1526 | prog_ns = self.shell.user_ns |
|
1526 | prog_ns = self.shell.user_ns | |
1527 | __name__save = self.shell.user_ns['__name__'] |
|
1527 | __name__save = self.shell.user_ns['__name__'] | |
1528 | prog_ns['__name__'] = '__main__' |
|
1528 | prog_ns['__name__'] = '__main__' | |
1529 | main_mod = self.shell.new_main_mod(prog_ns) |
|
1529 | main_mod = self.shell.new_main_mod(prog_ns) | |
1530 | else: |
|
1530 | else: | |
1531 | # Run in a fresh, empty namespace |
|
1531 | # Run in a fresh, empty namespace | |
1532 | if opts.has_key('n'): |
|
1532 | if opts.has_key('n'): | |
1533 | name = os.path.splitext(os.path.basename(filename))[0] |
|
1533 | name = os.path.splitext(os.path.basename(filename))[0] | |
1534 | else: |
|
1534 | else: | |
1535 | name = '__main__' |
|
1535 | name = '__main__' | |
1536 |
|
1536 | |||
1537 | main_mod = self.shell.new_main_mod() |
|
1537 | main_mod = self.shell.new_main_mod() | |
1538 | prog_ns = main_mod.__dict__ |
|
1538 | prog_ns = main_mod.__dict__ | |
1539 | prog_ns['__name__'] = name |
|
1539 | prog_ns['__name__'] = name | |
1540 |
|
1540 | |||
1541 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must |
|
1541 | # Since '%run foo' emulates 'python foo.py' at the cmd line, we must | |
1542 | # set the __file__ global in the script's namespace |
|
1542 | # set the __file__ global in the script's namespace | |
1543 | prog_ns['__file__'] = filename |
|
1543 | prog_ns['__file__'] = filename | |
1544 |
|
1544 | |||
1545 | # pickle fix. See interactiveshell for an explanation. But we need to make sure |
|
1545 | # pickle fix. See interactiveshell for an explanation. But we need to make sure | |
1546 | # that, if we overwrite __main__, we replace it at the end |
|
1546 | # that, if we overwrite __main__, we replace it at the end | |
1547 | main_mod_name = prog_ns['__name__'] |
|
1547 | main_mod_name = prog_ns['__name__'] | |
1548 |
|
1548 | |||
1549 | if main_mod_name == '__main__': |
|
1549 | if main_mod_name == '__main__': | |
1550 | restore_main = sys.modules['__main__'] |
|
1550 | restore_main = sys.modules['__main__'] | |
1551 | else: |
|
1551 | else: | |
1552 | restore_main = False |
|
1552 | restore_main = False | |
1553 |
|
1553 | |||
1554 | # This needs to be undone at the end to prevent holding references to |
|
1554 | # This needs to be undone at the end to prevent holding references to | |
1555 | # every single object ever created. |
|
1555 | # every single object ever created. | |
1556 | sys.modules[main_mod_name] = main_mod |
|
1556 | sys.modules[main_mod_name] = main_mod | |
1557 |
|
1557 | |||
1558 | stats = None |
|
1558 | stats = None | |
1559 | try: |
|
1559 | try: | |
1560 | self.shell.savehist() |
|
1560 | self.shell.savehist() | |
1561 |
|
1561 | |||
1562 | if opts.has_key('p'): |
|
1562 | if opts.has_key('p'): | |
1563 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) |
|
1563 | stats = self.magic_prun('',0,opts,arg_lst,prog_ns) | |
1564 | else: |
|
1564 | else: | |
1565 | if opts.has_key('d'): |
|
1565 | if opts.has_key('d'): | |
1566 | deb = debugger.Pdb(self.shell.colors) |
|
1566 | deb = debugger.Pdb(self.shell.colors) | |
1567 | # reset Breakpoint state, which is moronically kept |
|
1567 | # reset Breakpoint state, which is moronically kept | |
1568 | # in a class |
|
1568 | # in a class | |
1569 | bdb.Breakpoint.next = 1 |
|
1569 | bdb.Breakpoint.next = 1 | |
1570 | bdb.Breakpoint.bplist = {} |
|
1570 | bdb.Breakpoint.bplist = {} | |
1571 | bdb.Breakpoint.bpbynumber = [None] |
|
1571 | bdb.Breakpoint.bpbynumber = [None] | |
1572 | # Set an initial breakpoint to stop execution |
|
1572 | # Set an initial breakpoint to stop execution | |
1573 | maxtries = 10 |
|
1573 | maxtries = 10 | |
1574 | bp = int(opts.get('b',[1])[0]) |
|
1574 | bp = int(opts.get('b',[1])[0]) | |
1575 | checkline = deb.checkline(filename,bp) |
|
1575 | checkline = deb.checkline(filename,bp) | |
1576 | if not checkline: |
|
1576 | if not checkline: | |
1577 | for bp in range(bp+1,bp+maxtries+1): |
|
1577 | for bp in range(bp+1,bp+maxtries+1): | |
1578 | if deb.checkline(filename,bp): |
|
1578 | if deb.checkline(filename,bp): | |
1579 | break |
|
1579 | break | |
1580 | else: |
|
1580 | else: | |
1581 | msg = ("\nI failed to find a valid line to set " |
|
1581 | msg = ("\nI failed to find a valid line to set " | |
1582 | "a breakpoint\n" |
|
1582 | "a breakpoint\n" | |
1583 | "after trying up to line: %s.\n" |
|
1583 | "after trying up to line: %s.\n" | |
1584 | "Please set a valid breakpoint manually " |
|
1584 | "Please set a valid breakpoint manually " | |
1585 | "with the -b option." % bp) |
|
1585 | "with the -b option." % bp) | |
1586 | error(msg) |
|
1586 | error(msg) | |
1587 | return |
|
1587 | return | |
1588 | # if we find a good linenumber, set the breakpoint |
|
1588 | # if we find a good linenumber, set the breakpoint | |
1589 | deb.do_break('%s:%s' % (filename,bp)) |
|
1589 | deb.do_break('%s:%s' % (filename,bp)) | |
1590 | # Start file run |
|
1590 | # Start file run | |
1591 | print "NOTE: Enter 'c' at the", |
|
1591 | print "NOTE: Enter 'c' at the", | |
1592 | print "%s prompt to start your script." % deb.prompt |
|
1592 | print "%s prompt to start your script." % deb.prompt | |
1593 | try: |
|
1593 | try: | |
1594 | deb.run('execfile("%s")' % filename,prog_ns) |
|
1594 | deb.run('execfile("%s")' % filename,prog_ns) | |
1595 |
|
1595 | |||
1596 | except: |
|
1596 | except: | |
1597 | etype, value, tb = sys.exc_info() |
|
1597 | etype, value, tb = sys.exc_info() | |
1598 | # Skip three frames in the traceback: the %run one, |
|
1598 | # Skip three frames in the traceback: the %run one, | |
1599 | # one inside bdb.py, and the command-line typed by the |
|
1599 | # one inside bdb.py, and the command-line typed by the | |
1600 | # user (run by exec in pdb itself). |
|
1600 | # user (run by exec in pdb itself). | |
1601 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) |
|
1601 | self.shell.InteractiveTB(etype,value,tb,tb_offset=3) | |
1602 | else: |
|
1602 | else: | |
1603 | if runner is None: |
|
1603 | if runner is None: | |
1604 | runner = self.shell.safe_execfile |
|
1604 | runner = self.shell.safe_execfile | |
1605 | if opts.has_key('t'): |
|
1605 | if opts.has_key('t'): | |
1606 | # timed execution |
|
1606 | # timed execution | |
1607 | try: |
|
1607 | try: | |
1608 | nruns = int(opts['N'][0]) |
|
1608 | nruns = int(opts['N'][0]) | |
1609 | if nruns < 1: |
|
1609 | if nruns < 1: | |
1610 | error('Number of runs must be >=1') |
|
1610 | error('Number of runs must be >=1') | |
1611 | return |
|
1611 | return | |
1612 | except (KeyError): |
|
1612 | except (KeyError): | |
1613 | nruns = 1 |
|
1613 | nruns = 1 | |
1614 | if nruns == 1: |
|
1614 | if nruns == 1: | |
1615 | t0 = clock2() |
|
1615 | t0 = clock2() | |
1616 | runner(filename,prog_ns,prog_ns, |
|
1616 | runner(filename,prog_ns,prog_ns, | |
1617 | exit_ignore=exit_ignore) |
|
1617 | exit_ignore=exit_ignore) | |
1618 | t1 = clock2() |
|
1618 | t1 = clock2() | |
1619 | t_usr = t1[0]-t0[0] |
|
1619 | t_usr = t1[0]-t0[0] | |
1620 | t_sys = t1[1]-t0[1] |
|
1620 | t_sys = t1[1]-t0[1] | |
1621 | print "\nIPython CPU timings (estimated):" |
|
1621 | print "\nIPython CPU timings (estimated):" | |
1622 | print " User : %10s s." % t_usr |
|
1622 | print " User : %10s s." % t_usr | |
1623 | print " System: %10s s." % t_sys |
|
1623 | print " System: %10s s." % t_sys | |
1624 | else: |
|
1624 | else: | |
1625 | runs = range(nruns) |
|
1625 | runs = range(nruns) | |
1626 | t0 = clock2() |
|
1626 | t0 = clock2() | |
1627 | for nr in runs: |
|
1627 | for nr in runs: | |
1628 | runner(filename,prog_ns,prog_ns, |
|
1628 | runner(filename,prog_ns,prog_ns, | |
1629 | exit_ignore=exit_ignore) |
|
1629 | exit_ignore=exit_ignore) | |
1630 | t1 = clock2() |
|
1630 | t1 = clock2() | |
1631 | t_usr = t1[0]-t0[0] |
|
1631 | t_usr = t1[0]-t0[0] | |
1632 | t_sys = t1[1]-t0[1] |
|
1632 | t_sys = t1[1]-t0[1] | |
1633 | print "\nIPython CPU timings (estimated):" |
|
1633 | print "\nIPython CPU timings (estimated):" | |
1634 | print "Total runs performed:",nruns |
|
1634 | print "Total runs performed:",nruns | |
1635 | print " Times : %10s %10s" % ('Total','Per run') |
|
1635 | print " Times : %10s %10s" % ('Total','Per run') | |
1636 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) |
|
1636 | print " User : %10s s, %10s s." % (t_usr,t_usr/nruns) | |
1637 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) |
|
1637 | print " System: %10s s, %10s s." % (t_sys,t_sys/nruns) | |
1638 |
|
1638 | |||
1639 | else: |
|
1639 | else: | |
1640 | # regular execution |
|
1640 | # regular execution | |
1641 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) |
|
1641 | runner(filename,prog_ns,prog_ns,exit_ignore=exit_ignore) | |
1642 |
|
1642 | |||
1643 | if opts.has_key('i'): |
|
1643 | if opts.has_key('i'): | |
1644 | self.shell.user_ns['__name__'] = __name__save |
|
1644 | self.shell.user_ns['__name__'] = __name__save | |
1645 | else: |
|
1645 | else: | |
1646 | # The shell MUST hold a reference to prog_ns so after %run |
|
1646 | # The shell MUST hold a reference to prog_ns so after %run | |
1647 | # exits, the python deletion mechanism doesn't zero it out |
|
1647 | # exits, the python deletion mechanism doesn't zero it out | |
1648 | # (leaving dangling references). |
|
1648 | # (leaving dangling references). | |
1649 | self.shell.cache_main_mod(prog_ns,filename) |
|
1649 | self.shell.cache_main_mod(prog_ns,filename) | |
1650 | # update IPython interactive namespace |
|
1650 | # update IPython interactive namespace | |
1651 |
|
1651 | |||
1652 | # Some forms of read errors on the file may mean the |
|
1652 | # Some forms of read errors on the file may mean the | |
1653 | # __name__ key was never set; using pop we don't have to |
|
1653 | # __name__ key was never set; using pop we don't have to | |
1654 | # worry about a possible KeyError. |
|
1654 | # worry about a possible KeyError. | |
1655 | prog_ns.pop('__name__', None) |
|
1655 | prog_ns.pop('__name__', None) | |
1656 |
|
1656 | |||
1657 | self.shell.user_ns.update(prog_ns) |
|
1657 | self.shell.user_ns.update(prog_ns) | |
1658 | finally: |
|
1658 | finally: | |
1659 | # It's a bit of a mystery why, but __builtins__ can change from |
|
1659 | # It's a bit of a mystery why, but __builtins__ can change from | |
1660 | # being a module to becoming a dict missing some key data after |
|
1660 | # being a module to becoming a dict missing some key data after | |
1661 | # %run. As best I can see, this is NOT something IPython is doing |
|
1661 | # %run. As best I can see, this is NOT something IPython is doing | |
1662 | # at all, and similar problems have been reported before: |
|
1662 | # at all, and similar problems have been reported before: | |
1663 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html |
|
1663 | # http://coding.derkeiler.com/Archive/Python/comp.lang.python/2004-10/0188.html | |
1664 | # Since this seems to be done by the interpreter itself, the best |
|
1664 | # Since this seems to be done by the interpreter itself, the best | |
1665 | # we can do is to at least restore __builtins__ for the user on |
|
1665 | # we can do is to at least restore __builtins__ for the user on | |
1666 | # exit. |
|
1666 | # exit. | |
1667 | self.shell.user_ns['__builtins__'] = __builtin__ |
|
1667 | self.shell.user_ns['__builtins__'] = __builtin__ | |
1668 |
|
1668 | |||
1669 | # Ensure key global structures are restored |
|
1669 | # Ensure key global structures are restored | |
1670 | sys.argv = save_argv |
|
1670 | sys.argv = save_argv | |
1671 | if restore_main: |
|
1671 | if restore_main: | |
1672 | sys.modules['__main__'] = restore_main |
|
1672 | sys.modules['__main__'] = restore_main | |
1673 | else: |
|
1673 | else: | |
1674 | # Remove from sys.modules the reference to main_mod we'd |
|
1674 | # Remove from sys.modules the reference to main_mod we'd | |
1675 | # added. Otherwise it will trap references to objects |
|
1675 | # added. Otherwise it will trap references to objects | |
1676 | # contained therein. |
|
1676 | # contained therein. | |
1677 | del sys.modules[main_mod_name] |
|
1677 | del sys.modules[main_mod_name] | |
1678 |
|
1678 | |||
1679 | self.shell.reloadhist() |
|
1679 | self.shell.reloadhist() | |
1680 |
|
1680 | |||
1681 | return stats |
|
1681 | return stats | |
1682 |
|
1682 | |||
1683 | @testdec.skip_doctest |
|
1683 | @testdec.skip_doctest | |
1684 | def magic_timeit(self, parameter_s =''): |
|
1684 | def magic_timeit(self, parameter_s =''): | |
1685 | """Time execution of a Python statement or expression |
|
1685 | """Time execution of a Python statement or expression | |
1686 |
|
1686 | |||
1687 | Usage:\\ |
|
1687 | Usage:\\ | |
1688 | %timeit [-n<N> -r<R> [-t|-c]] statement |
|
1688 | %timeit [-n<N> -r<R> [-t|-c]] statement | |
1689 |
|
1689 | |||
1690 | Time execution of a Python statement or expression using the timeit |
|
1690 | Time execution of a Python statement or expression using the timeit | |
1691 | module. |
|
1691 | module. | |
1692 |
|
1692 | |||
1693 | Options: |
|
1693 | Options: | |
1694 | -n<N>: execute the given statement <N> times in a loop. If this value |
|
1694 | -n<N>: execute the given statement <N> times in a loop. If this value | |
1695 | is not given, a fitting value is chosen. |
|
1695 | is not given, a fitting value is chosen. | |
1696 |
|
1696 | |||
1697 | -r<R>: repeat the loop iteration <R> times and take the best result. |
|
1697 | -r<R>: repeat the loop iteration <R> times and take the best result. | |
1698 | Default: 3 |
|
1698 | Default: 3 | |
1699 |
|
1699 | |||
1700 | -t: use time.time to measure the time, which is the default on Unix. |
|
1700 | -t: use time.time to measure the time, which is the default on Unix. | |
1701 | This function measures wall time. |
|
1701 | This function measures wall time. | |
1702 |
|
1702 | |||
1703 | -c: use time.clock to measure the time, which is the default on |
|
1703 | -c: use time.clock to measure the time, which is the default on | |
1704 | Windows and measures wall time. On Unix, resource.getrusage is used |
|
1704 | Windows and measures wall time. On Unix, resource.getrusage is used | |
1705 | instead and returns the CPU user time. |
|
1705 | instead and returns the CPU user time. | |
1706 |
|
1706 | |||
1707 | -p<P>: use a precision of <P> digits to display the timing result. |
|
1707 | -p<P>: use a precision of <P> digits to display the timing result. | |
1708 | Default: 3 |
|
1708 | Default: 3 | |
1709 |
|
1709 | |||
1710 |
|
1710 | |||
1711 | Examples: |
|
1711 | Examples: | |
1712 |
|
1712 | |||
1713 | In [1]: %timeit pass |
|
1713 | In [1]: %timeit pass | |
1714 | 10000000 loops, best of 3: 53.3 ns per loop |
|
1714 | 10000000 loops, best of 3: 53.3 ns per loop | |
1715 |
|
1715 | |||
1716 | In [2]: u = None |
|
1716 | In [2]: u = None | |
1717 |
|
1717 | |||
1718 | In [3]: %timeit u is None |
|
1718 | In [3]: %timeit u is None | |
1719 | 10000000 loops, best of 3: 184 ns per loop |
|
1719 | 10000000 loops, best of 3: 184 ns per loop | |
1720 |
|
1720 | |||
1721 | In [4]: %timeit -r 4 u == None |
|
1721 | In [4]: %timeit -r 4 u == None | |
1722 | 1000000 loops, best of 4: 242 ns per loop |
|
1722 | 1000000 loops, best of 4: 242 ns per loop | |
1723 |
|
1723 | |||
1724 | In [5]: import time |
|
1724 | In [5]: import time | |
1725 |
|
1725 | |||
1726 | In [6]: %timeit -n1 time.sleep(2) |
|
1726 | In [6]: %timeit -n1 time.sleep(2) | |
1727 | 1 loops, best of 3: 2 s per loop |
|
1727 | 1 loops, best of 3: 2 s per loop | |
1728 |
|
1728 | |||
1729 |
|
1729 | |||
1730 | The times reported by %timeit will be slightly higher than those |
|
1730 | The times reported by %timeit will be slightly higher than those | |
1731 | reported by the timeit.py script when variables are accessed. This is |
|
1731 | reported by the timeit.py script when variables are accessed. This is | |
1732 | due to the fact that %timeit executes the statement in the namespace |
|
1732 | due to the fact that %timeit executes the statement in the namespace | |
1733 | of the shell, compared with timeit.py, which uses a single setup |
|
1733 | of the shell, compared with timeit.py, which uses a single setup | |
1734 | statement to import function or create variables. Generally, the bias |
|
1734 | statement to import function or create variables. Generally, the bias | |
1735 | does not matter as long as results from timeit.py are not mixed with |
|
1735 | does not matter as long as results from timeit.py are not mixed with | |
1736 | those from %timeit.""" |
|
1736 | those from %timeit.""" | |
1737 |
|
1737 | |||
1738 | import timeit |
|
1738 | import timeit | |
1739 | import math |
|
1739 | import math | |
1740 |
|
1740 | |||
1741 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in |
|
1741 | # XXX: Unfortunately the unicode 'micro' symbol can cause problems in | |
1742 | # certain terminals. Until we figure out a robust way of |
|
1742 | # certain terminals. Until we figure out a robust way of | |
1743 | # auto-detecting if the terminal can deal with it, use plain 'us' for |
|
1743 | # auto-detecting if the terminal can deal with it, use plain 'us' for | |
1744 | # microseconds. I am really NOT happy about disabling the proper |
|
1744 | # microseconds. I am really NOT happy about disabling the proper | |
1745 | # 'micro' prefix, but crashing is worse... If anyone knows what the |
|
1745 | # 'micro' prefix, but crashing is worse... If anyone knows what the | |
1746 | # right solution for this is, I'm all ears... |
|
1746 | # right solution for this is, I'm all ears... | |
1747 | # |
|
1747 | # | |
1748 | # Note: using |
|
1748 | # Note: using | |
1749 | # |
|
1749 | # | |
1750 | # s = u'\xb5' |
|
1750 | # s = u'\xb5' | |
1751 | # s.encode(sys.getdefaultencoding()) |
|
1751 | # s.encode(sys.getdefaultencoding()) | |
1752 | # |
|
1752 | # | |
1753 | # is not sufficient, as I've seen terminals where that fails but |
|
1753 | # is not sufficient, as I've seen terminals where that fails but | |
1754 | # print s |
|
1754 | # print s | |
1755 | # |
|
1755 | # | |
1756 | # succeeds |
|
1756 | # succeeds | |
1757 | # |
|
1757 | # | |
1758 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 |
|
1758 | # See bug: https://bugs.launchpad.net/ipython/+bug/348466 | |
1759 |
|
1759 | |||
1760 | #units = [u"s", u"ms",u'\xb5',"ns"] |
|
1760 | #units = [u"s", u"ms",u'\xb5',"ns"] | |
1761 | units = [u"s", u"ms",u'us',"ns"] |
|
1761 | units = [u"s", u"ms",u'us',"ns"] | |
1762 |
|
1762 | |||
1763 | scaling = [1, 1e3, 1e6, 1e9] |
|
1763 | scaling = [1, 1e3, 1e6, 1e9] | |
1764 |
|
1764 | |||
1765 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', |
|
1765 | opts, stmt = self.parse_options(parameter_s,'n:r:tcp:', | |
1766 | posix=False) |
|
1766 | posix=False) | |
1767 | if stmt == "": |
|
1767 | if stmt == "": | |
1768 | return |
|
1768 | return | |
1769 | timefunc = timeit.default_timer |
|
1769 | timefunc = timeit.default_timer | |
1770 | number = int(getattr(opts, "n", 0)) |
|
1770 | number = int(getattr(opts, "n", 0)) | |
1771 | repeat = int(getattr(opts, "r", timeit.default_repeat)) |
|
1771 | repeat = int(getattr(opts, "r", timeit.default_repeat)) | |
1772 | precision = int(getattr(opts, "p", 3)) |
|
1772 | precision = int(getattr(opts, "p", 3)) | |
1773 | if hasattr(opts, "t"): |
|
1773 | if hasattr(opts, "t"): | |
1774 | timefunc = time.time |
|
1774 | timefunc = time.time | |
1775 | if hasattr(opts, "c"): |
|
1775 | if hasattr(opts, "c"): | |
1776 | timefunc = clock |
|
1776 | timefunc = clock | |
1777 |
|
1777 | |||
1778 | timer = timeit.Timer(timer=timefunc) |
|
1778 | timer = timeit.Timer(timer=timefunc) | |
1779 | # this code has tight coupling to the inner workings of timeit.Timer, |
|
1779 | # this code has tight coupling to the inner workings of timeit.Timer, | |
1780 | # but is there a better way to achieve that the code stmt has access |
|
1780 | # but is there a better way to achieve that the code stmt has access | |
1781 | # to the shell namespace? |
|
1781 | # to the shell namespace? | |
1782 |
|
1782 | |||
1783 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), |
|
1783 | src = timeit.template % {'stmt': timeit.reindent(stmt, 8), | |
1784 | 'setup': "pass"} |
|
1784 | 'setup': "pass"} | |
1785 | # Track compilation time so it can be reported if too long |
|
1785 | # Track compilation time so it can be reported if too long | |
1786 | # Minimum time above which compilation time will be reported |
|
1786 | # Minimum time above which compilation time will be reported | |
1787 | tc_min = 0.1 |
|
1787 | tc_min = 0.1 | |
1788 |
|
1788 | |||
1789 | t0 = clock() |
|
1789 | t0 = clock() | |
1790 | code = compile(src, "<magic-timeit>", "exec") |
|
1790 | code = compile(src, "<magic-timeit>", "exec") | |
1791 | tc = clock()-t0 |
|
1791 | tc = clock()-t0 | |
1792 |
|
1792 | |||
1793 | ns = {} |
|
1793 | ns = {} | |
1794 | exec code in self.shell.user_ns, ns |
|
1794 | exec code in self.shell.user_ns, ns | |
1795 | timer.inner = ns["inner"] |
|
1795 | timer.inner = ns["inner"] | |
1796 |
|
1796 | |||
1797 | if number == 0: |
|
1797 | if number == 0: | |
1798 | # determine number so that 0.2 <= total time < 2.0 |
|
1798 | # determine number so that 0.2 <= total time < 2.0 | |
1799 | number = 1 |
|
1799 | number = 1 | |
1800 | for i in range(1, 10): |
|
1800 | for i in range(1, 10): | |
1801 | if timer.timeit(number) >= 0.2: |
|
1801 | if timer.timeit(number) >= 0.2: | |
1802 | break |
|
1802 | break | |
1803 | number *= 10 |
|
1803 | number *= 10 | |
1804 |
|
1804 | |||
1805 | best = min(timer.repeat(repeat, number)) / number |
|
1805 | best = min(timer.repeat(repeat, number)) / number | |
1806 |
|
1806 | |||
1807 | if best > 0.0 and best < 1000.0: |
|
1807 | if best > 0.0 and best < 1000.0: | |
1808 | order = min(-int(math.floor(math.log10(best)) // 3), 3) |
|
1808 | order = min(-int(math.floor(math.log10(best)) // 3), 3) | |
1809 | elif best >= 1000.0: |
|
1809 | elif best >= 1000.0: | |
1810 | order = 0 |
|
1810 | order = 0 | |
1811 | else: |
|
1811 | else: | |
1812 | order = 3 |
|
1812 | order = 3 | |
1813 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, |
|
1813 | print u"%d loops, best of %d: %.*g %s per loop" % (number, repeat, | |
1814 | precision, |
|
1814 | precision, | |
1815 | best * scaling[order], |
|
1815 | best * scaling[order], | |
1816 | units[order]) |
|
1816 | units[order]) | |
1817 | if tc > tc_min: |
|
1817 | if tc > tc_min: | |
1818 | print "Compiler time: %.2f s" % tc |
|
1818 | print "Compiler time: %.2f s" % tc | |
1819 |
|
1819 | |||
1820 | @testdec.skip_doctest |
|
1820 | @testdec.skip_doctest | |
1821 | def magic_time(self,parameter_s = ''): |
|
1821 | def magic_time(self,parameter_s = ''): | |
1822 | """Time execution of a Python statement or expression. |
|
1822 | """Time execution of a Python statement or expression. | |
1823 |
|
1823 | |||
1824 | The CPU and wall clock times are printed, and the value of the |
|
1824 | The CPU and wall clock times are printed, and the value of the | |
1825 | expression (if any) is returned. Note that under Win32, system time |
|
1825 | expression (if any) is returned. Note that under Win32, system time | |
1826 | is always reported as 0, since it can not be measured. |
|
1826 | is always reported as 0, since it can not be measured. | |
1827 |
|
1827 | |||
1828 | This function provides very basic timing functionality. In Python |
|
1828 | This function provides very basic timing functionality. In Python | |
1829 | 2.3, the timeit module offers more control and sophistication, so this |
|
1829 | 2.3, the timeit module offers more control and sophistication, so this | |
1830 | could be rewritten to use it (patches welcome). |
|
1830 | could be rewritten to use it (patches welcome). | |
1831 |
|
1831 | |||
1832 | Some examples: |
|
1832 | Some examples: | |
1833 |
|
1833 | |||
1834 | In [1]: time 2**128 |
|
1834 | In [1]: time 2**128 | |
1835 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1835 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1836 | Wall time: 0.00 |
|
1836 | Wall time: 0.00 | |
1837 | Out[1]: 340282366920938463463374607431768211456L |
|
1837 | Out[1]: 340282366920938463463374607431768211456L | |
1838 |
|
1838 | |||
1839 | In [2]: n = 1000000 |
|
1839 | In [2]: n = 1000000 | |
1840 |
|
1840 | |||
1841 | In [3]: time sum(range(n)) |
|
1841 | In [3]: time sum(range(n)) | |
1842 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s |
|
1842 | CPU times: user 1.20 s, sys: 0.05 s, total: 1.25 s | |
1843 | Wall time: 1.37 |
|
1843 | Wall time: 1.37 | |
1844 | Out[3]: 499999500000L |
|
1844 | Out[3]: 499999500000L | |
1845 |
|
1845 | |||
1846 | In [4]: time print 'hello world' |
|
1846 | In [4]: time print 'hello world' | |
1847 | hello world |
|
1847 | hello world | |
1848 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1848 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1849 | Wall time: 0.00 |
|
1849 | Wall time: 0.00 | |
1850 |
|
1850 | |||
1851 | Note that the time needed by Python to compile the given expression |
|
1851 | Note that the time needed by Python to compile the given expression | |
1852 | will be reported if it is more than 0.1s. In this example, the |
|
1852 | will be reported if it is more than 0.1s. In this example, the | |
1853 | actual exponentiation is done by Python at compilation time, so while |
|
1853 | actual exponentiation is done by Python at compilation time, so while | |
1854 | the expression can take a noticeable amount of time to compute, that |
|
1854 | the expression can take a noticeable amount of time to compute, that | |
1855 | time is purely due to the compilation: |
|
1855 | time is purely due to the compilation: | |
1856 |
|
1856 | |||
1857 | In [5]: time 3**9999; |
|
1857 | In [5]: time 3**9999; | |
1858 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1858 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1859 | Wall time: 0.00 s |
|
1859 | Wall time: 0.00 s | |
1860 |
|
1860 | |||
1861 | In [6]: time 3**999999; |
|
1861 | In [6]: time 3**999999; | |
1862 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s |
|
1862 | CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s | |
1863 | Wall time: 0.00 s |
|
1863 | Wall time: 0.00 s | |
1864 | Compiler : 0.78 s |
|
1864 | Compiler : 0.78 s | |
1865 | """ |
|
1865 | """ | |
1866 |
|
1866 | |||
1867 | # fail immediately if the given expression can't be compiled |
|
1867 | # fail immediately if the given expression can't be compiled | |
1868 |
|
1868 | |||
1869 | expr = self.shell.prefilter(parameter_s,False) |
|
1869 | expr = self.shell.prefilter(parameter_s,False) | |
1870 |
|
1870 | |||
1871 | # Minimum time above which compilation time will be reported |
|
1871 | # Minimum time above which compilation time will be reported | |
1872 | tc_min = 0.1 |
|
1872 | tc_min = 0.1 | |
1873 |
|
1873 | |||
1874 | try: |
|
1874 | try: | |
1875 | mode = 'eval' |
|
1875 | mode = 'eval' | |
1876 | t0 = clock() |
|
1876 | t0 = clock() | |
1877 | code = compile(expr,'<timed eval>',mode) |
|
1877 | code = compile(expr,'<timed eval>',mode) | |
1878 | tc = clock()-t0 |
|
1878 | tc = clock()-t0 | |
1879 | except SyntaxError: |
|
1879 | except SyntaxError: | |
1880 | mode = 'exec' |
|
1880 | mode = 'exec' | |
1881 | t0 = clock() |
|
1881 | t0 = clock() | |
1882 | code = compile(expr,'<timed exec>',mode) |
|
1882 | code = compile(expr,'<timed exec>',mode) | |
1883 | tc = clock()-t0 |
|
1883 | tc = clock()-t0 | |
1884 | # skew measurement as little as possible |
|
1884 | # skew measurement as little as possible | |
1885 | glob = self.shell.user_ns |
|
1885 | glob = self.shell.user_ns | |
1886 | clk = clock2 |
|
1886 | clk = clock2 | |
1887 | wtime = time.time |
|
1887 | wtime = time.time | |
1888 | # time execution |
|
1888 | # time execution | |
1889 | wall_st = wtime() |
|
1889 | wall_st = wtime() | |
1890 | if mode=='eval': |
|
1890 | if mode=='eval': | |
1891 | st = clk() |
|
1891 | st = clk() | |
1892 | out = eval(code,glob) |
|
1892 | out = eval(code,glob) | |
1893 | end = clk() |
|
1893 | end = clk() | |
1894 | else: |
|
1894 | else: | |
1895 | st = clk() |
|
1895 | st = clk() | |
1896 | exec code in glob |
|
1896 | exec code in glob | |
1897 | end = clk() |
|
1897 | end = clk() | |
1898 | out = None |
|
1898 | out = None | |
1899 | wall_end = wtime() |
|
1899 | wall_end = wtime() | |
1900 | # Compute actual times and report |
|
1900 | # Compute actual times and report | |
1901 | wall_time = wall_end-wall_st |
|
1901 | wall_time = wall_end-wall_st | |
1902 | cpu_user = end[0]-st[0] |
|
1902 | cpu_user = end[0]-st[0] | |
1903 | cpu_sys = end[1]-st[1] |
|
1903 | cpu_sys = end[1]-st[1] | |
1904 | cpu_tot = cpu_user+cpu_sys |
|
1904 | cpu_tot = cpu_user+cpu_sys | |
1905 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ |
|
1905 | print "CPU times: user %.2f s, sys: %.2f s, total: %.2f s" % \ | |
1906 | (cpu_user,cpu_sys,cpu_tot) |
|
1906 | (cpu_user,cpu_sys,cpu_tot) | |
1907 | print "Wall time: %.2f s" % wall_time |
|
1907 | print "Wall time: %.2f s" % wall_time | |
1908 | if tc > tc_min: |
|
1908 | if tc > tc_min: | |
1909 | print "Compiler : %.2f s" % tc |
|
1909 | print "Compiler : %.2f s" % tc | |
1910 | return out |
|
1910 | return out | |
1911 |
|
1911 | |||
1912 | @testdec.skip_doctest |
|
1912 | @testdec.skip_doctest | |
1913 | def magic_macro(self,parameter_s = ''): |
|
1913 | def magic_macro(self,parameter_s = ''): | |
1914 | """Define a set of input lines as a macro for future re-execution. |
|
1914 | """Define a set of input lines as a macro for future re-execution. | |
1915 |
|
1915 | |||
1916 | Usage:\\ |
|
1916 | Usage:\\ | |
1917 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... |
|
1917 | %macro [options] name n1-n2 n3-n4 ... n5 .. n6 ... | |
1918 |
|
1918 | |||
1919 | Options: |
|
1919 | Options: | |
1920 |
|
1920 | |||
1921 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
1921 | -r: use 'raw' input. By default, the 'processed' history is used, | |
1922 | so that magics are loaded in their transformed version to valid |
|
1922 | so that magics are loaded in their transformed version to valid | |
1923 | Python. If this option is given, the raw input as typed as the |
|
1923 | Python. If this option is given, the raw input as typed as the | |
1924 | command line is used instead. |
|
1924 | command line is used instead. | |
1925 |
|
1925 | |||
1926 | This will define a global variable called `name` which is a string |
|
1926 | This will define a global variable called `name` which is a string | |
1927 | made of joining the slices and lines you specify (n1,n2,... numbers |
|
1927 | made of joining the slices and lines you specify (n1,n2,... numbers | |
1928 | above) from your input history into a single string. This variable |
|
1928 | above) from your input history into a single string. This variable | |
1929 | acts like an automatic function which re-executes those lines as if |
|
1929 | acts like an automatic function which re-executes those lines as if | |
1930 | you had typed them. You just type 'name' at the prompt and the code |
|
1930 | you had typed them. You just type 'name' at the prompt and the code | |
1931 | executes. |
|
1931 | executes. | |
1932 |
|
1932 | |||
1933 | The notation for indicating number ranges is: n1-n2 means 'use line |
|
1933 | The notation for indicating number ranges is: n1-n2 means 'use line | |
1934 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means |
|
1934 | numbers n1,...n2' (the endpoint is included). That is, '5-7' means | |
1935 | using the lines numbered 5,6 and 7. |
|
1935 | using the lines numbered 5,6 and 7. | |
1936 |
|
1936 | |||
1937 | Note: as a 'hidden' feature, you can also use traditional python slice |
|
1937 | Note: as a 'hidden' feature, you can also use traditional python slice | |
1938 | notation, where N:M means numbers N through M-1. |
|
1938 | notation, where N:M means numbers N through M-1. | |
1939 |
|
1939 | |||
1940 | For example, if your history contains (%hist prints it): |
|
1940 | For example, if your history contains (%hist prints it): | |
1941 |
|
1941 | |||
1942 | 44: x=1 |
|
1942 | 44: x=1 | |
1943 | 45: y=3 |
|
1943 | 45: y=3 | |
1944 | 46: z=x+y |
|
1944 | 46: z=x+y | |
1945 | 47: print x |
|
1945 | 47: print x | |
1946 | 48: a=5 |
|
1946 | 48: a=5 | |
1947 | 49: print 'x',x,'y',y |
|
1947 | 49: print 'x',x,'y',y | |
1948 |
|
1948 | |||
1949 | you can create a macro with lines 44 through 47 (included) and line 49 |
|
1949 | you can create a macro with lines 44 through 47 (included) and line 49 | |
1950 | called my_macro with: |
|
1950 | called my_macro with: | |
1951 |
|
1951 | |||
1952 | In [55]: %macro my_macro 44-47 49 |
|
1952 | In [55]: %macro my_macro 44-47 49 | |
1953 |
|
1953 | |||
1954 | Now, typing `my_macro` (without quotes) will re-execute all this code |
|
1954 | Now, typing `my_macro` (without quotes) will re-execute all this code | |
1955 | in one pass. |
|
1955 | in one pass. | |
1956 |
|
1956 | |||
1957 | You don't need to give the line-numbers in order, and any given line |
|
1957 | You don't need to give the line-numbers in order, and any given line | |
1958 | number can appear multiple times. You can assemble macros with any |
|
1958 | number can appear multiple times. You can assemble macros with any | |
1959 | lines from your input history in any order. |
|
1959 | lines from your input history in any order. | |
1960 |
|
1960 | |||
1961 | The macro is a simple object which holds its value in an attribute, |
|
1961 | The macro is a simple object which holds its value in an attribute, | |
1962 | but IPython's display system checks for macros and executes them as |
|
1962 | but IPython's display system checks for macros and executes them as | |
1963 | code instead of printing them when you type their name. |
|
1963 | code instead of printing them when you type their name. | |
1964 |
|
1964 | |||
1965 | You can view a macro's contents by explicitly printing it with: |
|
1965 | You can view a macro's contents by explicitly printing it with: | |
1966 |
|
1966 | |||
1967 | 'print macro_name'. |
|
1967 | 'print macro_name'. | |
1968 |
|
1968 | |||
1969 | For one-off cases which DON'T contain magic function calls in them you |
|
1969 | For one-off cases which DON'T contain magic function calls in them you | |
1970 | can obtain similar results by explicitly executing slices from your |
|
1970 | can obtain similar results by explicitly executing slices from your | |
1971 | input history with: |
|
1971 | input history with: | |
1972 |
|
1972 | |||
1973 | In [60]: exec In[44:48]+In[49]""" |
|
1973 | In [60]: exec In[44:48]+In[49]""" | |
1974 |
|
1974 | |||
1975 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
1975 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
1976 | if not args: |
|
1976 | if not args: | |
1977 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] |
|
1977 | macs = [k for k,v in self.shell.user_ns.items() if isinstance(v, Macro)] | |
1978 | macs.sort() |
|
1978 | macs.sort() | |
1979 | return macs |
|
1979 | return macs | |
1980 | if len(args) == 1: |
|
1980 | if len(args) == 1: | |
1981 | raise UsageError( |
|
1981 | raise UsageError( | |
1982 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") |
|
1982 | "%macro insufficient args; usage '%macro name n1-n2 n3-4...") | |
1983 | name,ranges = args[0], args[1:] |
|
1983 | name,ranges = args[0], args[1:] | |
1984 |
|
1984 | |||
1985 | #print 'rng',ranges # dbg |
|
1985 | #print 'rng',ranges # dbg | |
1986 | lines = self.extract_input_slices(ranges,opts.has_key('r')) |
|
1986 | lines = self.extract_input_slices(ranges,opts.has_key('r')) | |
1987 | macro = Macro(lines) |
|
1987 | macro = Macro(lines) | |
1988 | self.shell.define_macro(name, macro) |
|
1988 | self.shell.define_macro(name, macro) | |
1989 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name |
|
1989 | print 'Macro `%s` created. To execute, type its name (without quotes).' % name | |
1990 | print 'Macro contents:' |
|
1990 | print 'Macro contents:' | |
1991 | print macro, |
|
1991 | print macro, | |
1992 |
|
1992 | |||
1993 | def magic_save(self,parameter_s = ''): |
|
1993 | def magic_save(self,parameter_s = ''): | |
1994 | """Save a set of lines to a given filename. |
|
1994 | """Save a set of lines to a given filename. | |
1995 |
|
1995 | |||
1996 | Usage:\\ |
|
1996 | Usage:\\ | |
1997 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... |
|
1997 | %save [options] filename n1-n2 n3-n4 ... n5 .. n6 ... | |
1998 |
|
1998 | |||
1999 | Options: |
|
1999 | Options: | |
2000 |
|
2000 | |||
2001 | -r: use 'raw' input. By default, the 'processed' history is used, |
|
2001 | -r: use 'raw' input. By default, the 'processed' history is used, | |
2002 | so that magics are loaded in their transformed version to valid |
|
2002 | so that magics are loaded in their transformed version to valid | |
2003 | Python. If this option is given, the raw input as typed as the |
|
2003 | Python. If this option is given, the raw input as typed as the | |
2004 | command line is used instead. |
|
2004 | command line is used instead. | |
2005 |
|
2005 | |||
2006 | This function uses the same syntax as %macro for line extraction, but |
|
2006 | This function uses the same syntax as %macro for line extraction, but | |
2007 | instead of creating a macro it saves the resulting string to the |
|
2007 | instead of creating a macro it saves the resulting string to the | |
2008 | filename you specify. |
|
2008 | filename you specify. | |
2009 |
|
2009 | |||
2010 | It adds a '.py' extension to the file if you don't do so yourself, and |
|
2010 | It adds a '.py' extension to the file if you don't do so yourself, and | |
2011 | it asks for confirmation before overwriting existing files.""" |
|
2011 | it asks for confirmation before overwriting existing files.""" | |
2012 |
|
2012 | |||
2013 | opts,args = self.parse_options(parameter_s,'r',mode='list') |
|
2013 | opts,args = self.parse_options(parameter_s,'r',mode='list') | |
2014 | fname,ranges = args[0], args[1:] |
|
2014 | fname,ranges = args[0], args[1:] | |
2015 | if not fname.endswith('.py'): |
|
2015 | if not fname.endswith('.py'): | |
2016 | fname += '.py' |
|
2016 | fname += '.py' | |
2017 | if os.path.isfile(fname): |
|
2017 | if os.path.isfile(fname): | |
2018 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) |
|
2018 | ans = raw_input('File `%s` exists. Overwrite (y/[N])? ' % fname) | |
2019 | if ans.lower() not in ['y','yes']: |
|
2019 | if ans.lower() not in ['y','yes']: | |
2020 | print 'Operation cancelled.' |
|
2020 | print 'Operation cancelled.' | |
2021 | return |
|
2021 | return | |
2022 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) |
|
2022 | cmds = ''.join(self.extract_input_slices(ranges,opts.has_key('r'))) | |
2023 | f = file(fname,'w') |
|
2023 | f = file(fname,'w') | |
2024 | f.write(cmds) |
|
2024 | f.write(cmds) | |
2025 | f.close() |
|
2025 | f.close() | |
2026 | print 'The following commands were written to file `%s`:' % fname |
|
2026 | print 'The following commands were written to file `%s`:' % fname | |
2027 | print cmds |
|
2027 | print cmds | |
2028 |
|
2028 | |||
2029 | def _edit_macro(self,mname,macro): |
|
2029 | def _edit_macro(self,mname,macro): | |
2030 | """open an editor with the macro data in a file""" |
|
2030 | """open an editor with the macro data in a file""" | |
2031 | filename = self.shell.mktempfile(macro.value) |
|
2031 | filename = self.shell.mktempfile(macro.value) | |
2032 | self.shell.hooks.editor(filename) |
|
2032 | self.shell.hooks.editor(filename) | |
2033 |
|
2033 | |||
2034 | # and make a new macro object, to replace the old one |
|
2034 | # and make a new macro object, to replace the old one | |
2035 | mfile = open(filename) |
|
2035 | mfile = open(filename) | |
2036 | mvalue = mfile.read() |
|
2036 | mvalue = mfile.read() | |
2037 | mfile.close() |
|
2037 | mfile.close() | |
2038 | self.shell.user_ns[mname] = Macro(mvalue) |
|
2038 | self.shell.user_ns[mname] = Macro(mvalue) | |
2039 |
|
2039 | |||
2040 | def magic_ed(self,parameter_s=''): |
|
2040 | def magic_ed(self,parameter_s=''): | |
2041 | """Alias to %edit.""" |
|
2041 | """Alias to %edit.""" | |
2042 | return self.magic_edit(parameter_s) |
|
2042 | return self.magic_edit(parameter_s) | |
2043 |
|
2043 | |||
2044 | @testdec.skip_doctest |
|
2044 | @testdec.skip_doctest | |
2045 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
2045 | def magic_edit(self,parameter_s='',last_call=['','']): | |
2046 | """Bring up an editor and execute the resulting code. |
|
2046 | """Bring up an editor and execute the resulting code. | |
2047 |
|
2047 | |||
2048 | Usage: |
|
2048 | Usage: | |
2049 | %edit [options] [args] |
|
2049 | %edit [options] [args] | |
2050 |
|
2050 | |||
2051 | %edit runs IPython's editor hook. The default version of this hook is |
|
2051 | %edit runs IPython's editor hook. The default version of this hook is | |
2052 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
2052 | set to call the __IPYTHON__.rc.editor command. This is read from your | |
2053 | environment variable $EDITOR. If this isn't found, it will default to |
|
2053 | environment variable $EDITOR. If this isn't found, it will default to | |
2054 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
2054 | vi under Linux/Unix and to notepad under Windows. See the end of this | |
2055 | docstring for how to change the editor hook. |
|
2055 | docstring for how to change the editor hook. | |
2056 |
|
2056 | |||
2057 | You can also set the value of this editor via the command line option |
|
2057 | You can also set the value of this editor via the command line option | |
2058 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
2058 | '-editor' or in your ipythonrc file. This is useful if you wish to use | |
2059 | specifically for IPython an editor different from your typical default |
|
2059 | specifically for IPython an editor different from your typical default | |
2060 | (and for Windows users who typically don't set environment variables). |
|
2060 | (and for Windows users who typically don't set environment variables). | |
2061 |
|
2061 | |||
2062 | This command allows you to conveniently edit multi-line code right in |
|
2062 | This command allows you to conveniently edit multi-line code right in | |
2063 | your IPython session. |
|
2063 | your IPython session. | |
2064 |
|
2064 | |||
2065 | If called without arguments, %edit opens up an empty editor with a |
|
2065 | If called without arguments, %edit opens up an empty editor with a | |
2066 | temporary file and will execute the contents of this file when you |
|
2066 | temporary file and will execute the contents of this file when you | |
2067 | close it (don't forget to save it!). |
|
2067 | close it (don't forget to save it!). | |
2068 |
|
2068 | |||
2069 |
|
2069 | |||
2070 | Options: |
|
2070 | Options: | |
2071 |
|
2071 | |||
2072 | -n <number>: open the editor at a specified line number. By default, |
|
2072 | -n <number>: open the editor at a specified line number. By default, | |
2073 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
2073 | the IPython editor hook uses the unix syntax 'editor +N filename', but | |
2074 | you can configure this by providing your own modified hook if your |
|
2074 | you can configure this by providing your own modified hook if your | |
2075 | favorite editor supports line-number specifications with a different |
|
2075 | favorite editor supports line-number specifications with a different | |
2076 | syntax. |
|
2076 | syntax. | |
2077 |
|
2077 | |||
2078 | -p: this will call the editor with the same data as the previous time |
|
2078 | -p: this will call the editor with the same data as the previous time | |
2079 | it was used, regardless of how long ago (in your current session) it |
|
2079 | it was used, regardless of how long ago (in your current session) it | |
2080 | was. |
|
2080 | was. | |
2081 |
|
2081 | |||
2082 | -r: use 'raw' input. This option only applies to input taken from the |
|
2082 | -r: use 'raw' input. This option only applies to input taken from the | |
2083 | user's history. By default, the 'processed' history is used, so that |
|
2083 | user's history. By default, the 'processed' history is used, so that | |
2084 | magics are loaded in their transformed version to valid Python. If |
|
2084 | magics are loaded in their transformed version to valid Python. If | |
2085 | this option is given, the raw input as typed as the command line is |
|
2085 | this option is given, the raw input as typed as the command line is | |
2086 | used instead. When you exit the editor, it will be executed by |
|
2086 | used instead. When you exit the editor, it will be executed by | |
2087 | IPython's own processor. |
|
2087 | IPython's own processor. | |
2088 |
|
2088 | |||
2089 | -x: do not execute the edited code immediately upon exit. This is |
|
2089 | -x: do not execute the edited code immediately upon exit. This is | |
2090 | mainly useful if you are editing programs which need to be called with |
|
2090 | mainly useful if you are editing programs which need to be called with | |
2091 | command line arguments, which you can then do using %run. |
|
2091 | command line arguments, which you can then do using %run. | |
2092 |
|
2092 | |||
2093 |
|
2093 | |||
2094 | Arguments: |
|
2094 | Arguments: | |
2095 |
|
2095 | |||
2096 | If arguments are given, the following possibilites exist: |
|
2096 | If arguments are given, the following possibilites exist: | |
2097 |
|
2097 | |||
2098 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
2098 | - The arguments are numbers or pairs of colon-separated numbers (like | |
2099 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
2099 | 1 4:8 9). These are interpreted as lines of previous input to be | |
2100 | loaded into the editor. The syntax is the same of the %macro command. |
|
2100 | loaded into the editor. The syntax is the same of the %macro command. | |
2101 |
|
2101 | |||
2102 | - If the argument doesn't start with a number, it is evaluated as a |
|
2102 | - If the argument doesn't start with a number, it is evaluated as a | |
2103 | variable and its contents loaded into the editor. You can thus edit |
|
2103 | variable and its contents loaded into the editor. You can thus edit | |
2104 | any string which contains python code (including the result of |
|
2104 | any string which contains python code (including the result of | |
2105 | previous edits). |
|
2105 | previous edits). | |
2106 |
|
2106 | |||
2107 | - If the argument is the name of an object (other than a string), |
|
2107 | - If the argument is the name of an object (other than a string), | |
2108 | IPython will try to locate the file where it was defined and open the |
|
2108 | IPython will try to locate the file where it was defined and open the | |
2109 | editor at the point where it is defined. You can use `%edit function` |
|
2109 | editor at the point where it is defined. You can use `%edit function` | |
2110 | to load an editor exactly at the point where 'function' is defined, |
|
2110 | to load an editor exactly at the point where 'function' is defined, | |
2111 | edit it and have the file be executed automatically. |
|
2111 | edit it and have the file be executed automatically. | |
2112 |
|
2112 | |||
2113 | If the object is a macro (see %macro for details), this opens up your |
|
2113 | If the object is a macro (see %macro for details), this opens up your | |
2114 | specified editor with a temporary file containing the macro's data. |
|
2114 | specified editor with a temporary file containing the macro's data. | |
2115 | Upon exit, the macro is reloaded with the contents of the file. |
|
2115 | Upon exit, the macro is reloaded with the contents of the file. | |
2116 |
|
2116 | |||
2117 | Note: opening at an exact line is only supported under Unix, and some |
|
2117 | Note: opening at an exact line is only supported under Unix, and some | |
2118 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
2118 | editors (like kedit and gedit up to Gnome 2.8) do not understand the | |
2119 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
2119 | '+NUMBER' parameter necessary for this feature. Good editors like | |
2120 | (X)Emacs, vi, jed, pico and joe all do. |
|
2120 | (X)Emacs, vi, jed, pico and joe all do. | |
2121 |
|
2121 | |||
2122 | - If the argument is not found as a variable, IPython will look for a |
|
2122 | - If the argument is not found as a variable, IPython will look for a | |
2123 | file with that name (adding .py if necessary) and load it into the |
|
2123 | file with that name (adding .py if necessary) and load it into the | |
2124 | editor. It will execute its contents with execfile() when you exit, |
|
2124 | editor. It will execute its contents with execfile() when you exit, | |
2125 | loading any code in the file into your interactive namespace. |
|
2125 | loading any code in the file into your interactive namespace. | |
2126 |
|
2126 | |||
2127 | After executing your code, %edit will return as output the code you |
|
2127 | After executing your code, %edit will return as output the code you | |
2128 | typed in the editor (except when it was an existing file). This way |
|
2128 | typed in the editor (except when it was an existing file). This way | |
2129 | you can reload the code in further invocations of %edit as a variable, |
|
2129 | you can reload the code in further invocations of %edit as a variable, | |
2130 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
2130 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of | |
2131 | the output. |
|
2131 | the output. | |
2132 |
|
2132 | |||
2133 | Note that %edit is also available through the alias %ed. |
|
2133 | Note that %edit is also available through the alias %ed. | |
2134 |
|
2134 | |||
2135 | This is an example of creating a simple function inside the editor and |
|
2135 | This is an example of creating a simple function inside the editor and | |
2136 | then modifying it. First, start up the editor: |
|
2136 | then modifying it. First, start up the editor: | |
2137 |
|
2137 | |||
2138 | In [1]: ed |
|
2138 | In [1]: ed | |
2139 | Editing... done. Executing edited code... |
|
2139 | Editing... done. Executing edited code... | |
2140 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
2140 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' | |
2141 |
|
2141 | |||
2142 | We can then call the function foo(): |
|
2142 | We can then call the function foo(): | |
2143 |
|
2143 | |||
2144 | In [2]: foo() |
|
2144 | In [2]: foo() | |
2145 | foo() was defined in an editing session |
|
2145 | foo() was defined in an editing session | |
2146 |
|
2146 | |||
2147 | Now we edit foo. IPython automatically loads the editor with the |
|
2147 | Now we edit foo. IPython automatically loads the editor with the | |
2148 | (temporary) file where foo() was previously defined: |
|
2148 | (temporary) file where foo() was previously defined: | |
2149 |
|
2149 | |||
2150 | In [3]: ed foo |
|
2150 | In [3]: ed foo | |
2151 | Editing... done. Executing edited code... |
|
2151 | Editing... done. Executing edited code... | |
2152 |
|
2152 | |||
2153 | And if we call foo() again we get the modified version: |
|
2153 | And if we call foo() again we get the modified version: | |
2154 |
|
2154 | |||
2155 | In [4]: foo() |
|
2155 | In [4]: foo() | |
2156 | foo() has now been changed! |
|
2156 | foo() has now been changed! | |
2157 |
|
2157 | |||
2158 | Here is an example of how to edit a code snippet successive |
|
2158 | Here is an example of how to edit a code snippet successive | |
2159 | times. First we call the editor: |
|
2159 | times. First we call the editor: | |
2160 |
|
2160 | |||
2161 | In [5]: ed |
|
2161 | In [5]: ed | |
2162 | Editing... done. Executing edited code... |
|
2162 | Editing... done. Executing edited code... | |
2163 | hello |
|
2163 | hello | |
2164 | Out[5]: "print 'hello'n" |
|
2164 | Out[5]: "print 'hello'n" | |
2165 |
|
2165 | |||
2166 | Now we call it again with the previous output (stored in _): |
|
2166 | Now we call it again with the previous output (stored in _): | |
2167 |
|
2167 | |||
2168 | In [6]: ed _ |
|
2168 | In [6]: ed _ | |
2169 | Editing... done. Executing edited code... |
|
2169 | Editing... done. Executing edited code... | |
2170 | hello world |
|
2170 | hello world | |
2171 | Out[6]: "print 'hello world'n" |
|
2171 | Out[6]: "print 'hello world'n" | |
2172 |
|
2172 | |||
2173 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
2173 | Now we call it with the output #8 (stored in _8, also as Out[8]): | |
2174 |
|
2174 | |||
2175 | In [7]: ed _8 |
|
2175 | In [7]: ed _8 | |
2176 | Editing... done. Executing edited code... |
|
2176 | Editing... done. Executing edited code... | |
2177 | hello again |
|
2177 | hello again | |
2178 | Out[7]: "print 'hello again'n" |
|
2178 | Out[7]: "print 'hello again'n" | |
2179 |
|
2179 | |||
2180 |
|
2180 | |||
2181 | Changing the default editor hook: |
|
2181 | Changing the default editor hook: | |
2182 |
|
2182 | |||
2183 | If you wish to write your own editor hook, you can put it in a |
|
2183 | If you wish to write your own editor hook, you can put it in a | |
2184 | configuration file which you load at startup time. The default hook |
|
2184 | configuration file which you load at startup time. The default hook | |
2185 | is defined in the IPython.core.hooks module, and you can use that as a |
|
2185 | is defined in the IPython.core.hooks module, and you can use that as a | |
2186 | starting example for further modifications. That file also has |
|
2186 | starting example for further modifications. That file also has | |
2187 | general instructions on how to set a new hook for use once you've |
|
2187 | general instructions on how to set a new hook for use once you've | |
2188 | defined it.""" |
|
2188 | defined it.""" | |
2189 |
|
2189 | |||
2190 | # FIXME: This function has become a convoluted mess. It needs a |
|
2190 | # FIXME: This function has become a convoluted mess. It needs a | |
2191 | # ground-up rewrite with clean, simple logic. |
|
2191 | # ground-up rewrite with clean, simple logic. | |
2192 |
|
2192 | |||
2193 | def make_filename(arg): |
|
2193 | def make_filename(arg): | |
2194 | "Make a filename from the given args" |
|
2194 | "Make a filename from the given args" | |
2195 | try: |
|
2195 | try: | |
2196 | filename = get_py_filename(arg) |
|
2196 | filename = get_py_filename(arg) | |
2197 | except IOError: |
|
2197 | except IOError: | |
2198 | if args.endswith('.py'): |
|
2198 | if args.endswith('.py'): | |
2199 | filename = arg |
|
2199 | filename = arg | |
2200 | else: |
|
2200 | else: | |
2201 | filename = None |
|
2201 | filename = None | |
2202 | return filename |
|
2202 | return filename | |
2203 |
|
2203 | |||
2204 | # custom exceptions |
|
2204 | # custom exceptions | |
2205 | class DataIsObject(Exception): pass |
|
2205 | class DataIsObject(Exception): pass | |
2206 |
|
2206 | |||
2207 | opts,args = self.parse_options(parameter_s,'prxn:') |
|
2207 | opts,args = self.parse_options(parameter_s,'prxn:') | |
2208 | # Set a few locals from the options for convenience: |
|
2208 | # Set a few locals from the options for convenience: | |
2209 | opts_p = opts.has_key('p') |
|
2209 | opts_p = opts.has_key('p') | |
2210 | opts_r = opts.has_key('r') |
|
2210 | opts_r = opts.has_key('r') | |
2211 |
|
2211 | |||
2212 | # Default line number value |
|
2212 | # Default line number value | |
2213 | lineno = opts.get('n',None) |
|
2213 | lineno = opts.get('n',None) | |
2214 |
|
2214 | |||
2215 | if opts_p: |
|
2215 | if opts_p: | |
2216 | args = '_%s' % last_call[0] |
|
2216 | args = '_%s' % last_call[0] | |
2217 | if not self.shell.user_ns.has_key(args): |
|
2217 | if not self.shell.user_ns.has_key(args): | |
2218 | args = last_call[1] |
|
2218 | args = last_call[1] | |
2219 |
|
2219 | |||
2220 | # use last_call to remember the state of the previous call, but don't |
|
2220 | # use last_call to remember the state of the previous call, but don't | |
2221 | # let it be clobbered by successive '-p' calls. |
|
2221 | # let it be clobbered by successive '-p' calls. | |
2222 | try: |
|
2222 | try: | |
2223 | last_call[0] = self.shell.displayhook.prompt_count |
|
2223 | last_call[0] = self.shell.displayhook.prompt_count | |
2224 | if not opts_p: |
|
2224 | if not opts_p: | |
2225 | last_call[1] = parameter_s |
|
2225 | last_call[1] = parameter_s | |
2226 | except: |
|
2226 | except: | |
2227 | pass |
|
2227 | pass | |
2228 |
|
2228 | |||
2229 | # by default this is done with temp files, except when the given |
|
2229 | # by default this is done with temp files, except when the given | |
2230 | # arg is a filename |
|
2230 | # arg is a filename | |
2231 | use_temp = 1 |
|
2231 | use_temp = 1 | |
2232 |
|
2232 | |||
2233 | if re.match(r'\d',args): |
|
2233 | if re.match(r'\d',args): | |
2234 | # Mode where user specifies ranges of lines, like in %macro. |
|
2234 | # Mode where user specifies ranges of lines, like in %macro. | |
2235 | # This means that you can't edit files whose names begin with |
|
2235 | # This means that you can't edit files whose names begin with | |
2236 | # numbers this way. Tough. |
|
2236 | # numbers this way. Tough. | |
2237 | ranges = args.split() |
|
2237 | ranges = args.split() | |
2238 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
2238 | data = ''.join(self.extract_input_slices(ranges,opts_r)) | |
2239 | elif args.endswith('.py'): |
|
2239 | elif args.endswith('.py'): | |
2240 | filename = make_filename(args) |
|
2240 | filename = make_filename(args) | |
2241 | data = '' |
|
2241 | data = '' | |
2242 | use_temp = 0 |
|
2242 | use_temp = 0 | |
2243 | elif args: |
|
2243 | elif args: | |
2244 | try: |
|
2244 | try: | |
2245 | # Load the parameter given as a variable. If not a string, |
|
2245 | # Load the parameter given as a variable. If not a string, | |
2246 | # process it as an object instead (below) |
|
2246 | # process it as an object instead (below) | |
2247 |
|
2247 | |||
2248 | #print '*** args',args,'type',type(args) # dbg |
|
2248 | #print '*** args',args,'type',type(args) # dbg | |
2249 | data = eval(args,self.shell.user_ns) |
|
2249 | data = eval(args,self.shell.user_ns) | |
2250 | if not type(data) in StringTypes: |
|
2250 | if not type(data) in StringTypes: | |
2251 | raise DataIsObject |
|
2251 | raise DataIsObject | |
2252 |
|
2252 | |||
2253 | except (NameError,SyntaxError): |
|
2253 | except (NameError,SyntaxError): | |
2254 | # given argument is not a variable, try as a filename |
|
2254 | # given argument is not a variable, try as a filename | |
2255 | filename = make_filename(args) |
|
2255 | filename = make_filename(args) | |
2256 | if filename is None: |
|
2256 | if filename is None: | |
2257 | warn("Argument given (%s) can't be found as a variable " |
|
2257 | warn("Argument given (%s) can't be found as a variable " | |
2258 | "or as a filename." % args) |
|
2258 | "or as a filename." % args) | |
2259 | return |
|
2259 | return | |
2260 |
|
2260 | |||
2261 | data = '' |
|
2261 | data = '' | |
2262 | use_temp = 0 |
|
2262 | use_temp = 0 | |
2263 | except DataIsObject: |
|
2263 | except DataIsObject: | |
2264 |
|
2264 | |||
2265 | # macros have a special edit function |
|
2265 | # macros have a special edit function | |
2266 | if isinstance(data,Macro): |
|
2266 | if isinstance(data,Macro): | |
2267 | self._edit_macro(args,data) |
|
2267 | self._edit_macro(args,data) | |
2268 | return |
|
2268 | return | |
2269 |
|
2269 | |||
2270 | # For objects, try to edit the file where they are defined |
|
2270 | # For objects, try to edit the file where they are defined | |
2271 | try: |
|
2271 | try: | |
2272 | filename = inspect.getabsfile(data) |
|
2272 | filename = inspect.getabsfile(data) | |
2273 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
2273 | if 'fakemodule' in filename.lower() and inspect.isclass(data): | |
2274 | # class created by %edit? Try to find source |
|
2274 | # class created by %edit? Try to find source | |
2275 | # by looking for method definitions instead, the |
|
2275 | # by looking for method definitions instead, the | |
2276 | # __module__ in those classes is FakeModule. |
|
2276 | # __module__ in those classes is FakeModule. | |
2277 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
2277 | attrs = [getattr(data, aname) for aname in dir(data)] | |
2278 | for attr in attrs: |
|
2278 | for attr in attrs: | |
2279 | if not inspect.ismethod(attr): |
|
2279 | if not inspect.ismethod(attr): | |
2280 | continue |
|
2280 | continue | |
2281 | filename = inspect.getabsfile(attr) |
|
2281 | filename = inspect.getabsfile(attr) | |
2282 | if filename and 'fakemodule' not in filename.lower(): |
|
2282 | if filename and 'fakemodule' not in filename.lower(): | |
2283 | # change the attribute to be the edit target instead |
|
2283 | # change the attribute to be the edit target instead | |
2284 | data = attr |
|
2284 | data = attr | |
2285 | break |
|
2285 | break | |
2286 |
|
2286 | |||
2287 | datafile = 1 |
|
2287 | datafile = 1 | |
2288 | except TypeError: |
|
2288 | except TypeError: | |
2289 | filename = make_filename(args) |
|
2289 | filename = make_filename(args) | |
2290 | datafile = 1 |
|
2290 | datafile = 1 | |
2291 | warn('Could not find file where `%s` is defined.\n' |
|
2291 | warn('Could not find file where `%s` is defined.\n' | |
2292 | 'Opening a file named `%s`' % (args,filename)) |
|
2292 | 'Opening a file named `%s`' % (args,filename)) | |
2293 | # Now, make sure we can actually read the source (if it was in |
|
2293 | # Now, make sure we can actually read the source (if it was in | |
2294 | # a temp file it's gone by now). |
|
2294 | # a temp file it's gone by now). | |
2295 | if datafile: |
|
2295 | if datafile: | |
2296 | try: |
|
2296 | try: | |
2297 | if lineno is None: |
|
2297 | if lineno is None: | |
2298 | lineno = inspect.getsourcelines(data)[1] |
|
2298 | lineno = inspect.getsourcelines(data)[1] | |
2299 | except IOError: |
|
2299 | except IOError: | |
2300 | filename = make_filename(args) |
|
2300 | filename = make_filename(args) | |
2301 | if filename is None: |
|
2301 | if filename is None: | |
2302 | warn('The file `%s` where `%s` was defined cannot ' |
|
2302 | warn('The file `%s` where `%s` was defined cannot ' | |
2303 | 'be read.' % (filename,data)) |
|
2303 | 'be read.' % (filename,data)) | |
2304 | return |
|
2304 | return | |
2305 | use_temp = 0 |
|
2305 | use_temp = 0 | |
2306 | else: |
|
2306 | else: | |
2307 | data = '' |
|
2307 | data = '' | |
2308 |
|
2308 | |||
2309 | if use_temp: |
|
2309 | if use_temp: | |
2310 | filename = self.shell.mktempfile(data) |
|
2310 | filename = self.shell.mktempfile(data) | |
2311 | print 'IPython will make a temporary file named:',filename |
|
2311 | print 'IPython will make a temporary file named:',filename | |
2312 |
|
2312 | |||
2313 | # do actual editing here |
|
2313 | # do actual editing here | |
2314 | print 'Editing...', |
|
2314 | print 'Editing...', | |
2315 | sys.stdout.flush() |
|
2315 | sys.stdout.flush() | |
2316 | try: |
|
2316 | try: | |
2317 | # Quote filenames that may have spaces in them |
|
2317 | # Quote filenames that may have spaces in them | |
2318 | if ' ' in filename: |
|
2318 | if ' ' in filename: | |
2319 | filename = "%s" % filename |
|
2319 | filename = "%s" % filename | |
2320 | self.shell.hooks.editor(filename,lineno) |
|
2320 | self.shell.hooks.editor(filename,lineno) | |
2321 | except TryNext: |
|
2321 | except TryNext: | |
2322 | warn('Could not open editor') |
|
2322 | warn('Could not open editor') | |
2323 | return |
|
2323 | return | |
2324 |
|
2324 | |||
2325 | # XXX TODO: should this be generalized for all string vars? |
|
2325 | # XXX TODO: should this be generalized for all string vars? | |
2326 | # For now, this is special-cased to blocks created by cpaste |
|
2326 | # For now, this is special-cased to blocks created by cpaste | |
2327 | if args.strip() == 'pasted_block': |
|
2327 | if args.strip() == 'pasted_block': | |
2328 | self.shell.user_ns['pasted_block'] = file_read(filename) |
|
2328 | self.shell.user_ns['pasted_block'] = file_read(filename) | |
2329 |
|
2329 | |||
2330 | if opts.has_key('x'): # -x prevents actual execution |
|
2330 | if opts.has_key('x'): # -x prevents actual execution | |
2331 |
|
2331 | |||
2332 | else: |
|
2332 | else: | |
2333 | print 'done. Executing edited code...' |
|
2333 | print 'done. Executing edited code...' | |
2334 | if opts_r: |
|
2334 | if opts_r: | |
2335 | self.shell.runlines(file_read(filename)) |
|
2335 | self.shell.runlines(file_read(filename)) | |
2336 | else: |
|
2336 | else: | |
2337 | self.shell.safe_execfile(filename,self.shell.user_ns, |
|
2337 | self.shell.safe_execfile(filename,self.shell.user_ns, | |
2338 | self.shell.user_ns) |
|
2338 | self.shell.user_ns) | |
2339 |
|
2339 | |||
2340 |
|
2340 | |||
2341 | if use_temp: |
|
2341 | if use_temp: | |
2342 | try: |
|
2342 | try: | |
2343 | return open(filename).read() |
|
2343 | return open(filename).read() | |
2344 | except IOError,msg: |
|
2344 | except IOError,msg: | |
2345 | if msg.filename == filename: |
|
2345 | if msg.filename == filename: | |
2346 | warn('File not found. Did you forget to save?') |
|
2346 | warn('File not found. Did you forget to save?') | |
2347 | return |
|
2347 | return | |
2348 | else: |
|
2348 | else: | |
2349 | self.shell.showtraceback() |
|
2349 | self.shell.showtraceback() | |
2350 |
|
2350 | |||
2351 | def magic_xmode(self,parameter_s = ''): |
|
2351 | def magic_xmode(self,parameter_s = ''): | |
2352 | """Switch modes for the exception handlers. |
|
2352 | """Switch modes for the exception handlers. | |
2353 |
|
2353 | |||
2354 | Valid modes: Plain, Context and Verbose. |
|
2354 | Valid modes: Plain, Context and Verbose. | |
2355 |
|
2355 | |||
2356 | If called without arguments, acts as a toggle.""" |
|
2356 | If called without arguments, acts as a toggle.""" | |
2357 |
|
2357 | |||
2358 | def xmode_switch_err(name): |
|
2358 | def xmode_switch_err(name): | |
2359 | warn('Error changing %s exception modes.\n%s' % |
|
2359 | warn('Error changing %s exception modes.\n%s' % | |
2360 | (name,sys.exc_info()[1])) |
|
2360 | (name,sys.exc_info()[1])) | |
2361 |
|
2361 | |||
2362 | shell = self.shell |
|
2362 | shell = self.shell | |
2363 | new_mode = parameter_s.strip().capitalize() |
|
2363 | new_mode = parameter_s.strip().capitalize() | |
2364 | try: |
|
2364 | try: | |
2365 | shell.InteractiveTB.set_mode(mode=new_mode) |
|
2365 | shell.InteractiveTB.set_mode(mode=new_mode) | |
2366 | print 'Exception reporting mode:',shell.InteractiveTB.mode |
|
2366 | print 'Exception reporting mode:',shell.InteractiveTB.mode | |
2367 | except: |
|
2367 | except: | |
2368 | xmode_switch_err('user') |
|
2368 | xmode_switch_err('user') | |
2369 |
|
2369 | |||
2370 | def magic_colors(self,parameter_s = ''): |
|
2370 | def magic_colors(self,parameter_s = ''): | |
2371 | """Switch color scheme for prompts, info system and exception handlers. |
|
2371 | """Switch color scheme for prompts, info system and exception handlers. | |
2372 |
|
2372 | |||
2373 | Currently implemented schemes: NoColor, Linux, LightBG. |
|
2373 | Currently implemented schemes: NoColor, Linux, LightBG. | |
2374 |
|
2374 | |||
2375 | Color scheme names are not case-sensitive.""" |
|
2375 | Color scheme names are not case-sensitive.""" | |
2376 |
|
2376 | |||
2377 | def color_switch_err(name): |
|
2377 | def color_switch_err(name): | |
2378 | warn('Error changing %s color schemes.\n%s' % |
|
2378 | warn('Error changing %s color schemes.\n%s' % | |
2379 | (name,sys.exc_info()[1])) |
|
2379 | (name,sys.exc_info()[1])) | |
2380 |
|
2380 | |||
2381 |
|
2381 | |||
2382 | new_scheme = parameter_s.strip() |
|
2382 | new_scheme = parameter_s.strip() | |
2383 | if not new_scheme: |
|
2383 | if not new_scheme: | |
2384 | raise UsageError( |
|
2384 | raise UsageError( | |
2385 | "%colors: you must specify a color scheme. See '%colors?'") |
|
2385 | "%colors: you must specify a color scheme. See '%colors?'") | |
2386 | return |
|
2386 | return | |
2387 | # local shortcut |
|
2387 | # local shortcut | |
2388 | shell = self.shell |
|
2388 | shell = self.shell | |
2389 |
|
2389 | |||
2390 | import IPython.utils.rlineimpl as readline |
|
2390 | import IPython.utils.rlineimpl as readline | |
2391 |
|
2391 | |||
2392 | if not readline.have_readline and sys.platform == "win32": |
|
2392 | if not readline.have_readline and sys.platform == "win32": | |
2393 | msg = """\ |
|
2393 | msg = """\ | |
2394 | Proper color support under MS Windows requires the pyreadline library. |
|
2394 | Proper color support under MS Windows requires the pyreadline library. | |
2395 | You can find it at: |
|
2395 | You can find it at: | |
2396 | http://ipython.scipy.org/moin/PyReadline/Intro |
|
2396 | http://ipython.scipy.org/moin/PyReadline/Intro | |
2397 | Gary's readline needs the ctypes module, from: |
|
2397 | Gary's readline needs the ctypes module, from: | |
2398 | http://starship.python.net/crew/theller/ctypes |
|
2398 | http://starship.python.net/crew/theller/ctypes | |
2399 | (Note that ctypes is already part of Python versions 2.5 and newer). |
|
2399 | (Note that ctypes is already part of Python versions 2.5 and newer). | |
2400 |
|
2400 | |||
2401 | Defaulting color scheme to 'NoColor'""" |
|
2401 | Defaulting color scheme to 'NoColor'""" | |
2402 | new_scheme = 'NoColor' |
|
2402 | new_scheme = 'NoColor' | |
2403 | warn(msg) |
|
2403 | warn(msg) | |
2404 |
|
2404 | |||
2405 | # readline option is 0 |
|
2405 | # readline option is 0 | |
2406 | if not shell.has_readline: |
|
2406 | if not shell.has_readline: | |
2407 | new_scheme = 'NoColor' |
|
2407 | new_scheme = 'NoColor' | |
2408 |
|
2408 | |||
2409 | # Set prompt colors |
|
2409 | # Set prompt colors | |
2410 | try: |
|
2410 | try: | |
2411 | shell.displayhook.set_colors(new_scheme) |
|
2411 | shell.displayhook.set_colors(new_scheme) | |
2412 | except: |
|
2412 | except: | |
2413 | color_switch_err('prompt') |
|
2413 | color_switch_err('prompt') | |
2414 | else: |
|
2414 | else: | |
2415 | shell.colors = \ |
|
2415 | shell.colors = \ | |
2416 | shell.displayhook.color_table.active_scheme_name |
|
2416 | shell.displayhook.color_table.active_scheme_name | |
2417 | # Set exception colors |
|
2417 | # Set exception colors | |
2418 | try: |
|
2418 | try: | |
2419 | shell.InteractiveTB.set_colors(scheme = new_scheme) |
|
2419 | shell.InteractiveTB.set_colors(scheme = new_scheme) | |
2420 | shell.SyntaxTB.set_colors(scheme = new_scheme) |
|
2420 | shell.SyntaxTB.set_colors(scheme = new_scheme) | |
2421 | except: |
|
2421 | except: | |
2422 | color_switch_err('exception') |
|
2422 | color_switch_err('exception') | |
2423 |
|
2423 | |||
2424 | # Set info (for 'object?') colors |
|
2424 | # Set info (for 'object?') colors | |
2425 | if shell.color_info: |
|
2425 | if shell.color_info: | |
2426 | try: |
|
2426 | try: | |
2427 | shell.inspector.set_active_scheme(new_scheme) |
|
2427 | shell.inspector.set_active_scheme(new_scheme) | |
2428 | except: |
|
2428 | except: | |
2429 | color_switch_err('object inspector') |
|
2429 | color_switch_err('object inspector') | |
2430 | else: |
|
2430 | else: | |
2431 | shell.inspector.set_active_scheme('NoColor') |
|
2431 | shell.inspector.set_active_scheme('NoColor') | |
2432 |
|
2432 | |||
2433 | def magic_Pprint(self, parameter_s=''): |
|
2433 | def magic_Pprint(self, parameter_s=''): | |
2434 | """Toggle pretty printing on/off.""" |
|
2434 | """Toggle pretty printing on/off.""" | |
2435 |
|
2435 | |||
2436 | self.shell.pprint = 1 - self.shell.pprint |
|
2436 | self.shell.pprint = 1 - self.shell.pprint | |
2437 | print 'Pretty printing has been turned', \ |
|
2437 | print 'Pretty printing has been turned', \ | |
2438 | ['OFF','ON'][self.shell.pprint] |
|
2438 | ['OFF','ON'][self.shell.pprint] | |
2439 |
|
2439 | |||
2440 | def magic_Exit(self, parameter_s=''): |
|
2440 | def magic_Exit(self, parameter_s=''): | |
2441 | """Exit IPython.""" |
|
2441 | """Exit IPython.""" | |
2442 |
|
2442 | |||
2443 | self.shell.ask_exit() |
|
2443 | self.shell.ask_exit() | |
2444 |
|
2444 | |||
2445 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. |
|
2445 | # Add aliases as magics so all common forms work: exit, quit, Exit, Quit. | |
2446 | magic_exit = magic_quit = magic_Quit = magic_Exit |
|
2446 | magic_exit = magic_quit = magic_Quit = magic_Exit | |
2447 |
|
2447 | |||
2448 | #...................................................................... |
|
2448 | #...................................................................... | |
2449 | # Functions to implement unix shell-type things |
|
2449 | # Functions to implement unix shell-type things | |
2450 |
|
2450 | |||
2451 | @testdec.skip_doctest |
|
2451 | @testdec.skip_doctest | |
2452 | def magic_alias(self, parameter_s = ''): |
|
2452 | def magic_alias(self, parameter_s = ''): | |
2453 | """Define an alias for a system command. |
|
2453 | """Define an alias for a system command. | |
2454 |
|
2454 | |||
2455 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' |
|
2455 | '%alias alias_name cmd' defines 'alias_name' as an alias for 'cmd' | |
2456 |
|
2456 | |||
2457 | Then, typing 'alias_name params' will execute the system command 'cmd |
|
2457 | Then, typing 'alias_name params' will execute the system command 'cmd | |
2458 | params' (from your underlying operating system). |
|
2458 | params' (from your underlying operating system). | |
2459 |
|
2459 | |||
2460 | Aliases have lower precedence than magic functions and Python normal |
|
2460 | Aliases have lower precedence than magic functions and Python normal | |
2461 | variables, so if 'foo' is both a Python variable and an alias, the |
|
2461 | variables, so if 'foo' is both a Python variable and an alias, the | |
2462 | alias can not be executed until 'del foo' removes the Python variable. |
|
2462 | alias can not be executed until 'del foo' removes the Python variable. | |
2463 |
|
2463 | |||
2464 | You can use the %l specifier in an alias definition to represent the |
|
2464 | You can use the %l specifier in an alias definition to represent the | |
2465 | whole line when the alias is called. For example: |
|
2465 | whole line when the alias is called. For example: | |
2466 |
|
2466 | |||
2467 | In [2]: alias bracket echo "Input in brackets: <%l>" |
|
2467 | In [2]: alias bracket echo "Input in brackets: <%l>" | |
2468 | In [3]: bracket hello world |
|
2468 | In [3]: bracket hello world | |
2469 | Input in brackets: <hello world> |
|
2469 | Input in brackets: <hello world> | |
2470 |
|
2470 | |||
2471 | You can also define aliases with parameters using %s specifiers (one |
|
2471 | You can also define aliases with parameters using %s specifiers (one | |
2472 | per parameter): |
|
2472 | per parameter): | |
2473 |
|
2473 | |||
2474 | In [1]: alias parts echo first %s second %s |
|
2474 | In [1]: alias parts echo first %s second %s | |
2475 | In [2]: %parts A B |
|
2475 | In [2]: %parts A B | |
2476 | first A second B |
|
2476 | first A second B | |
2477 | In [3]: %parts A |
|
2477 | In [3]: %parts A | |
2478 | Incorrect number of arguments: 2 expected. |
|
2478 | Incorrect number of arguments: 2 expected. | |
2479 | parts is an alias to: 'echo first %s second %s' |
|
2479 | parts is an alias to: 'echo first %s second %s' | |
2480 |
|
2480 | |||
2481 | Note that %l and %s are mutually exclusive. You can only use one or |
|
2481 | Note that %l and %s are mutually exclusive. You can only use one or | |
2482 | the other in your aliases. |
|
2482 | the other in your aliases. | |
2483 |
|
2483 | |||
2484 | Aliases expand Python variables just like system calls using ! or !! |
|
2484 | Aliases expand Python variables just like system calls using ! or !! | |
2485 | do: all expressions prefixed with '$' get expanded. For details of |
|
2485 | do: all expressions prefixed with '$' get expanded. For details of | |
2486 | the semantic rules, see PEP-215: |
|
2486 | the semantic rules, see PEP-215: | |
2487 | http://www.python.org/peps/pep-0215.html. This is the library used by |
|
2487 | http://www.python.org/peps/pep-0215.html. This is the library used by | |
2488 | IPython for variable expansion. If you want to access a true shell |
|
2488 | IPython for variable expansion. If you want to access a true shell | |
2489 | variable, an extra $ is necessary to prevent its expansion by IPython: |
|
2489 | variable, an extra $ is necessary to prevent its expansion by IPython: | |
2490 |
|
2490 | |||
2491 | In [6]: alias show echo |
|
2491 | In [6]: alias show echo | |
2492 | In [7]: PATH='A Python string' |
|
2492 | In [7]: PATH='A Python string' | |
2493 | In [8]: show $PATH |
|
2493 | In [8]: show $PATH | |
2494 | A Python string |
|
2494 | A Python string | |
2495 | In [9]: show $$PATH |
|
2495 | In [9]: show $$PATH | |
2496 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... |
|
2496 | /usr/local/lf9560/bin:/usr/local/intel/compiler70/ia32/bin:... | |
2497 |
|
2497 | |||
2498 | You can use the alias facility to acess all of $PATH. See the %rehash |
|
2498 | You can use the alias facility to acess all of $PATH. See the %rehash | |
2499 | and %rehashx functions, which automatically create aliases for the |
|
2499 | and %rehashx functions, which automatically create aliases for the | |
2500 | contents of your $PATH. |
|
2500 | contents of your $PATH. | |
2501 |
|
2501 | |||
2502 | If called with no parameters, %alias prints the current alias table.""" |
|
2502 | If called with no parameters, %alias prints the current alias table.""" | |
2503 |
|
2503 | |||
2504 | par = parameter_s.strip() |
|
2504 | par = parameter_s.strip() | |
2505 | if not par: |
|
2505 | if not par: | |
2506 | stored = self.db.get('stored_aliases', {} ) |
|
2506 | stored = self.db.get('stored_aliases', {} ) | |
2507 | aliases = sorted(self.shell.alias_manager.aliases) |
|
2507 | aliases = sorted(self.shell.alias_manager.aliases) | |
2508 | # for k, v in stored: |
|
2508 | # for k, v in stored: | |
2509 | # atab.append(k, v[0]) |
|
2509 | # atab.append(k, v[0]) | |
2510 |
|
2510 | |||
2511 | print "Total number of aliases:", len(aliases) |
|
2511 | print "Total number of aliases:", len(aliases) | |
2512 | return aliases |
|
2512 | return aliases | |
2513 |
|
2513 | |||
2514 | # Now try to define a new one |
|
2514 | # Now try to define a new one | |
2515 | try: |
|
2515 | try: | |
2516 | alias,cmd = par.split(None, 1) |
|
2516 | alias,cmd = par.split(None, 1) | |
2517 | except: |
|
2517 | except: | |
2518 | print oinspect.getdoc(self.magic_alias) |
|
2518 | print oinspect.getdoc(self.magic_alias) | |
2519 | else: |
|
2519 | else: | |
2520 | self.shell.alias_manager.soft_define_alias(alias, cmd) |
|
2520 | self.shell.alias_manager.soft_define_alias(alias, cmd) | |
2521 | # end magic_alias |
|
2521 | # end magic_alias | |
2522 |
|
2522 | |||
2523 | def magic_unalias(self, parameter_s = ''): |
|
2523 | def magic_unalias(self, parameter_s = ''): | |
2524 | """Remove an alias""" |
|
2524 | """Remove an alias""" | |
2525 |
|
2525 | |||
2526 | aname = parameter_s.strip() |
|
2526 | aname = parameter_s.strip() | |
2527 | self.shell.alias_manager.undefine_alias(aname) |
|
2527 | self.shell.alias_manager.undefine_alias(aname) | |
2528 | stored = self.db.get('stored_aliases', {} ) |
|
2528 | stored = self.db.get('stored_aliases', {} ) | |
2529 | if aname in stored: |
|
2529 | if aname in stored: | |
2530 | print "Removing %stored alias",aname |
|
2530 | print "Removing %stored alias",aname | |
2531 | del stored[aname] |
|
2531 | del stored[aname] | |
2532 | self.db['stored_aliases'] = stored |
|
2532 | self.db['stored_aliases'] = stored | |
2533 |
|
2533 | |||
2534 | def magic_rehashx(self, parameter_s = ''): |
|
2534 | def magic_rehashx(self, parameter_s = ''): | |
2535 | """Update the alias table with all executable files in $PATH. |
|
2535 | """Update the alias table with all executable files in $PATH. | |
2536 |
|
2536 | |||
2537 | This version explicitly checks that every entry in $PATH is a file |
|
2537 | This version explicitly checks that every entry in $PATH is a file | |
2538 | with execute access (os.X_OK), so it is much slower than %rehash. |
|
2538 | with execute access (os.X_OK), so it is much slower than %rehash. | |
2539 |
|
2539 | |||
2540 | Under Windows, it checks executability as a match agains a |
|
2540 | Under Windows, it checks executability as a match agains a | |
2541 | '|'-separated string of extensions, stored in the IPython config |
|
2541 | '|'-separated string of extensions, stored in the IPython config | |
2542 | variable win_exec_ext. This defaults to 'exe|com|bat'. |
|
2542 | variable win_exec_ext. This defaults to 'exe|com|bat'. | |
2543 |
|
2543 | |||
2544 | This function also resets the root module cache of module completer, |
|
2544 | This function also resets the root module cache of module completer, | |
2545 | used on slow filesystems. |
|
2545 | used on slow filesystems. | |
2546 | """ |
|
2546 | """ | |
2547 | from IPython.core.alias import InvalidAliasError |
|
2547 | from IPython.core.alias import InvalidAliasError | |
2548 |
|
2548 | |||
2549 | # for the benefit of module completer in ipy_completers.py |
|
2549 | # for the benefit of module completer in ipy_completers.py | |
2550 | del self.db['rootmodules'] |
|
2550 | del self.db['rootmodules'] | |
2551 |
|
2551 | |||
2552 | path = [os.path.abspath(os.path.expanduser(p)) for p in |
|
2552 | path = [os.path.abspath(os.path.expanduser(p)) for p in | |
2553 | os.environ.get('PATH','').split(os.pathsep)] |
|
2553 | os.environ.get('PATH','').split(os.pathsep)] | |
2554 | path = filter(os.path.isdir,path) |
|
2554 | path = filter(os.path.isdir,path) | |
2555 |
|
2555 | |||
2556 | syscmdlist = [] |
|
2556 | syscmdlist = [] | |
2557 | # Now define isexec in a cross platform manner. |
|
2557 | # Now define isexec in a cross platform manner. | |
2558 | if os.name == 'posix': |
|
2558 | if os.name == 'posix': | |
2559 | isexec = lambda fname:os.path.isfile(fname) and \ |
|
2559 | isexec = lambda fname:os.path.isfile(fname) and \ | |
2560 | os.access(fname,os.X_OK) |
|
2560 | os.access(fname,os.X_OK) | |
2561 | else: |
|
2561 | else: | |
2562 | try: |
|
2562 | try: | |
2563 | winext = os.environ['pathext'].replace(';','|').replace('.','') |
|
2563 | winext = os.environ['pathext'].replace(';','|').replace('.','') | |
2564 | except KeyError: |
|
2564 | except KeyError: | |
2565 | winext = 'exe|com|bat|py' |
|
2565 | winext = 'exe|com|bat|py' | |
2566 | if 'py' not in winext: |
|
2566 | if 'py' not in winext: | |
2567 | winext += '|py' |
|
2567 | winext += '|py' | |
2568 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) |
|
2568 | execre = re.compile(r'(.*)\.(%s)$' % winext,re.IGNORECASE) | |
2569 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) |
|
2569 | isexec = lambda fname:os.path.isfile(fname) and execre.match(fname) | |
2570 | savedir = os.getcwd() |
|
2570 | savedir = os.getcwd() | |
2571 |
|
2571 | |||
2572 | # Now walk the paths looking for executables to alias. |
|
2572 | # Now walk the paths looking for executables to alias. | |
2573 | try: |
|
2573 | try: | |
2574 | # write the whole loop for posix/Windows so we don't have an if in |
|
2574 | # write the whole loop for posix/Windows so we don't have an if in | |
2575 | # the innermost part |
|
2575 | # the innermost part | |
2576 | if os.name == 'posix': |
|
2576 | if os.name == 'posix': | |
2577 | for pdir in path: |
|
2577 | for pdir in path: | |
2578 | os.chdir(pdir) |
|
2578 | os.chdir(pdir) | |
2579 | for ff in os.listdir(pdir): |
|
2579 | for ff in os.listdir(pdir): | |
2580 | if isexec(ff): |
|
2580 | if isexec(ff): | |
2581 | try: |
|
2581 | try: | |
2582 | # Removes dots from the name since ipython |
|
2582 | # Removes dots from the name since ipython | |
2583 | # will assume names with dots to be python. |
|
2583 | # will assume names with dots to be python. | |
2584 | self.shell.alias_manager.define_alias( |
|
2584 | self.shell.alias_manager.define_alias( | |
2585 | ff.replace('.',''), ff) |
|
2585 | ff.replace('.',''), ff) | |
2586 | except InvalidAliasError: |
|
2586 | except InvalidAliasError: | |
2587 | pass |
|
2587 | pass | |
2588 | else: |
|
2588 | else: | |
2589 | syscmdlist.append(ff) |
|
2589 | syscmdlist.append(ff) | |
2590 | else: |
|
2590 | else: | |
2591 | no_alias = self.shell.alias_manager.no_alias |
|
2591 | no_alias = self.shell.alias_manager.no_alias | |
2592 | for pdir in path: |
|
2592 | for pdir in path: | |
2593 | os.chdir(pdir) |
|
2593 | os.chdir(pdir) | |
2594 | for ff in os.listdir(pdir): |
|
2594 | for ff in os.listdir(pdir): | |
2595 | base, ext = os.path.splitext(ff) |
|
2595 | base, ext = os.path.splitext(ff) | |
2596 | if isexec(ff) and base.lower() not in no_alias: |
|
2596 | if isexec(ff) and base.lower() not in no_alias: | |
2597 | if ext.lower() == '.exe': |
|
2597 | if ext.lower() == '.exe': | |
2598 | ff = base |
|
2598 | ff = base | |
2599 | try: |
|
2599 | try: | |
2600 | # Removes dots from the name since ipython |
|
2600 | # Removes dots from the name since ipython | |
2601 | # will assume names with dots to be python. |
|
2601 | # will assume names with dots to be python. | |
2602 | self.shell.alias_manager.define_alias( |
|
2602 | self.shell.alias_manager.define_alias( | |
2603 | base.lower().replace('.',''), ff) |
|
2603 | base.lower().replace('.',''), ff) | |
2604 | except InvalidAliasError: |
|
2604 | except InvalidAliasError: | |
2605 | pass |
|
2605 | pass | |
2606 | syscmdlist.append(ff) |
|
2606 | syscmdlist.append(ff) | |
2607 | db = self.db |
|
2607 | db = self.db | |
2608 | db['syscmdlist'] = syscmdlist |
|
2608 | db['syscmdlist'] = syscmdlist | |
2609 | finally: |
|
2609 | finally: | |
2610 | os.chdir(savedir) |
|
2610 | os.chdir(savedir) | |
2611 |
|
2611 | |||
2612 | def magic_pwd(self, parameter_s = ''): |
|
2612 | def magic_pwd(self, parameter_s = ''): | |
2613 | """Return the current working directory path.""" |
|
2613 | """Return the current working directory path.""" | |
2614 | return os.getcwd() |
|
2614 | return os.getcwd() | |
2615 |
|
2615 | |||
2616 | def magic_cd(self, parameter_s=''): |
|
2616 | def magic_cd(self, parameter_s=''): | |
2617 | """Change the current working directory. |
|
2617 | """Change the current working directory. | |
2618 |
|
2618 | |||
2619 | This command automatically maintains an internal list of directories |
|
2619 | This command automatically maintains an internal list of directories | |
2620 | you visit during your IPython session, in the variable _dh. The |
|
2620 | you visit during your IPython session, in the variable _dh. The | |
2621 | command %dhist shows this history nicely formatted. You can also |
|
2621 | command %dhist shows this history nicely formatted. You can also | |
2622 | do 'cd -<tab>' to see directory history conveniently. |
|
2622 | do 'cd -<tab>' to see directory history conveniently. | |
2623 |
|
2623 | |||
2624 | Usage: |
|
2624 | Usage: | |
2625 |
|
2625 | |||
2626 | cd 'dir': changes to directory 'dir'. |
|
2626 | cd 'dir': changes to directory 'dir'. | |
2627 |
|
2627 | |||
2628 | cd -: changes to the last visited directory. |
|
2628 | cd -: changes to the last visited directory. | |
2629 |
|
2629 | |||
2630 | cd -<n>: changes to the n-th directory in the directory history. |
|
2630 | cd -<n>: changes to the n-th directory in the directory history. | |
2631 |
|
2631 | |||
2632 | cd --foo: change to directory that matches 'foo' in history |
|
2632 | cd --foo: change to directory that matches 'foo' in history | |
2633 |
|
2633 | |||
2634 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark |
|
2634 | cd -b <bookmark_name>: jump to a bookmark set by %bookmark | |
2635 | (note: cd <bookmark_name> is enough if there is no |
|
2635 | (note: cd <bookmark_name> is enough if there is no | |
2636 | directory <bookmark_name>, but a bookmark with the name exists.) |
|
2636 | directory <bookmark_name>, but a bookmark with the name exists.) | |
2637 | 'cd -b <tab>' allows you to tab-complete bookmark names. |
|
2637 | 'cd -b <tab>' allows you to tab-complete bookmark names. | |
2638 |
|
2638 | |||
2639 | Options: |
|
2639 | Options: | |
2640 |
|
2640 | |||
2641 | -q: quiet. Do not print the working directory after the cd command is |
|
2641 | -q: quiet. Do not print the working directory after the cd command is | |
2642 | executed. By default IPython's cd command does print this directory, |
|
2642 | executed. By default IPython's cd command does print this directory, | |
2643 | since the default prompts do not display path information. |
|
2643 | since the default prompts do not display path information. | |
2644 |
|
2644 | |||
2645 | Note that !cd doesn't work for this purpose because the shell where |
|
2645 | Note that !cd doesn't work for this purpose because the shell where | |
2646 | !command runs is immediately discarded after executing 'command'.""" |
|
2646 | !command runs is immediately discarded after executing 'command'.""" | |
2647 |
|
2647 | |||
2648 | parameter_s = parameter_s.strip() |
|
2648 | parameter_s = parameter_s.strip() | |
2649 | #bkms = self.shell.persist.get("bookmarks",{}) |
|
2649 | #bkms = self.shell.persist.get("bookmarks",{}) | |
2650 |
|
2650 | |||
2651 | oldcwd = os.getcwd() |
|
2651 | oldcwd = os.getcwd() | |
2652 | numcd = re.match(r'(-)(\d+)$',parameter_s) |
|
2652 | numcd = re.match(r'(-)(\d+)$',parameter_s) | |
2653 | # jump in directory history by number |
|
2653 | # jump in directory history by number | |
2654 | if numcd: |
|
2654 | if numcd: | |
2655 | nn = int(numcd.group(2)) |
|
2655 | nn = int(numcd.group(2)) | |
2656 | try: |
|
2656 | try: | |
2657 | ps = self.shell.user_ns['_dh'][nn] |
|
2657 | ps = self.shell.user_ns['_dh'][nn] | |
2658 | except IndexError: |
|
2658 | except IndexError: | |
2659 | print 'The requested directory does not exist in history.' |
|
2659 | print 'The requested directory does not exist in history.' | |
2660 | return |
|
2660 | return | |
2661 | else: |
|
2661 | else: | |
2662 | opts = {} |
|
2662 | opts = {} | |
2663 | elif parameter_s.startswith('--'): |
|
2663 | elif parameter_s.startswith('--'): | |
2664 | ps = None |
|
2664 | ps = None | |
2665 | fallback = None |
|
2665 | fallback = None | |
2666 | pat = parameter_s[2:] |
|
2666 | pat = parameter_s[2:] | |
2667 | dh = self.shell.user_ns['_dh'] |
|
2667 | dh = self.shell.user_ns['_dh'] | |
2668 | # first search only by basename (last component) |
|
2668 | # first search only by basename (last component) | |
2669 | for ent in reversed(dh): |
|
2669 | for ent in reversed(dh): | |
2670 | if pat in os.path.basename(ent) and os.path.isdir(ent): |
|
2670 | if pat in os.path.basename(ent) and os.path.isdir(ent): | |
2671 | ps = ent |
|
2671 | ps = ent | |
2672 | break |
|
2672 | break | |
2673 |
|
2673 | |||
2674 | if fallback is None and pat in ent and os.path.isdir(ent): |
|
2674 | if fallback is None and pat in ent and os.path.isdir(ent): | |
2675 | fallback = ent |
|
2675 | fallback = ent | |
2676 |
|
2676 | |||
2677 | # if we have no last part match, pick the first full path match |
|
2677 | # if we have no last part match, pick the first full path match | |
2678 | if ps is None: |
|
2678 | if ps is None: | |
2679 | ps = fallback |
|
2679 | ps = fallback | |
2680 |
|
2680 | |||
2681 | if ps is None: |
|
2681 | if ps is None: | |
2682 | print "No matching entry in directory history" |
|
2682 | print "No matching entry in directory history" | |
2683 | return |
|
2683 | return | |
2684 | else: |
|
2684 | else: | |
2685 | opts = {} |
|
2685 | opts = {} | |
2686 |
|
2686 | |||
2687 |
|
2687 | |||
2688 | else: |
|
2688 | else: | |
2689 | #turn all non-space-escaping backslashes to slashes, |
|
2689 | #turn all non-space-escaping backslashes to slashes, | |
2690 | # for c:\windows\directory\names\ |
|
2690 | # for c:\windows\directory\names\ | |
2691 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) |
|
2691 | parameter_s = re.sub(r'\\(?! )','/', parameter_s) | |
2692 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') |
|
2692 | opts,ps = self.parse_options(parameter_s,'qb',mode='string') | |
2693 | # jump to previous |
|
2693 | # jump to previous | |
2694 | if ps == '-': |
|
2694 | if ps == '-': | |
2695 | try: |
|
2695 | try: | |
2696 | ps = self.shell.user_ns['_dh'][-2] |
|
2696 | ps = self.shell.user_ns['_dh'][-2] | |
2697 | except IndexError: |
|
2697 | except IndexError: | |
2698 | raise UsageError('%cd -: No previous directory to change to.') |
|
2698 | raise UsageError('%cd -: No previous directory to change to.') | |
2699 | # jump to bookmark if needed |
|
2699 | # jump to bookmark if needed | |
2700 | else: |
|
2700 | else: | |
2701 | if not os.path.isdir(ps) or opts.has_key('b'): |
|
2701 | if not os.path.isdir(ps) or opts.has_key('b'): | |
2702 | bkms = self.db.get('bookmarks', {}) |
|
2702 | bkms = self.db.get('bookmarks', {}) | |
2703 |
|
2703 | |||
2704 | if bkms.has_key(ps): |
|
2704 | if bkms.has_key(ps): | |
2705 | target = bkms[ps] |
|
2705 | target = bkms[ps] | |
2706 | print '(bookmark:%s) -> %s' % (ps,target) |
|
2706 | print '(bookmark:%s) -> %s' % (ps,target) | |
2707 | ps = target |
|
2707 | ps = target | |
2708 | else: |
|
2708 | else: | |
2709 | if opts.has_key('b'): |
|
2709 | if opts.has_key('b'): | |
2710 | raise UsageError("Bookmark '%s' not found. " |
|
2710 | raise UsageError("Bookmark '%s' not found. " | |
2711 | "Use '%%bookmark -l' to see your bookmarks." % ps) |
|
2711 | "Use '%%bookmark -l' to see your bookmarks." % ps) | |
2712 |
|
2712 | |||
2713 | # at this point ps should point to the target dir |
|
2713 | # at this point ps should point to the target dir | |
2714 | if ps: |
|
2714 | if ps: | |
2715 | try: |
|
2715 | try: | |
2716 | os.chdir(os.path.expanduser(ps)) |
|
2716 | os.chdir(os.path.expanduser(ps)) | |
2717 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2717 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2718 | set_term_title('IPython: ' + abbrev_cwd()) |
|
2718 | set_term_title('IPython: ' + abbrev_cwd()) | |
2719 | except OSError: |
|
2719 | except OSError: | |
2720 | print sys.exc_info()[1] |
|
2720 | print sys.exc_info()[1] | |
2721 | else: |
|
2721 | else: | |
2722 | cwd = os.getcwd() |
|
2722 | cwd = os.getcwd() | |
2723 | dhist = self.shell.user_ns['_dh'] |
|
2723 | dhist = self.shell.user_ns['_dh'] | |
2724 | if oldcwd != cwd: |
|
2724 | if oldcwd != cwd: | |
2725 | dhist.append(cwd) |
|
2725 | dhist.append(cwd) | |
2726 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2726 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2727 |
|
2727 | |||
2728 | else: |
|
2728 | else: | |
2729 | os.chdir(self.shell.home_dir) |
|
2729 | os.chdir(self.shell.home_dir) | |
2730 | if hasattr(self.shell, 'term_title') and self.shell.term_title: |
|
2730 | if hasattr(self.shell, 'term_title') and self.shell.term_title: | |
2731 | set_term_title('IPython: ' + '~') |
|
2731 | set_term_title('IPython: ' + '~') | |
2732 | cwd = os.getcwd() |
|
2732 | cwd = os.getcwd() | |
2733 | dhist = self.shell.user_ns['_dh'] |
|
2733 | dhist = self.shell.user_ns['_dh'] | |
2734 |
|
2734 | |||
2735 | if oldcwd != cwd: |
|
2735 | if oldcwd != cwd: | |
2736 | dhist.append(cwd) |
|
2736 | dhist.append(cwd) | |
2737 | self.db['dhist'] = compress_dhist(dhist)[-100:] |
|
2737 | self.db['dhist'] = compress_dhist(dhist)[-100:] | |
2738 | if not 'q' in opts and self.shell.user_ns['_dh']: |
|
2738 | if not 'q' in opts and self.shell.user_ns['_dh']: | |
2739 | print self.shell.user_ns['_dh'][-1] |
|
2739 | print self.shell.user_ns['_dh'][-1] | |
2740 |
|
2740 | |||
2741 |
|
2741 | |||
2742 | def magic_env(self, parameter_s=''): |
|
2742 | def magic_env(self, parameter_s=''): | |
2743 | """List environment variables.""" |
|
2743 | """List environment variables.""" | |
2744 |
|
2744 | |||
2745 | return os.environ.data |
|
2745 | return os.environ.data | |
2746 |
|
2746 | |||
2747 | def magic_pushd(self, parameter_s=''): |
|
2747 | def magic_pushd(self, parameter_s=''): | |
2748 | """Place the current dir on stack and change directory. |
|
2748 | """Place the current dir on stack and change directory. | |
2749 |
|
2749 | |||
2750 | Usage:\\ |
|
2750 | Usage:\\ | |
2751 | %pushd ['dirname'] |
|
2751 | %pushd ['dirname'] | |
2752 | """ |
|
2752 | """ | |
2753 |
|
2753 | |||
2754 | dir_s = self.shell.dir_stack |
|
2754 | dir_s = self.shell.dir_stack | |
2755 | tgt = os.path.expanduser(parameter_s) |
|
2755 | tgt = os.path.expanduser(parameter_s) | |
2756 | cwd = os.getcwd().replace(self.home_dir,'~') |
|
2756 | cwd = os.getcwd().replace(self.home_dir,'~') | |
2757 | if tgt: |
|
2757 | if tgt: | |
2758 | self.magic_cd(parameter_s) |
|
2758 | self.magic_cd(parameter_s) | |
2759 | dir_s.insert(0,cwd) |
|
2759 | dir_s.insert(0,cwd) | |
2760 | return self.magic_dirs() |
|
2760 | return self.magic_dirs() | |
2761 |
|
2761 | |||
2762 | def magic_popd(self, parameter_s=''): |
|
2762 | def magic_popd(self, parameter_s=''): | |
2763 | """Change to directory popped off the top of the stack. |
|
2763 | """Change to directory popped off the top of the stack. | |
2764 | """ |
|
2764 | """ | |
2765 | if not self.shell.dir_stack: |
|
2765 | if not self.shell.dir_stack: | |
2766 | raise UsageError("%popd on empty stack") |
|
2766 | raise UsageError("%popd on empty stack") | |
2767 | top = self.shell.dir_stack.pop(0) |
|
2767 | top = self.shell.dir_stack.pop(0) | |
2768 | self.magic_cd(top) |
|
2768 | self.magic_cd(top) | |
2769 | print "popd ->",top |
|
2769 | print "popd ->",top | |
2770 |
|
2770 | |||
2771 | def magic_dirs(self, parameter_s=''): |
|
2771 | def magic_dirs(self, parameter_s=''): | |
2772 | """Return the current directory stack.""" |
|
2772 | """Return the current directory stack.""" | |
2773 |
|
2773 | |||
2774 | return self.shell.dir_stack |
|
2774 | return self.shell.dir_stack | |
2775 |
|
2775 | |||
2776 | def magic_dhist(self, parameter_s=''): |
|
2776 | def magic_dhist(self, parameter_s=''): | |
2777 | """Print your history of visited directories. |
|
2777 | """Print your history of visited directories. | |
2778 |
|
2778 | |||
2779 | %dhist -> print full history\\ |
|
2779 | %dhist -> print full history\\ | |
2780 | %dhist n -> print last n entries only\\ |
|
2780 | %dhist n -> print last n entries only\\ | |
2781 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ |
|
2781 | %dhist n1 n2 -> print entries between n1 and n2 (n1 not included)\\ | |
2782 |
|
2782 | |||
2783 | This history is automatically maintained by the %cd command, and |
|
2783 | This history is automatically maintained by the %cd command, and | |
2784 | always available as the global list variable _dh. You can use %cd -<n> |
|
2784 | always available as the global list variable _dh. You can use %cd -<n> | |
2785 | to go to directory number <n>. |
|
2785 | to go to directory number <n>. | |
2786 |
|
2786 | |||
2787 | Note that most of time, you should view directory history by entering |
|
2787 | Note that most of time, you should view directory history by entering | |
2788 | cd -<TAB>. |
|
2788 | cd -<TAB>. | |
2789 |
|
2789 | |||
2790 | """ |
|
2790 | """ | |
2791 |
|
2791 | |||
2792 | dh = self.shell.user_ns['_dh'] |
|
2792 | dh = self.shell.user_ns['_dh'] | |
2793 | if parameter_s: |
|
2793 | if parameter_s: | |
2794 | try: |
|
2794 | try: | |
2795 | args = map(int,parameter_s.split()) |
|
2795 | args = map(int,parameter_s.split()) | |
2796 | except: |
|
2796 | except: | |
2797 | self.arg_err(Magic.magic_dhist) |
|
2797 | self.arg_err(Magic.magic_dhist) | |
2798 | return |
|
2798 | return | |
2799 | if len(args) == 1: |
|
2799 | if len(args) == 1: | |
2800 | ini,fin = max(len(dh)-(args[0]),0),len(dh) |
|
2800 | ini,fin = max(len(dh)-(args[0]),0),len(dh) | |
2801 | elif len(args) == 2: |
|
2801 | elif len(args) == 2: | |
2802 | ini,fin = args |
|
2802 | ini,fin = args | |
2803 | else: |
|
2803 | else: | |
2804 | self.arg_err(Magic.magic_dhist) |
|
2804 | self.arg_err(Magic.magic_dhist) | |
2805 | return |
|
2805 | return | |
2806 | else: |
|
2806 | else: | |
2807 | ini,fin = 0,len(dh) |
|
2807 | ini,fin = 0,len(dh) | |
2808 | nlprint(dh, |
|
2808 | nlprint(dh, | |
2809 | header = 'Directory history (kept in _dh)', |
|
2809 | header = 'Directory history (kept in _dh)', | |
2810 | start=ini,stop=fin) |
|
2810 | start=ini,stop=fin) | |
2811 |
|
2811 | |||
2812 | @testdec.skip_doctest |
|
2812 | @testdec.skip_doctest | |
2813 | def magic_sc(self, parameter_s=''): |
|
2813 | def magic_sc(self, parameter_s=''): | |
2814 | """Shell capture - execute a shell command and capture its output. |
|
2814 | """Shell capture - execute a shell command and capture its output. | |
2815 |
|
2815 | |||
2816 | DEPRECATED. Suboptimal, retained for backwards compatibility. |
|
2816 | DEPRECATED. Suboptimal, retained for backwards compatibility. | |
2817 |
|
2817 | |||
2818 | You should use the form 'var = !command' instead. Example: |
|
2818 | You should use the form 'var = !command' instead. Example: | |
2819 |
|
2819 | |||
2820 | "%sc -l myfiles = ls ~" should now be written as |
|
2820 | "%sc -l myfiles = ls ~" should now be written as | |
2821 |
|
2821 | |||
2822 | "myfiles = !ls ~" |
|
2822 | "myfiles = !ls ~" | |
2823 |
|
2823 | |||
2824 | myfiles.s, myfiles.l and myfiles.n still apply as documented |
|
2824 | myfiles.s, myfiles.l and myfiles.n still apply as documented | |
2825 | below. |
|
2825 | below. | |
2826 |
|
2826 | |||
2827 | -- |
|
2827 | -- | |
2828 | %sc [options] varname=command |
|
2828 | %sc [options] varname=command | |
2829 |
|
2829 | |||
2830 | IPython will run the given command using commands.getoutput(), and |
|
2830 | IPython will run the given command using commands.getoutput(), and | |
2831 | will then update the user's interactive namespace with a variable |
|
2831 | will then update the user's interactive namespace with a variable | |
2832 | called varname, containing the value of the call. Your command can |
|
2832 | called varname, containing the value of the call. Your command can | |
2833 | contain shell wildcards, pipes, etc. |
|
2833 | contain shell wildcards, pipes, etc. | |
2834 |
|
2834 | |||
2835 | The '=' sign in the syntax is mandatory, and the variable name you |
|
2835 | The '=' sign in the syntax is mandatory, and the variable name you | |
2836 | supply must follow Python's standard conventions for valid names. |
|
2836 | supply must follow Python's standard conventions for valid names. | |
2837 |
|
2837 | |||
2838 | (A special format without variable name exists for internal use) |
|
2838 | (A special format without variable name exists for internal use) | |
2839 |
|
2839 | |||
2840 | Options: |
|
2840 | Options: | |
2841 |
|
2841 | |||
2842 | -l: list output. Split the output on newlines into a list before |
|
2842 | -l: list output. Split the output on newlines into a list before | |
2843 | assigning it to the given variable. By default the output is stored |
|
2843 | assigning it to the given variable. By default the output is stored | |
2844 | as a single string. |
|
2844 | as a single string. | |
2845 |
|
2845 | |||
2846 | -v: verbose. Print the contents of the variable. |
|
2846 | -v: verbose. Print the contents of the variable. | |
2847 |
|
2847 | |||
2848 | In most cases you should not need to split as a list, because the |
|
2848 | In most cases you should not need to split as a list, because the | |
2849 | returned value is a special type of string which can automatically |
|
2849 | returned value is a special type of string which can automatically | |
2850 | provide its contents either as a list (split on newlines) or as a |
|
2850 | provide its contents either as a list (split on newlines) or as a | |
2851 | space-separated string. These are convenient, respectively, either |
|
2851 | space-separated string. These are convenient, respectively, either | |
2852 | for sequential processing or to be passed to a shell command. |
|
2852 | for sequential processing or to be passed to a shell command. | |
2853 |
|
2853 | |||
2854 | For example: |
|
2854 | For example: | |
2855 |
|
2855 | |||
2856 | # all-random |
|
2856 | # all-random | |
2857 |
|
2857 | |||
2858 | # Capture into variable a |
|
2858 | # Capture into variable a | |
2859 | In [1]: sc a=ls *py |
|
2859 | In [1]: sc a=ls *py | |
2860 |
|
2860 | |||
2861 | # a is a string with embedded newlines |
|
2861 | # a is a string with embedded newlines | |
2862 | In [2]: a |
|
2862 | In [2]: a | |
2863 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' |
|
2863 | Out[2]: 'setup.py\\nwin32_manual_post_install.py' | |
2864 |
|
2864 | |||
2865 | # which can be seen as a list: |
|
2865 | # which can be seen as a list: | |
2866 | In [3]: a.l |
|
2866 | In [3]: a.l | |
2867 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] |
|
2867 | Out[3]: ['setup.py', 'win32_manual_post_install.py'] | |
2868 |
|
2868 | |||
2869 | # or as a whitespace-separated string: |
|
2869 | # or as a whitespace-separated string: | |
2870 | In [4]: a.s |
|
2870 | In [4]: a.s | |
2871 | Out[4]: 'setup.py win32_manual_post_install.py' |
|
2871 | Out[4]: 'setup.py win32_manual_post_install.py' | |
2872 |
|
2872 | |||
2873 | # a.s is useful to pass as a single command line: |
|
2873 | # a.s is useful to pass as a single command line: | |
2874 | In [5]: !wc -l $a.s |
|
2874 | In [5]: !wc -l $a.s | |
2875 | 146 setup.py |
|
2875 | 146 setup.py | |
2876 | 130 win32_manual_post_install.py |
|
2876 | 130 win32_manual_post_install.py | |
2877 | 276 total |
|
2877 | 276 total | |
2878 |
|
2878 | |||
2879 | # while the list form is useful to loop over: |
|
2879 | # while the list form is useful to loop over: | |
2880 | In [6]: for f in a.l: |
|
2880 | In [6]: for f in a.l: | |
2881 | ...: !wc -l $f |
|
2881 | ...: !wc -l $f | |
2882 | ...: |
|
2882 | ...: | |
2883 | 146 setup.py |
|
2883 | 146 setup.py | |
2884 | 130 win32_manual_post_install.py |
|
2884 | 130 win32_manual_post_install.py | |
2885 |
|
2885 | |||
2886 | Similiarly, the lists returned by the -l option are also special, in |
|
2886 | Similiarly, the lists returned by the -l option are also special, in | |
2887 | the sense that you can equally invoke the .s attribute on them to |
|
2887 | the sense that you can equally invoke the .s attribute on them to | |
2888 | automatically get a whitespace-separated string from their contents: |
|
2888 | automatically get a whitespace-separated string from their contents: | |
2889 |
|
2889 | |||
2890 | In [7]: sc -l b=ls *py |
|
2890 | In [7]: sc -l b=ls *py | |
2891 |
|
2891 | |||
2892 | In [8]: b |
|
2892 | In [8]: b | |
2893 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] |
|
2893 | Out[8]: ['setup.py', 'win32_manual_post_install.py'] | |
2894 |
|
2894 | |||
2895 | In [9]: b.s |
|
2895 | In [9]: b.s | |
2896 | Out[9]: 'setup.py win32_manual_post_install.py' |
|
2896 | Out[9]: 'setup.py win32_manual_post_install.py' | |
2897 |
|
2897 | |||
2898 | In summary, both the lists and strings used for ouptut capture have |
|
2898 | In summary, both the lists and strings used for ouptut capture have | |
2899 | the following special attributes: |
|
2899 | the following special attributes: | |
2900 |
|
2900 | |||
2901 | .l (or .list) : value as list. |
|
2901 | .l (or .list) : value as list. | |
2902 | .n (or .nlstr): value as newline-separated string. |
|
2902 | .n (or .nlstr): value as newline-separated string. | |
2903 | .s (or .spstr): value as space-separated string. |
|
2903 | .s (or .spstr): value as space-separated string. | |
2904 | """ |
|
2904 | """ | |
2905 |
|
2905 | |||
2906 | opts,args = self.parse_options(parameter_s,'lv') |
|
2906 | opts,args = self.parse_options(parameter_s,'lv') | |
2907 | # Try to get a variable name and command to run |
|
2907 | # Try to get a variable name and command to run | |
2908 | try: |
|
2908 | try: | |
2909 | # the variable name must be obtained from the parse_options |
|
2909 | # the variable name must be obtained from the parse_options | |
2910 | # output, which uses shlex.split to strip options out. |
|
2910 | # output, which uses shlex.split to strip options out. | |
2911 | var,_ = args.split('=',1) |
|
2911 | var,_ = args.split('=',1) | |
2912 | var = var.strip() |
|
2912 | var = var.strip() | |
2913 | # But the the command has to be extracted from the original input |
|
2913 | # But the the command has to be extracted from the original input | |
2914 | # parameter_s, not on what parse_options returns, to avoid the |
|
2914 | # parameter_s, not on what parse_options returns, to avoid the | |
2915 | # quote stripping which shlex.split performs on it. |
|
2915 | # quote stripping which shlex.split performs on it. | |
2916 | _,cmd = parameter_s.split('=',1) |
|
2916 | _,cmd = parameter_s.split('=',1) | |
2917 | except ValueError: |
|
2917 | except ValueError: | |
2918 | var,cmd = '','' |
|
2918 | var,cmd = '','' | |
2919 | # If all looks ok, proceed |
|
2919 | # If all looks ok, proceed | |
2920 | out = self.shell.getoutput(cmd) |
|
2920 | out = self.shell.getoutput(cmd) | |
2921 | if opts.has_key('l'): |
|
2921 | if opts.has_key('l'): | |
2922 |
out = SList(out.split( |
|
2922 | out = SList(out.splitlines()) | |
2923 | else: |
|
2923 | else: | |
2924 | out = LSString(out) |
|
2924 | out = LSString(out) | |
2925 | if opts.has_key('v'): |
|
2925 | if opts.has_key('v'): | |
2926 | print '%s ==\n%s' % (var,pformat(out)) |
|
2926 | print '%s ==\n%s' % (var,pformat(out)) | |
2927 | if var: |
|
2927 | if var: | |
2928 | self.shell.user_ns.update({var:out}) |
|
2928 | self.shell.user_ns.update({var:out}) | |
2929 | else: |
|
2929 | else: | |
2930 | return out |
|
2930 | return out | |
2931 |
|
2931 | |||
2932 | def magic_sx(self, parameter_s=''): |
|
2932 | def magic_sx(self, parameter_s=''): | |
2933 | """Shell execute - run a shell command and capture its output. |
|
2933 | """Shell execute - run a shell command and capture its output. | |
2934 |
|
2934 | |||
2935 | %sx command |
|
2935 | %sx command | |
2936 |
|
2936 | |||
2937 | IPython will run the given command using commands.getoutput(), and |
|
2937 | IPython will run the given command using commands.getoutput(), and | |
2938 | return the result formatted as a list (split on '\\n'). Since the |
|
2938 | return the result formatted as a list (split on '\\n'). Since the | |
2939 | output is _returned_, it will be stored in ipython's regular output |
|
2939 | output is _returned_, it will be stored in ipython's regular output | |
2940 | cache Out[N] and in the '_N' automatic variables. |
|
2940 | cache Out[N] and in the '_N' automatic variables. | |
2941 |
|
2941 | |||
2942 | Notes: |
|
2942 | Notes: | |
2943 |
|
2943 | |||
2944 | 1) If an input line begins with '!!', then %sx is automatically |
|
2944 | 1) If an input line begins with '!!', then %sx is automatically | |
2945 | invoked. That is, while: |
|
2945 | invoked. That is, while: | |
2946 | !ls |
|
2946 | !ls | |
2947 | causes ipython to simply issue system('ls'), typing |
|
2947 | causes ipython to simply issue system('ls'), typing | |
2948 | !!ls |
|
2948 | !!ls | |
2949 | is a shorthand equivalent to: |
|
2949 | is a shorthand equivalent to: | |
2950 | %sx ls |
|
2950 | %sx ls | |
2951 |
|
2951 | |||
2952 | 2) %sx differs from %sc in that %sx automatically splits into a list, |
|
2952 | 2) %sx differs from %sc in that %sx automatically splits into a list, | |
2953 | like '%sc -l'. The reason for this is to make it as easy as possible |
|
2953 | like '%sc -l'. The reason for this is to make it as easy as possible | |
2954 | to process line-oriented shell output via further python commands. |
|
2954 | to process line-oriented shell output via further python commands. | |
2955 | %sc is meant to provide much finer control, but requires more |
|
2955 | %sc is meant to provide much finer control, but requires more | |
2956 | typing. |
|
2956 | typing. | |
2957 |
|
2957 | |||
2958 | 3) Just like %sc -l, this is a list with special attributes: |
|
2958 | 3) Just like %sc -l, this is a list with special attributes: | |
2959 |
|
2959 | |||
2960 | .l (or .list) : value as list. |
|
2960 | .l (or .list) : value as list. | |
2961 | .n (or .nlstr): value as newline-separated string. |
|
2961 | .n (or .nlstr): value as newline-separated string. | |
2962 | .s (or .spstr): value as whitespace-separated string. |
|
2962 | .s (or .spstr): value as whitespace-separated string. | |
2963 |
|
2963 | |||
2964 | This is very useful when trying to use such lists as arguments to |
|
2964 | This is very useful when trying to use such lists as arguments to | |
2965 | system commands.""" |
|
2965 | system commands.""" | |
2966 |
|
2966 | |||
2967 | if parameter_s: |
|
2967 | if parameter_s: | |
2968 | out = self.shell.getoutput(parameter_s) |
|
2968 | out = self.shell.getoutput(parameter_s) | |
2969 | if out is not None: |
|
2969 | if out is not None: | |
2970 | return SList(out.splitlines()) |
|
2970 | return SList(out.splitlines()) | |
2971 |
|
2971 | |||
2972 | def magic_r(self, parameter_s=''): |
|
2972 | def magic_r(self, parameter_s=''): | |
2973 | """Repeat previous input. |
|
2973 | """Repeat previous input. | |
2974 |
|
2974 | |||
2975 | Note: Consider using the more powerfull %rep instead! |
|
2975 | Note: Consider using the more powerfull %rep instead! | |
2976 |
|
2976 | |||
2977 | If given an argument, repeats the previous command which starts with |
|
2977 | If given an argument, repeats the previous command which starts with | |
2978 | the same string, otherwise it just repeats the previous input. |
|
2978 | the same string, otherwise it just repeats the previous input. | |
2979 |
|
2979 | |||
2980 | Shell escaped commands (with ! as first character) are not recognized |
|
2980 | Shell escaped commands (with ! as first character) are not recognized | |
2981 | by this system, only pure python code and magic commands. |
|
2981 | by this system, only pure python code and magic commands. | |
2982 | """ |
|
2982 | """ | |
2983 |
|
2983 | |||
2984 | start = parameter_s.strip() |
|
2984 | start = parameter_s.strip() | |
2985 | esc_magic = ESC_MAGIC |
|
2985 | esc_magic = ESC_MAGIC | |
2986 | # Identify magic commands even if automagic is on (which means |
|
2986 | # Identify magic commands even if automagic is on (which means | |
2987 | # the in-memory version is different from that typed by the user). |
|
2987 | # the in-memory version is different from that typed by the user). | |
2988 | if self.shell.automagic: |
|
2988 | if self.shell.automagic: | |
2989 | start_magic = esc_magic+start |
|
2989 | start_magic = esc_magic+start | |
2990 | else: |
|
2990 | else: | |
2991 | start_magic = start |
|
2991 | start_magic = start | |
2992 | # Look through the input history in reverse |
|
2992 | # Look through the input history in reverse | |
2993 | for n in range(len(self.shell.input_hist)-2,0,-1): |
|
2993 | for n in range(len(self.shell.input_hist)-2,0,-1): | |
2994 | input = self.shell.input_hist[n] |
|
2994 | input = self.shell.input_hist[n] | |
2995 | # skip plain 'r' lines so we don't recurse to infinity |
|
2995 | # skip plain 'r' lines so we don't recurse to infinity | |
2996 | if input != '_ip.magic("r")\n' and \ |
|
2996 | if input != '_ip.magic("r")\n' and \ | |
2997 | (input.startswith(start) or input.startswith(start_magic)): |
|
2997 | (input.startswith(start) or input.startswith(start_magic)): | |
2998 | #print 'match',`input` # dbg |
|
2998 | #print 'match',`input` # dbg | |
2999 | print 'Executing:',input, |
|
2999 | print 'Executing:',input, | |
3000 | self.shell.runlines(input) |
|
3000 | self.shell.runlines(input) | |
3001 | return |
|
3001 | return | |
3002 | print 'No previous input matching `%s` found.' % start |
|
3002 | print 'No previous input matching `%s` found.' % start | |
3003 |
|
3003 | |||
3004 |
|
3004 | |||
3005 | def magic_bookmark(self, parameter_s=''): |
|
3005 | def magic_bookmark(self, parameter_s=''): | |
3006 | """Manage IPython's bookmark system. |
|
3006 | """Manage IPython's bookmark system. | |
3007 |
|
3007 | |||
3008 | %bookmark <name> - set bookmark to current dir |
|
3008 | %bookmark <name> - set bookmark to current dir | |
3009 | %bookmark <name> <dir> - set bookmark to <dir> |
|
3009 | %bookmark <name> <dir> - set bookmark to <dir> | |
3010 | %bookmark -l - list all bookmarks |
|
3010 | %bookmark -l - list all bookmarks | |
3011 | %bookmark -d <name> - remove bookmark |
|
3011 | %bookmark -d <name> - remove bookmark | |
3012 | %bookmark -r - remove all bookmarks |
|
3012 | %bookmark -r - remove all bookmarks | |
3013 |
|
3013 | |||
3014 | You can later on access a bookmarked folder with: |
|
3014 | You can later on access a bookmarked folder with: | |
3015 | %cd -b <name> |
|
3015 | %cd -b <name> | |
3016 | or simply '%cd <name>' if there is no directory called <name> AND |
|
3016 | or simply '%cd <name>' if there is no directory called <name> AND | |
3017 | there is such a bookmark defined. |
|
3017 | there is such a bookmark defined. | |
3018 |
|
3018 | |||
3019 | Your bookmarks persist through IPython sessions, but they are |
|
3019 | Your bookmarks persist through IPython sessions, but they are | |
3020 | associated with each profile.""" |
|
3020 | associated with each profile.""" | |
3021 |
|
3021 | |||
3022 | opts,args = self.parse_options(parameter_s,'drl',mode='list') |
|
3022 | opts,args = self.parse_options(parameter_s,'drl',mode='list') | |
3023 | if len(args) > 2: |
|
3023 | if len(args) > 2: | |
3024 | raise UsageError("%bookmark: too many arguments") |
|
3024 | raise UsageError("%bookmark: too many arguments") | |
3025 |
|
3025 | |||
3026 | bkms = self.db.get('bookmarks',{}) |
|
3026 | bkms = self.db.get('bookmarks',{}) | |
3027 |
|
3027 | |||
3028 | if opts.has_key('d'): |
|
3028 | if opts.has_key('d'): | |
3029 | try: |
|
3029 | try: | |
3030 | todel = args[0] |
|
3030 | todel = args[0] | |
3031 | except IndexError: |
|
3031 | except IndexError: | |
3032 | raise UsageError( |
|
3032 | raise UsageError( | |
3033 | "%bookmark -d: must provide a bookmark to delete") |
|
3033 | "%bookmark -d: must provide a bookmark to delete") | |
3034 | else: |
|
3034 | else: | |
3035 | try: |
|
3035 | try: | |
3036 | del bkms[todel] |
|
3036 | del bkms[todel] | |
3037 | except KeyError: |
|
3037 | except KeyError: | |
3038 | raise UsageError( |
|
3038 | raise UsageError( | |
3039 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) |
|
3039 | "%%bookmark -d: Can't delete bookmark '%s'" % todel) | |
3040 |
|
3040 | |||
3041 | elif opts.has_key('r'): |
|
3041 | elif opts.has_key('r'): | |
3042 | bkms = {} |
|
3042 | bkms = {} | |
3043 | elif opts.has_key('l'): |
|
3043 | elif opts.has_key('l'): | |
3044 | bks = bkms.keys() |
|
3044 | bks = bkms.keys() | |
3045 | bks.sort() |
|
3045 | bks.sort() | |
3046 | if bks: |
|
3046 | if bks: | |
3047 | size = max(map(len,bks)) |
|
3047 | size = max(map(len,bks)) | |
3048 | else: |
|
3048 | else: | |
3049 | size = 0 |
|
3049 | size = 0 | |
3050 | fmt = '%-'+str(size)+'s -> %s' |
|
3050 | fmt = '%-'+str(size)+'s -> %s' | |
3051 | print 'Current bookmarks:' |
|
3051 | print 'Current bookmarks:' | |
3052 | for bk in bks: |
|
3052 | for bk in bks: | |
3053 | print fmt % (bk,bkms[bk]) |
|
3053 | print fmt % (bk,bkms[bk]) | |
3054 | else: |
|
3054 | else: | |
3055 | if not args: |
|
3055 | if not args: | |
3056 | raise UsageError("%bookmark: You must specify the bookmark name") |
|
3056 | raise UsageError("%bookmark: You must specify the bookmark name") | |
3057 | elif len(args)==1: |
|
3057 | elif len(args)==1: | |
3058 | bkms[args[0]] = os.getcwd() |
|
3058 | bkms[args[0]] = os.getcwd() | |
3059 | elif len(args)==2: |
|
3059 | elif len(args)==2: | |
3060 | bkms[args[0]] = args[1] |
|
3060 | bkms[args[0]] = args[1] | |
3061 | self.db['bookmarks'] = bkms |
|
3061 | self.db['bookmarks'] = bkms | |
3062 |
|
3062 | |||
3063 | def magic_pycat(self, parameter_s=''): |
|
3063 | def magic_pycat(self, parameter_s=''): | |
3064 | """Show a syntax-highlighted file through a pager. |
|
3064 | """Show a syntax-highlighted file through a pager. | |
3065 |
|
3065 | |||
3066 | This magic is similar to the cat utility, but it will assume the file |
|
3066 | This magic is similar to the cat utility, but it will assume the file | |
3067 | to be Python source and will show it with syntax highlighting. """ |
|
3067 | to be Python source and will show it with syntax highlighting. """ | |
3068 |
|
3068 | |||
3069 | try: |
|
3069 | try: | |
3070 | filename = get_py_filename(parameter_s) |
|
3070 | filename = get_py_filename(parameter_s) | |
3071 | cont = file_read(filename) |
|
3071 | cont = file_read(filename) | |
3072 | except IOError: |
|
3072 | except IOError: | |
3073 | try: |
|
3073 | try: | |
3074 | cont = eval(parameter_s,self.user_ns) |
|
3074 | cont = eval(parameter_s,self.user_ns) | |
3075 | except NameError: |
|
3075 | except NameError: | |
3076 | cont = None |
|
3076 | cont = None | |
3077 | if cont is None: |
|
3077 | if cont is None: | |
3078 | print "Error: no such file or variable" |
|
3078 | print "Error: no such file or variable" | |
3079 | return |
|
3079 | return | |
3080 |
|
3080 | |||
3081 | page.page(self.shell.pycolorize(cont)) |
|
3081 | page.page(self.shell.pycolorize(cont)) | |
3082 |
|
3082 | |||
3083 | def _rerun_pasted(self): |
|
3083 | def _rerun_pasted(self): | |
3084 | """ Rerun a previously pasted command. |
|
3084 | """ Rerun a previously pasted command. | |
3085 | """ |
|
3085 | """ | |
3086 | b = self.user_ns.get('pasted_block', None) |
|
3086 | b = self.user_ns.get('pasted_block', None) | |
3087 | if b is None: |
|
3087 | if b is None: | |
3088 | raise UsageError('No previous pasted block available') |
|
3088 | raise UsageError('No previous pasted block available') | |
3089 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) |
|
3089 | print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b)) | |
3090 | exec b in self.user_ns |
|
3090 | exec b in self.user_ns | |
3091 |
|
3091 | |||
3092 | def _get_pasted_lines(self, sentinel): |
|
3092 | def _get_pasted_lines(self, sentinel): | |
3093 | """ Yield pasted lines until the user enters the given sentinel value. |
|
3093 | """ Yield pasted lines until the user enters the given sentinel value. | |
3094 | """ |
|
3094 | """ | |
3095 | from IPython.core import interactiveshell |
|
3095 | from IPython.core import interactiveshell | |
3096 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel |
|
3096 | print "Pasting code; enter '%s' alone on the line to stop." % sentinel | |
3097 | while True: |
|
3097 | while True: | |
3098 | l = interactiveshell.raw_input_original(':') |
|
3098 | l = interactiveshell.raw_input_original(':') | |
3099 | if l == sentinel: |
|
3099 | if l == sentinel: | |
3100 | return |
|
3100 | return | |
3101 | else: |
|
3101 | else: | |
3102 | yield l |
|
3102 | yield l | |
3103 |
|
3103 | |||
3104 | def _strip_pasted_lines_for_code(self, raw_lines): |
|
3104 | def _strip_pasted_lines_for_code(self, raw_lines): | |
3105 | """ Strip non-code parts of a sequence of lines to return a block of |
|
3105 | """ Strip non-code parts of a sequence of lines to return a block of | |
3106 | code. |
|
3106 | code. | |
3107 | """ |
|
3107 | """ | |
3108 | # Regular expressions that declare text we strip from the input: |
|
3108 | # Regular expressions that declare text we strip from the input: | |
3109 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt |
|
3109 | strip_re = [r'^\s*In \[\d+\]:', # IPython input prompt | |
3110 | r'^\s*(\s?>)+', # Python input prompt |
|
3110 | r'^\s*(\s?>)+', # Python input prompt | |
3111 | r'^\s*\.{3,}', # Continuation prompts |
|
3111 | r'^\s*\.{3,}', # Continuation prompts | |
3112 | r'^\++', |
|
3112 | r'^\++', | |
3113 | ] |
|
3113 | ] | |
3114 |
|
3114 | |||
3115 | strip_from_start = map(re.compile,strip_re) |
|
3115 | strip_from_start = map(re.compile,strip_re) | |
3116 |
|
3116 | |||
3117 | lines = [] |
|
3117 | lines = [] | |
3118 | for l in raw_lines: |
|
3118 | for l in raw_lines: | |
3119 | for pat in strip_from_start: |
|
3119 | for pat in strip_from_start: | |
3120 | l = pat.sub('',l) |
|
3120 | l = pat.sub('',l) | |
3121 | lines.append(l) |
|
3121 | lines.append(l) | |
3122 |
|
3122 | |||
3123 | block = "\n".join(lines) + '\n' |
|
3123 | block = "\n".join(lines) + '\n' | |
3124 | #print "block:\n",block |
|
3124 | #print "block:\n",block | |
3125 | return block |
|
3125 | return block | |
3126 |
|
3126 | |||
3127 | def _execute_block(self, block, par): |
|
3127 | def _execute_block(self, block, par): | |
3128 | """ Execute a block, or store it in a variable, per the user's request. |
|
3128 | """ Execute a block, or store it in a variable, per the user's request. | |
3129 | """ |
|
3129 | """ | |
3130 | if not par: |
|
3130 | if not par: | |
3131 | b = textwrap.dedent(block) |
|
3131 | b = textwrap.dedent(block) | |
3132 | self.user_ns['pasted_block'] = b |
|
3132 | self.user_ns['pasted_block'] = b | |
3133 | exec b in self.user_ns |
|
3133 | exec b in self.user_ns | |
3134 | else: |
|
3134 | else: | |
3135 | self.user_ns[par] = SList(block.splitlines()) |
|
3135 | self.user_ns[par] = SList(block.splitlines()) | |
3136 | print "Block assigned to '%s'" % par |
|
3136 | print "Block assigned to '%s'" % par | |
3137 |
|
3137 | |||
3138 | def magic_quickref(self,arg): |
|
3138 | def magic_quickref(self,arg): | |
3139 | """ Show a quick reference sheet """ |
|
3139 | """ Show a quick reference sheet """ | |
3140 | import IPython.core.usage |
|
3140 | import IPython.core.usage | |
3141 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') |
|
3141 | qr = IPython.core.usage.quick_reference + self.magic_magic('-brief') | |
3142 |
|
3142 | |||
3143 | page.page(qr) |
|
3143 | page.page(qr) | |
3144 |
|
3144 | |||
3145 | def magic_doctest_mode(self,parameter_s=''): |
|
3145 | def magic_doctest_mode(self,parameter_s=''): | |
3146 | """Toggle doctest mode on and off. |
|
3146 | """Toggle doctest mode on and off. | |
3147 |
|
3147 | |||
3148 | This mode is intended to make IPython behave as much as possible like a |
|
3148 | This mode is intended to make IPython behave as much as possible like a | |
3149 | plain Python shell, from the perspective of how its prompts, exceptions |
|
3149 | plain Python shell, from the perspective of how its prompts, exceptions | |
3150 | and output look. This makes it easy to copy and paste parts of a |
|
3150 | and output look. This makes it easy to copy and paste parts of a | |
3151 | session into doctests. It does so by: |
|
3151 | session into doctests. It does so by: | |
3152 |
|
3152 | |||
3153 | - Changing the prompts to the classic ``>>>`` ones. |
|
3153 | - Changing the prompts to the classic ``>>>`` ones. | |
3154 | - Changing the exception reporting mode to 'Plain'. |
|
3154 | - Changing the exception reporting mode to 'Plain'. | |
3155 | - Disabling pretty-printing of output. |
|
3155 | - Disabling pretty-printing of output. | |
3156 |
|
3156 | |||
3157 | Note that IPython also supports the pasting of code snippets that have |
|
3157 | Note that IPython also supports the pasting of code snippets that have | |
3158 | leading '>>>' and '...' prompts in them. This means that you can paste |
|
3158 | leading '>>>' and '...' prompts in them. This means that you can paste | |
3159 | doctests from files or docstrings (even if they have leading |
|
3159 | doctests from files or docstrings (even if they have leading | |
3160 | whitespace), and the code will execute correctly. You can then use |
|
3160 | whitespace), and the code will execute correctly. You can then use | |
3161 | '%history -t' to see the translated history; this will give you the |
|
3161 | '%history -t' to see the translated history; this will give you the | |
3162 | input after removal of all the leading prompts and whitespace, which |
|
3162 | input after removal of all the leading prompts and whitespace, which | |
3163 | can be pasted back into an editor. |
|
3163 | can be pasted back into an editor. | |
3164 |
|
3164 | |||
3165 | With these features, you can switch into this mode easily whenever you |
|
3165 | With these features, you can switch into this mode easily whenever you | |
3166 | need to do testing and changes to doctests, without having to leave |
|
3166 | need to do testing and changes to doctests, without having to leave | |
3167 | your existing IPython session. |
|
3167 | your existing IPython session. | |
3168 | """ |
|
3168 | """ | |
3169 |
|
3169 | |||
3170 | from IPython.utils.ipstruct import Struct |
|
3170 | from IPython.utils.ipstruct import Struct | |
3171 |
|
3171 | |||
3172 | # Shorthands |
|
3172 | # Shorthands | |
3173 | shell = self.shell |
|
3173 | shell = self.shell | |
3174 | oc = shell.displayhook |
|
3174 | oc = shell.displayhook | |
3175 | meta = shell.meta |
|
3175 | meta = shell.meta | |
3176 | # dstore is a data store kept in the instance metadata bag to track any |
|
3176 | # dstore is a data store kept in the instance metadata bag to track any | |
3177 | # changes we make, so we can undo them later. |
|
3177 | # changes we make, so we can undo them later. | |
3178 | dstore = meta.setdefault('doctest_mode',Struct()) |
|
3178 | dstore = meta.setdefault('doctest_mode',Struct()) | |
3179 | save_dstore = dstore.setdefault |
|
3179 | save_dstore = dstore.setdefault | |
3180 |
|
3180 | |||
3181 | # save a few values we'll need to recover later |
|
3181 | # save a few values we'll need to recover later | |
3182 | mode = save_dstore('mode',False) |
|
3182 | mode = save_dstore('mode',False) | |
3183 | save_dstore('rc_pprint',shell.pprint) |
|
3183 | save_dstore('rc_pprint',shell.pprint) | |
3184 | save_dstore('xmode',shell.InteractiveTB.mode) |
|
3184 | save_dstore('xmode',shell.InteractiveTB.mode) | |
3185 | save_dstore('rc_separate_out',shell.separate_out) |
|
3185 | save_dstore('rc_separate_out',shell.separate_out) | |
3186 | save_dstore('rc_separate_out2',shell.separate_out2) |
|
3186 | save_dstore('rc_separate_out2',shell.separate_out2) | |
3187 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) |
|
3187 | save_dstore('rc_prompts_pad_left',shell.prompts_pad_left) | |
3188 | save_dstore('rc_separate_in',shell.separate_in) |
|
3188 | save_dstore('rc_separate_in',shell.separate_in) | |
3189 |
|
3189 | |||
3190 | if mode == False: |
|
3190 | if mode == False: | |
3191 | # turn on |
|
3191 | # turn on | |
3192 | oc.prompt1.p_template = '>>> ' |
|
3192 | oc.prompt1.p_template = '>>> ' | |
3193 | oc.prompt2.p_template = '... ' |
|
3193 | oc.prompt2.p_template = '... ' | |
3194 | oc.prompt_out.p_template = '' |
|
3194 | oc.prompt_out.p_template = '' | |
3195 |
|
3195 | |||
3196 | # Prompt separators like plain python |
|
3196 | # Prompt separators like plain python | |
3197 | oc.input_sep = oc.prompt1.sep = '' |
|
3197 | oc.input_sep = oc.prompt1.sep = '' | |
3198 | oc.output_sep = '' |
|
3198 | oc.output_sep = '' | |
3199 | oc.output_sep2 = '' |
|
3199 | oc.output_sep2 = '' | |
3200 |
|
3200 | |||
3201 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3201 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3202 | oc.prompt_out.pad_left = False |
|
3202 | oc.prompt_out.pad_left = False | |
3203 |
|
3203 | |||
3204 | shell.pprint = False |
|
3204 | shell.pprint = False | |
3205 |
|
3205 | |||
3206 | shell.magic_xmode('Plain') |
|
3206 | shell.magic_xmode('Plain') | |
3207 | else: |
|
3207 | else: | |
3208 | # turn off |
|
3208 | # turn off | |
3209 | oc.prompt1.p_template = shell.prompt_in1 |
|
3209 | oc.prompt1.p_template = shell.prompt_in1 | |
3210 | oc.prompt2.p_template = shell.prompt_in2 |
|
3210 | oc.prompt2.p_template = shell.prompt_in2 | |
3211 | oc.prompt_out.p_template = shell.prompt_out |
|
3211 | oc.prompt_out.p_template = shell.prompt_out | |
3212 |
|
3212 | |||
3213 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in |
|
3213 | oc.input_sep = oc.prompt1.sep = dstore.rc_separate_in | |
3214 |
|
3214 | |||
3215 | oc.output_sep = dstore.rc_separate_out |
|
3215 | oc.output_sep = dstore.rc_separate_out | |
3216 | oc.output_sep2 = dstore.rc_separate_out2 |
|
3216 | oc.output_sep2 = dstore.rc_separate_out2 | |
3217 |
|
3217 | |||
3218 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ |
|
3218 | oc.prompt1.pad_left = oc.prompt2.pad_left = \ | |
3219 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left |
|
3219 | oc.prompt_out.pad_left = dstore.rc_prompts_pad_left | |
3220 |
|
3220 | |||
3221 | shell.pprint = dstore.rc_pprint |
|
3221 | shell.pprint = dstore.rc_pprint | |
3222 |
|
3222 | |||
3223 | shell.magic_xmode(dstore.xmode) |
|
3223 | shell.magic_xmode(dstore.xmode) | |
3224 |
|
3224 | |||
3225 | # Store new mode and inform |
|
3225 | # Store new mode and inform | |
3226 | dstore.mode = bool(1-int(mode)) |
|
3226 | dstore.mode = bool(1-int(mode)) | |
3227 | mode_label = ['OFF','ON'][dstore.mode] |
|
3227 | mode_label = ['OFF','ON'][dstore.mode] | |
3228 | print 'Doctest mode is:', mode_label |
|
3228 | print 'Doctest mode is:', mode_label | |
3229 |
|
3229 | |||
3230 | def magic_gui(self, parameter_s=''): |
|
3230 | def magic_gui(self, parameter_s=''): | |
3231 | """Enable or disable IPython GUI event loop integration. |
|
3231 | """Enable or disable IPython GUI event loop integration. | |
3232 |
|
3232 | |||
3233 | %gui [GUINAME] |
|
3233 | %gui [GUINAME] | |
3234 |
|
3234 | |||
3235 | This magic replaces IPython's threaded shells that were activated |
|
3235 | This magic replaces IPython's threaded shells that were activated | |
3236 | using the (pylab/wthread/etc.) command line flags. GUI toolkits |
|
3236 | using the (pylab/wthread/etc.) command line flags. GUI toolkits | |
3237 | can now be enabled, disabled and swtiched at runtime and keyboard |
|
3237 | can now be enabled, disabled and swtiched at runtime and keyboard | |
3238 | interrupts should work without any problems. The following toolkits |
|
3238 | interrupts should work without any problems. The following toolkits | |
3239 | are supported: wxPython, PyQt4, PyGTK, and Tk:: |
|
3239 | are supported: wxPython, PyQt4, PyGTK, and Tk:: | |
3240 |
|
3240 | |||
3241 | %gui wx # enable wxPython event loop integration |
|
3241 | %gui wx # enable wxPython event loop integration | |
3242 | %gui qt4|qt # enable PyQt4 event loop integration |
|
3242 | %gui qt4|qt # enable PyQt4 event loop integration | |
3243 | %gui gtk # enable PyGTK event loop integration |
|
3243 | %gui gtk # enable PyGTK event loop integration | |
3244 | %gui tk # enable Tk event loop integration |
|
3244 | %gui tk # enable Tk event loop integration | |
3245 | %gui # disable all event loop integration |
|
3245 | %gui # disable all event loop integration | |
3246 |
|
3246 | |||
3247 | WARNING: after any of these has been called you can simply create |
|
3247 | WARNING: after any of these has been called you can simply create | |
3248 | an application object, but DO NOT start the event loop yourself, as |
|
3248 | an application object, but DO NOT start the event loop yourself, as | |
3249 | we have already handled that. |
|
3249 | we have already handled that. | |
3250 | """ |
|
3250 | """ | |
3251 | from IPython.lib.inputhook import enable_gui |
|
3251 | from IPython.lib.inputhook import enable_gui | |
3252 | opts, arg = self.parse_options(parameter_s='') |
|
3252 | opts, arg = self.parse_options(parameter_s='') | |
3253 | if arg=='': arg = None |
|
3253 | if arg=='': arg = None | |
3254 | return enable_gui(arg) |
|
3254 | return enable_gui(arg) | |
3255 |
|
3255 | |||
3256 | def magic_load_ext(self, module_str): |
|
3256 | def magic_load_ext(self, module_str): | |
3257 | """Load an IPython extension by its module name.""" |
|
3257 | """Load an IPython extension by its module name.""" | |
3258 | return self.extension_manager.load_extension(module_str) |
|
3258 | return self.extension_manager.load_extension(module_str) | |
3259 |
|
3259 | |||
3260 | def magic_unload_ext(self, module_str): |
|
3260 | def magic_unload_ext(self, module_str): | |
3261 | """Unload an IPython extension by its module name.""" |
|
3261 | """Unload an IPython extension by its module name.""" | |
3262 | self.extension_manager.unload_extension(module_str) |
|
3262 | self.extension_manager.unload_extension(module_str) | |
3263 |
|
3263 | |||
3264 | def magic_reload_ext(self, module_str): |
|
3264 | def magic_reload_ext(self, module_str): | |
3265 | """Reload an IPython extension by its module name.""" |
|
3265 | """Reload an IPython extension by its module name.""" | |
3266 | self.extension_manager.reload_extension(module_str) |
|
3266 | self.extension_manager.reload_extension(module_str) | |
3267 |
|
3267 | |||
3268 | @testdec.skip_doctest |
|
3268 | @testdec.skip_doctest | |
3269 | def magic_install_profiles(self, s): |
|
3269 | def magic_install_profiles(self, s): | |
3270 | """Install the default IPython profiles into the .ipython dir. |
|
3270 | """Install the default IPython profiles into the .ipython dir. | |
3271 |
|
3271 | |||
3272 | If the default profiles have already been installed, they will not |
|
3272 | If the default profiles have already been installed, they will not | |
3273 | be overwritten. You can force overwriting them by using the ``-o`` |
|
3273 | be overwritten. You can force overwriting them by using the ``-o`` | |
3274 | option:: |
|
3274 | option:: | |
3275 |
|
3275 | |||
3276 | In [1]: %install_profiles -o |
|
3276 | In [1]: %install_profiles -o | |
3277 | """ |
|
3277 | """ | |
3278 | if '-o' in s: |
|
3278 | if '-o' in s: | |
3279 | overwrite = True |
|
3279 | overwrite = True | |
3280 | else: |
|
3280 | else: | |
3281 | overwrite = False |
|
3281 | overwrite = False | |
3282 | from IPython.config import profile |
|
3282 | from IPython.config import profile | |
3283 | profile_dir = os.path.split(profile.__file__)[0] |
|
3283 | profile_dir = os.path.split(profile.__file__)[0] | |
3284 | ipython_dir = self.ipython_dir |
|
3284 | ipython_dir = self.ipython_dir | |
3285 | files = os.listdir(profile_dir) |
|
3285 | files = os.listdir(profile_dir) | |
3286 |
|
3286 | |||
3287 | to_install = [] |
|
3287 | to_install = [] | |
3288 | for f in files: |
|
3288 | for f in files: | |
3289 | if f.startswith('ipython_config'): |
|
3289 | if f.startswith('ipython_config'): | |
3290 | src = os.path.join(profile_dir, f) |
|
3290 | src = os.path.join(profile_dir, f) | |
3291 | dst = os.path.join(ipython_dir, f) |
|
3291 | dst = os.path.join(ipython_dir, f) | |
3292 | if (not os.path.isfile(dst)) or overwrite: |
|
3292 | if (not os.path.isfile(dst)) or overwrite: | |
3293 | to_install.append((f, src, dst)) |
|
3293 | to_install.append((f, src, dst)) | |
3294 | if len(to_install)>0: |
|
3294 | if len(to_install)>0: | |
3295 | print "Installing profiles to: ", ipython_dir |
|
3295 | print "Installing profiles to: ", ipython_dir | |
3296 | for (f, src, dst) in to_install: |
|
3296 | for (f, src, dst) in to_install: | |
3297 | shutil.copy(src, dst) |
|
3297 | shutil.copy(src, dst) | |
3298 | print " %s" % f |
|
3298 | print " %s" % f | |
3299 |
|
3299 | |||
3300 | def magic_install_default_config(self, s): |
|
3300 | def magic_install_default_config(self, s): | |
3301 | """Install IPython's default config file into the .ipython dir. |
|
3301 | """Install IPython's default config file into the .ipython dir. | |
3302 |
|
3302 | |||
3303 | If the default config file (:file:`ipython_config.py`) is already |
|
3303 | If the default config file (:file:`ipython_config.py`) is already | |
3304 | installed, it will not be overwritten. You can force overwriting |
|
3304 | installed, it will not be overwritten. You can force overwriting | |
3305 | by using the ``-o`` option:: |
|
3305 | by using the ``-o`` option:: | |
3306 |
|
3306 | |||
3307 | In [1]: %install_default_config |
|
3307 | In [1]: %install_default_config | |
3308 | """ |
|
3308 | """ | |
3309 | if '-o' in s: |
|
3309 | if '-o' in s: | |
3310 | overwrite = True |
|
3310 | overwrite = True | |
3311 | else: |
|
3311 | else: | |
3312 | overwrite = False |
|
3312 | overwrite = False | |
3313 | from IPython.config import default |
|
3313 | from IPython.config import default | |
3314 | config_dir = os.path.split(default.__file__)[0] |
|
3314 | config_dir = os.path.split(default.__file__)[0] | |
3315 | ipython_dir = self.ipython_dir |
|
3315 | ipython_dir = self.ipython_dir | |
3316 | default_config_file_name = 'ipython_config.py' |
|
3316 | default_config_file_name = 'ipython_config.py' | |
3317 | src = os.path.join(config_dir, default_config_file_name) |
|
3317 | src = os.path.join(config_dir, default_config_file_name) | |
3318 | dst = os.path.join(ipython_dir, default_config_file_name) |
|
3318 | dst = os.path.join(ipython_dir, default_config_file_name) | |
3319 | if (not os.path.isfile(dst)) or overwrite: |
|
3319 | if (not os.path.isfile(dst)) or overwrite: | |
3320 | shutil.copy(src, dst) |
|
3320 | shutil.copy(src, dst) | |
3321 | print "Installing default config file: %s" % dst |
|
3321 | print "Installing default config file: %s" % dst | |
3322 |
|
3322 | |||
3323 | # Pylab support: simple wrappers that activate pylab, load gui input |
|
3323 | # Pylab support: simple wrappers that activate pylab, load gui input | |
3324 | # handling and modify slightly %run |
|
3324 | # handling and modify slightly %run | |
3325 |
|
3325 | |||
3326 | @testdec.skip_doctest |
|
3326 | @testdec.skip_doctest | |
3327 | def _pylab_magic_run(self, parameter_s=''): |
|
3327 | def _pylab_magic_run(self, parameter_s=''): | |
3328 | Magic.magic_run(self, parameter_s, |
|
3328 | Magic.magic_run(self, parameter_s, | |
3329 | runner=mpl_runner(self.shell.safe_execfile)) |
|
3329 | runner=mpl_runner(self.shell.safe_execfile)) | |
3330 |
|
3330 | |||
3331 | _pylab_magic_run.__doc__ = magic_run.__doc__ |
|
3331 | _pylab_magic_run.__doc__ = magic_run.__doc__ | |
3332 |
|
3332 | |||
3333 | @testdec.skip_doctest |
|
3333 | @testdec.skip_doctest | |
3334 | def magic_pylab(self, s): |
|
3334 | def magic_pylab(self, s): | |
3335 | """Load numpy and matplotlib to work interactively. |
|
3335 | """Load numpy and matplotlib to work interactively. | |
3336 |
|
3336 | |||
3337 | %pylab [GUINAME] |
|
3337 | %pylab [GUINAME] | |
3338 |
|
3338 | |||
3339 | This function lets you activate pylab (matplotlib, numpy and |
|
3339 | This function lets you activate pylab (matplotlib, numpy and | |
3340 | interactive support) at any point during an IPython session. |
|
3340 | interactive support) at any point during an IPython session. | |
3341 |
|
3341 | |||
3342 | It will import at the top level numpy as np, pyplot as plt, matplotlib, |
|
3342 | It will import at the top level numpy as np, pyplot as plt, matplotlib, | |
3343 | pylab and mlab, as well as all names from numpy and pylab. |
|
3343 | pylab and mlab, as well as all names from numpy and pylab. | |
3344 |
|
3344 | |||
3345 | Parameters |
|
3345 | Parameters | |
3346 | ---------- |
|
3346 | ---------- | |
3347 | guiname : optional |
|
3347 | guiname : optional | |
3348 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or |
|
3348 | One of the valid arguments to the %gui magic ('qt', 'wx', 'gtk' or | |
3349 | 'tk'). If given, the corresponding Matplotlib backend is used, |
|
3349 | 'tk'). If given, the corresponding Matplotlib backend is used, | |
3350 | otherwise matplotlib's default (which you can override in your |
|
3350 | otherwise matplotlib's default (which you can override in your | |
3351 | matplotlib config file) is used. |
|
3351 | matplotlib config file) is used. | |
3352 |
|
3352 | |||
3353 | Examples |
|
3353 | Examples | |
3354 | -------- |
|
3354 | -------- | |
3355 | In this case, where the MPL default is TkAgg: |
|
3355 | In this case, where the MPL default is TkAgg: | |
3356 | In [2]: %pylab |
|
3356 | In [2]: %pylab | |
3357 |
|
3357 | |||
3358 | Welcome to pylab, a matplotlib-based Python environment. |
|
3358 | Welcome to pylab, a matplotlib-based Python environment. | |
3359 | Backend in use: TkAgg |
|
3359 | Backend in use: TkAgg | |
3360 | For more information, type 'help(pylab)'. |
|
3360 | For more information, type 'help(pylab)'. | |
3361 |
|
3361 | |||
3362 | But you can explicitly request a different backend: |
|
3362 | But you can explicitly request a different backend: | |
3363 | In [3]: %pylab qt |
|
3363 | In [3]: %pylab qt | |
3364 |
|
3364 | |||
3365 | Welcome to pylab, a matplotlib-based Python environment. |
|
3365 | Welcome to pylab, a matplotlib-based Python environment. | |
3366 | Backend in use: Qt4Agg |
|
3366 | Backend in use: Qt4Agg | |
3367 | For more information, type 'help(pylab)'. |
|
3367 | For more information, type 'help(pylab)'. | |
3368 | """ |
|
3368 | """ | |
3369 | self.shell.enable_pylab(s) |
|
3369 | self.shell.enable_pylab(s) | |
3370 |
|
3370 | |||
3371 | def magic_tb(self, s): |
|
3371 | def magic_tb(self, s): | |
3372 | """Print the last traceback with the currently active exception mode. |
|
3372 | """Print the last traceback with the currently active exception mode. | |
3373 |
|
3373 | |||
3374 | See %xmode for changing exception reporting modes.""" |
|
3374 | See %xmode for changing exception reporting modes.""" | |
3375 | self.shell.showtraceback() |
|
3375 | self.shell.showtraceback() | |
3376 |
|
3376 | |||
3377 | # end Magic |
|
3377 | # end Magic |
@@ -1,1014 +1,1014 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # encoding: utf-8 |
|
2 | # encoding: utf-8 | |
3 | """ |
|
3 | """ | |
4 | Prefiltering components. |
|
4 | Prefiltering components. | |
5 |
|
5 | |||
6 | Prefilters transform user input before it is exec'd by Python. These |
|
6 | Prefilters transform user input before it is exec'd by Python. These | |
7 | transforms are used to implement additional syntax such as !ls and %magic. |
|
7 | transforms are used to implement additional syntax such as !ls and %magic. | |
8 |
|
8 | |||
9 | Authors: |
|
9 | Authors: | |
10 |
|
10 | |||
11 | * Brian Granger |
|
11 | * Brian Granger | |
12 | * Fernando Perez |
|
12 | * Fernando Perez | |
13 | * Dan Milstein |
|
13 | * Dan Milstein | |
14 | * Ville Vainio |
|
14 | * Ville Vainio | |
15 | """ |
|
15 | """ | |
16 |
|
16 | |||
17 | #----------------------------------------------------------------------------- |
|
17 | #----------------------------------------------------------------------------- | |
18 | # Copyright (C) 2008-2009 The IPython Development Team |
|
18 | # Copyright (C) 2008-2009 The IPython Development Team | |
19 | # |
|
19 | # | |
20 | # Distributed under the terms of the BSD License. The full license is in |
|
20 | # Distributed under the terms of the BSD License. The full license is in | |
21 | # the file COPYING, distributed as part of this software. |
|
21 | # the file COPYING, distributed as part of this software. | |
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Imports |
|
25 | # Imports | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 | import __builtin__ |
|
28 | import __builtin__ | |
29 | import codeop |
|
29 | import codeop | |
30 | import re |
|
30 | import re | |
31 |
|
31 | |||
32 | from IPython.core.alias import AliasManager |
|
32 | from IPython.core.alias import AliasManager | |
33 | from IPython.core.autocall import IPyAutocall |
|
33 | from IPython.core.autocall import IPyAutocall | |
34 | from IPython.config.configurable import Configurable |
|
34 | from IPython.config.configurable import Configurable | |
35 | from IPython.core.splitinput import split_user_input |
|
35 | from IPython.core.splitinput import split_user_input | |
36 | from IPython.core import page |
|
36 | from IPython.core import page | |
37 |
|
37 | |||
38 | from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance |
|
38 | from IPython.utils.traitlets import List, Int, Any, Str, CBool, Bool, Instance | |
39 | import IPython.utils.io |
|
39 | import IPython.utils.io | |
40 | from IPython.utils.text import make_quoted_expr |
|
40 | from IPython.utils.text import make_quoted_expr | |
41 | from IPython.utils.autoattr import auto_attr |
|
41 | from IPython.utils.autoattr import auto_attr | |
42 |
|
42 | |||
43 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
44 | # Global utilities, errors and constants |
|
44 | # Global utilities, errors and constants | |
45 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
46 |
|
46 | |||
47 | # Warning, these cannot be changed unless various regular expressions |
|
47 | # Warning, these cannot be changed unless various regular expressions | |
48 | # are updated in a number of places. Not great, but at least we told you. |
|
48 | # are updated in a number of places. Not great, but at least we told you. | |
49 | ESC_SHELL = '!' |
|
49 | ESC_SHELL = '!' | |
50 | ESC_SH_CAP = '!!' |
|
50 | ESC_SH_CAP = '!!' | |
51 | ESC_HELP = '?' |
|
51 | ESC_HELP = '?' | |
52 | ESC_MAGIC = '%' |
|
52 | ESC_MAGIC = '%' | |
53 | ESC_QUOTE = ',' |
|
53 | ESC_QUOTE = ',' | |
54 | ESC_QUOTE2 = ';' |
|
54 | ESC_QUOTE2 = ';' | |
55 | ESC_PAREN = '/' |
|
55 | ESC_PAREN = '/' | |
56 |
|
56 | |||
57 |
|
57 | |||
58 | class PrefilterError(Exception): |
|
58 | class PrefilterError(Exception): | |
59 | pass |
|
59 | pass | |
60 |
|
60 | |||
61 |
|
61 | |||
62 | # RegExp to identify potential function names |
|
62 | # RegExp to identify potential function names | |
63 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') |
|
63 | re_fun_name = re.compile(r'[a-zA-Z_]([a-zA-Z0-9_.]*) *$') | |
64 |
|
64 | |||
65 | # RegExp to exclude strings with this start from autocalling. In |
|
65 | # RegExp to exclude strings with this start from autocalling. In | |
66 | # particular, all binary operators should be excluded, so that if foo is |
|
66 | # particular, all binary operators should be excluded, so that if foo is | |
67 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The |
|
67 | # callable, foo OP bar doesn't become foo(OP bar), which is invalid. The | |
68 | # characters '!=()' don't need to be checked for, as the checkPythonChars |
|
68 | # characters '!=()' don't need to be checked for, as the checkPythonChars | |
69 | # routine explicitely does so, to catch direct calls and rebindings of |
|
69 | # routine explicitely does so, to catch direct calls and rebindings of | |
70 | # existing names. |
|
70 | # existing names. | |
71 |
|
71 | |||
72 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise |
|
72 | # Warning: the '-' HAS TO BE AT THE END of the first group, otherwise | |
73 | # it affects the rest of the group in square brackets. |
|
73 | # it affects the rest of the group in square brackets. | |
74 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' |
|
74 | re_exclude_auto = re.compile(r'^[,&^\|\*/\+-]' | |
75 | r'|^is |^not |^in |^and |^or ') |
|
75 | r'|^is |^not |^in |^and |^or ') | |
76 |
|
76 | |||
77 | # try to catch also methods for stuff in lists/tuples/dicts: off |
|
77 | # try to catch also methods for stuff in lists/tuples/dicts: off | |
78 | # (experimental). For this to work, the line_split regexp would need |
|
78 | # (experimental). For this to work, the line_split regexp would need | |
79 | # to be modified so it wouldn't break things at '['. That line is |
|
79 | # to be modified so it wouldn't break things at '['. That line is | |
80 | # nasty enough that I shouldn't change it until I can test it _well_. |
|
80 | # nasty enough that I shouldn't change it until I can test it _well_. | |
81 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') |
|
81 | #self.re_fun_name = re.compile (r'[a-zA-Z_]([a-zA-Z0-9_.\[\]]*) ?$') | |
82 |
|
82 | |||
83 |
|
83 | |||
84 | # Handler Check Utilities |
|
84 | # Handler Check Utilities | |
85 | def is_shadowed(identifier, ip): |
|
85 | def is_shadowed(identifier, ip): | |
86 | """Is the given identifier defined in one of the namespaces which shadow |
|
86 | """Is the given identifier defined in one of the namespaces which shadow | |
87 | the alias and magic namespaces? Note that an identifier is different |
|
87 | the alias and magic namespaces? Note that an identifier is different | |
88 | than ifun, because it can not contain a '.' character.""" |
|
88 | than ifun, because it can not contain a '.' character.""" | |
89 | # This is much safer than calling ofind, which can change state |
|
89 | # This is much safer than calling ofind, which can change state | |
90 | return (identifier in ip.user_ns \ |
|
90 | return (identifier in ip.user_ns \ | |
91 | or identifier in ip.internal_ns \ |
|
91 | or identifier in ip.internal_ns \ | |
92 | or identifier in ip.ns_table['builtin']) |
|
92 | or identifier in ip.ns_table['builtin']) | |
93 |
|
93 | |||
94 |
|
94 | |||
95 | #----------------------------------------------------------------------------- |
|
95 | #----------------------------------------------------------------------------- | |
96 | # The LineInfo class used throughout |
|
96 | # The LineInfo class used throughout | |
97 | #----------------------------------------------------------------------------- |
|
97 | #----------------------------------------------------------------------------- | |
98 |
|
98 | |||
99 |
|
99 | |||
100 | class LineInfo(object): |
|
100 | class LineInfo(object): | |
101 | """A single line of input and associated info. |
|
101 | """A single line of input and associated info. | |
102 |
|
102 | |||
103 | Includes the following as properties: |
|
103 | Includes the following as properties: | |
104 |
|
104 | |||
105 | line |
|
105 | line | |
106 | The original, raw line |
|
106 | The original, raw line | |
107 |
|
107 | |||
108 | continue_prompt |
|
108 | continue_prompt | |
109 | Is this line a continuation in a sequence of multiline input? |
|
109 | Is this line a continuation in a sequence of multiline input? | |
110 |
|
110 | |||
111 | pre |
|
111 | pre | |
112 | The initial esc character or whitespace. |
|
112 | The initial esc character or whitespace. | |
113 |
|
113 | |||
114 | pre_char |
|
114 | pre_char | |
115 | The escape character(s) in pre or the empty string if there isn't one. |
|
115 | The escape character(s) in pre or the empty string if there isn't one. | |
116 | Note that '!!' is a possible value for pre_char. Otherwise it will |
|
116 | Note that '!!' is a possible value for pre_char. Otherwise it will | |
117 | always be a single character. |
|
117 | always be a single character. | |
118 |
|
118 | |||
119 | pre_whitespace |
|
119 | pre_whitespace | |
120 | The leading whitespace from pre if it exists. If there is a pre_char, |
|
120 | The leading whitespace from pre if it exists. If there is a pre_char, | |
121 | this is just ''. |
|
121 | this is just ''. | |
122 |
|
122 | |||
123 | ifun |
|
123 | ifun | |
124 | The 'function part', which is basically the maximal initial sequence |
|
124 | The 'function part', which is basically the maximal initial sequence | |
125 | of valid python identifiers and the '.' character. This is what is |
|
125 | of valid python identifiers and the '.' character. This is what is | |
126 | checked for alias and magic transformations, used for auto-calling, |
|
126 | checked for alias and magic transformations, used for auto-calling, | |
127 | etc. |
|
127 | etc. | |
128 |
|
128 | |||
129 | the_rest |
|
129 | the_rest | |
130 | Everything else on the line. |
|
130 | Everything else on the line. | |
131 | """ |
|
131 | """ | |
132 | def __init__(self, line, continue_prompt): |
|
132 | def __init__(self, line, continue_prompt): | |
133 | self.line = line |
|
133 | self.line = line | |
134 | self.continue_prompt = continue_prompt |
|
134 | self.continue_prompt = continue_prompt | |
135 | self.pre, self.ifun, self.the_rest = split_user_input(line) |
|
135 | self.pre, self.ifun, self.the_rest = split_user_input(line) | |
136 |
|
136 | |||
137 | self.pre_char = self.pre.strip() |
|
137 | self.pre_char = self.pre.strip() | |
138 | if self.pre_char: |
|
138 | if self.pre_char: | |
139 | self.pre_whitespace = '' # No whitespace allowd before esc chars |
|
139 | self.pre_whitespace = '' # No whitespace allowd before esc chars | |
140 | else: |
|
140 | else: | |
141 | self.pre_whitespace = self.pre |
|
141 | self.pre_whitespace = self.pre | |
142 |
|
142 | |||
143 | self._oinfo = None |
|
143 | self._oinfo = None | |
144 |
|
144 | |||
145 | def ofind(self, ip): |
|
145 | def ofind(self, ip): | |
146 | """Do a full, attribute-walking lookup of the ifun in the various |
|
146 | """Do a full, attribute-walking lookup of the ifun in the various | |
147 | namespaces for the given IPython InteractiveShell instance. |
|
147 | namespaces for the given IPython InteractiveShell instance. | |
148 |
|
148 | |||
149 | Return a dict with keys: found,obj,ospace,ismagic |
|
149 | Return a dict with keys: found,obj,ospace,ismagic | |
150 |
|
150 | |||
151 | Note: can cause state changes because of calling getattr, but should |
|
151 | Note: can cause state changes because of calling getattr, but should | |
152 | only be run if autocall is on and if the line hasn't matched any |
|
152 | only be run if autocall is on and if the line hasn't matched any | |
153 | other, less dangerous handlers. |
|
153 | other, less dangerous handlers. | |
154 |
|
154 | |||
155 | Does cache the results of the call, so can be called multiple times |
|
155 | Does cache the results of the call, so can be called multiple times | |
156 | without worrying about *further* damaging state. |
|
156 | without worrying about *further* damaging state. | |
157 | """ |
|
157 | """ | |
158 | if not self._oinfo: |
|
158 | if not self._oinfo: | |
159 | # ip.shell._ofind is actually on the Magic class! |
|
159 | # ip.shell._ofind is actually on the Magic class! | |
160 | self._oinfo = ip.shell._ofind(self.ifun) |
|
160 | self._oinfo = ip.shell._ofind(self.ifun) | |
161 | return self._oinfo |
|
161 | return self._oinfo | |
162 |
|
162 | |||
163 | def __str__(self): |
|
163 | def __str__(self): | |
164 | return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest) |
|
164 | return "Lineinfo [%s|%s|%s]" %(self.pre, self.ifun, self.the_rest) | |
165 |
|
165 | |||
166 |
|
166 | |||
167 | #----------------------------------------------------------------------------- |
|
167 | #----------------------------------------------------------------------------- | |
168 | # Main Prefilter manager |
|
168 | # Main Prefilter manager | |
169 | #----------------------------------------------------------------------------- |
|
169 | #----------------------------------------------------------------------------- | |
170 |
|
170 | |||
171 |
|
171 | |||
172 | class PrefilterManager(Configurable): |
|
172 | class PrefilterManager(Configurable): | |
173 | """Main prefilter component. |
|
173 | """Main prefilter component. | |
174 |
|
174 | |||
175 | The IPython prefilter is run on all user input before it is run. The |
|
175 | The IPython prefilter is run on all user input before it is run. The | |
176 | prefilter consumes lines of input and produces transformed lines of |
|
176 | prefilter consumes lines of input and produces transformed lines of | |
177 | input. |
|
177 | input. | |
178 |
|
178 | |||
179 | The iplementation consists of two phases: |
|
179 | The iplementation consists of two phases: | |
180 |
|
180 | |||
181 | 1. Transformers |
|
181 | 1. Transformers | |
182 | 2. Checkers and handlers |
|
182 | 2. Checkers and handlers | |
183 |
|
183 | |||
184 | Over time, we plan on deprecating the checkers and handlers and doing |
|
184 | Over time, we plan on deprecating the checkers and handlers and doing | |
185 | everything in the transformers. |
|
185 | everything in the transformers. | |
186 |
|
186 | |||
187 | The transformers are instances of :class:`PrefilterTransformer` and have |
|
187 | The transformers are instances of :class:`PrefilterTransformer` and have | |
188 | a single method :meth:`transform` that takes a line and returns a |
|
188 | a single method :meth:`transform` that takes a line and returns a | |
189 | transformed line. The transformation can be accomplished using any |
|
189 | transformed line. The transformation can be accomplished using any | |
190 | tool, but our current ones use regular expressions for speed. We also |
|
190 | tool, but our current ones use regular expressions for speed. We also | |
191 | ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers. |
|
191 | ship :mod:`pyparsing` in :mod:`IPython.external` for use in transformers. | |
192 |
|
192 | |||
193 | After all the transformers have been run, the line is fed to the checkers, |
|
193 | After all the transformers have been run, the line is fed to the checkers, | |
194 | which are instances of :class:`PrefilterChecker`. The line is passed to |
|
194 | which are instances of :class:`PrefilterChecker`. The line is passed to | |
195 | the :meth:`check` method, which either returns `None` or a |
|
195 | the :meth:`check` method, which either returns `None` or a | |
196 | :class:`PrefilterHandler` instance. If `None` is returned, the other |
|
196 | :class:`PrefilterHandler` instance. If `None` is returned, the other | |
197 | checkers are tried. If an :class:`PrefilterHandler` instance is returned, |
|
197 | checkers are tried. If an :class:`PrefilterHandler` instance is returned, | |
198 | the line is passed to the :meth:`handle` method of the returned |
|
198 | the line is passed to the :meth:`handle` method of the returned | |
199 | handler and no further checkers are tried. |
|
199 | handler and no further checkers are tried. | |
200 |
|
200 | |||
201 | Both transformers and checkers have a `priority` attribute, that determines |
|
201 | Both transformers and checkers have a `priority` attribute, that determines | |
202 | the order in which they are called. Smaller priorities are tried first. |
|
202 | the order in which they are called. Smaller priorities are tried first. | |
203 |
|
203 | |||
204 | Both transformers and checkers also have `enabled` attribute, which is |
|
204 | Both transformers and checkers also have `enabled` attribute, which is | |
205 | a boolean that determines if the instance is used. |
|
205 | a boolean that determines if the instance is used. | |
206 |
|
206 | |||
207 | Users or developers can change the priority or enabled attribute of |
|
207 | Users or developers can change the priority or enabled attribute of | |
208 | transformers or checkers, but they must call the :meth:`sort_checkers` |
|
208 | transformers or checkers, but they must call the :meth:`sort_checkers` | |
209 | or :meth:`sort_transformers` method after changing the priority. |
|
209 | or :meth:`sort_transformers` method after changing the priority. | |
210 | """ |
|
210 | """ | |
211 |
|
211 | |||
212 | multi_line_specials = CBool(True, config=True) |
|
212 | multi_line_specials = CBool(True, config=True) | |
213 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
213 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
214 |
|
214 | |||
215 | def __init__(self, shell=None, config=None): |
|
215 | def __init__(self, shell=None, config=None): | |
216 | super(PrefilterManager, self).__init__(shell=shell, config=config) |
|
216 | super(PrefilterManager, self).__init__(shell=shell, config=config) | |
217 | self.shell = shell |
|
217 | self.shell = shell | |
218 | self.init_transformers() |
|
218 | self.init_transformers() | |
219 | self.init_handlers() |
|
219 | self.init_handlers() | |
220 | self.init_checkers() |
|
220 | self.init_checkers() | |
221 |
|
221 | |||
222 | #------------------------------------------------------------------------- |
|
222 | #------------------------------------------------------------------------- | |
223 | # API for managing transformers |
|
223 | # API for managing transformers | |
224 | #------------------------------------------------------------------------- |
|
224 | #------------------------------------------------------------------------- | |
225 |
|
225 | |||
226 | def init_transformers(self): |
|
226 | def init_transformers(self): | |
227 | """Create the default transformers.""" |
|
227 | """Create the default transformers.""" | |
228 | self._transformers = [] |
|
228 | self._transformers = [] | |
229 | for transformer_cls in _default_transformers: |
|
229 | for transformer_cls in _default_transformers: | |
230 | transformer_cls( |
|
230 | transformer_cls( | |
231 | shell=self.shell, prefilter_manager=self, config=self.config |
|
231 | shell=self.shell, prefilter_manager=self, config=self.config | |
232 | ) |
|
232 | ) | |
233 |
|
233 | |||
234 | def sort_transformers(self): |
|
234 | def sort_transformers(self): | |
235 | """Sort the transformers by priority. |
|
235 | """Sort the transformers by priority. | |
236 |
|
236 | |||
237 | This must be called after the priority of a transformer is changed. |
|
237 | This must be called after the priority of a transformer is changed. | |
238 | The :meth:`register_transformer` method calls this automatically. |
|
238 | The :meth:`register_transformer` method calls this automatically. | |
239 | """ |
|
239 | """ | |
240 | self._transformers.sort(cmp=lambda x,y: x.priority-y.priority) |
|
240 | self._transformers.sort(cmp=lambda x,y: x.priority-y.priority) | |
241 |
|
241 | |||
242 | @property |
|
242 | @property | |
243 | def transformers(self): |
|
243 | def transformers(self): | |
244 | """Return a list of checkers, sorted by priority.""" |
|
244 | """Return a list of checkers, sorted by priority.""" | |
245 | return self._transformers |
|
245 | return self._transformers | |
246 |
|
246 | |||
247 | def register_transformer(self, transformer): |
|
247 | def register_transformer(self, transformer): | |
248 | """Register a transformer instance.""" |
|
248 | """Register a transformer instance.""" | |
249 | if transformer not in self._transformers: |
|
249 | if transformer not in self._transformers: | |
250 | self._transformers.append(transformer) |
|
250 | self._transformers.append(transformer) | |
251 | self.sort_transformers() |
|
251 | self.sort_transformers() | |
252 |
|
252 | |||
253 | def unregister_transformer(self, transformer): |
|
253 | def unregister_transformer(self, transformer): | |
254 | """Unregister a transformer instance.""" |
|
254 | """Unregister a transformer instance.""" | |
255 | if transformer in self._transformers: |
|
255 | if transformer in self._transformers: | |
256 | self._transformers.remove(transformer) |
|
256 | self._transformers.remove(transformer) | |
257 |
|
257 | |||
258 | #------------------------------------------------------------------------- |
|
258 | #------------------------------------------------------------------------- | |
259 | # API for managing checkers |
|
259 | # API for managing checkers | |
260 | #------------------------------------------------------------------------- |
|
260 | #------------------------------------------------------------------------- | |
261 |
|
261 | |||
262 | def init_checkers(self): |
|
262 | def init_checkers(self): | |
263 | """Create the default checkers.""" |
|
263 | """Create the default checkers.""" | |
264 | self._checkers = [] |
|
264 | self._checkers = [] | |
265 | for checker in _default_checkers: |
|
265 | for checker in _default_checkers: | |
266 | checker( |
|
266 | checker( | |
267 | shell=self.shell, prefilter_manager=self, config=self.config |
|
267 | shell=self.shell, prefilter_manager=self, config=self.config | |
268 | ) |
|
268 | ) | |
269 |
|
269 | |||
270 | def sort_checkers(self): |
|
270 | def sort_checkers(self): | |
271 | """Sort the checkers by priority. |
|
271 | """Sort the checkers by priority. | |
272 |
|
272 | |||
273 | This must be called after the priority of a checker is changed. |
|
273 | This must be called after the priority of a checker is changed. | |
274 | The :meth:`register_checker` method calls this automatically. |
|
274 | The :meth:`register_checker` method calls this automatically. | |
275 | """ |
|
275 | """ | |
276 | self._checkers.sort(cmp=lambda x,y: x.priority-y.priority) |
|
276 | self._checkers.sort(cmp=lambda x,y: x.priority-y.priority) | |
277 |
|
277 | |||
278 | @property |
|
278 | @property | |
279 | def checkers(self): |
|
279 | def checkers(self): | |
280 | """Return a list of checkers, sorted by priority.""" |
|
280 | """Return a list of checkers, sorted by priority.""" | |
281 | return self._checkers |
|
281 | return self._checkers | |
282 |
|
282 | |||
283 | def register_checker(self, checker): |
|
283 | def register_checker(self, checker): | |
284 | """Register a checker instance.""" |
|
284 | """Register a checker instance.""" | |
285 | if checker not in self._checkers: |
|
285 | if checker not in self._checkers: | |
286 | self._checkers.append(checker) |
|
286 | self._checkers.append(checker) | |
287 | self.sort_checkers() |
|
287 | self.sort_checkers() | |
288 |
|
288 | |||
289 | def unregister_checker(self, checker): |
|
289 | def unregister_checker(self, checker): | |
290 | """Unregister a checker instance.""" |
|
290 | """Unregister a checker instance.""" | |
291 | if checker in self._checkers: |
|
291 | if checker in self._checkers: | |
292 | self._checkers.remove(checker) |
|
292 | self._checkers.remove(checker) | |
293 |
|
293 | |||
294 | #------------------------------------------------------------------------- |
|
294 | #------------------------------------------------------------------------- | |
295 | # API for managing checkers |
|
295 | # API for managing checkers | |
296 | #------------------------------------------------------------------------- |
|
296 | #------------------------------------------------------------------------- | |
297 |
|
297 | |||
298 | def init_handlers(self): |
|
298 | def init_handlers(self): | |
299 | """Create the default handlers.""" |
|
299 | """Create the default handlers.""" | |
300 | self._handlers = {} |
|
300 | self._handlers = {} | |
301 | self._esc_handlers = {} |
|
301 | self._esc_handlers = {} | |
302 | for handler in _default_handlers: |
|
302 | for handler in _default_handlers: | |
303 | handler( |
|
303 | handler( | |
304 | shell=self.shell, prefilter_manager=self, config=self.config |
|
304 | shell=self.shell, prefilter_manager=self, config=self.config | |
305 | ) |
|
305 | ) | |
306 |
|
306 | |||
307 | @property |
|
307 | @property | |
308 | def handlers(self): |
|
308 | def handlers(self): | |
309 | """Return a dict of all the handlers.""" |
|
309 | """Return a dict of all the handlers.""" | |
310 | return self._handlers |
|
310 | return self._handlers | |
311 |
|
311 | |||
312 | def register_handler(self, name, handler, esc_strings): |
|
312 | def register_handler(self, name, handler, esc_strings): | |
313 | """Register a handler instance by name with esc_strings.""" |
|
313 | """Register a handler instance by name with esc_strings.""" | |
314 | self._handlers[name] = handler |
|
314 | self._handlers[name] = handler | |
315 | for esc_str in esc_strings: |
|
315 | for esc_str in esc_strings: | |
316 | self._esc_handlers[esc_str] = handler |
|
316 | self._esc_handlers[esc_str] = handler | |
317 |
|
317 | |||
318 | def unregister_handler(self, name, handler, esc_strings): |
|
318 | def unregister_handler(self, name, handler, esc_strings): | |
319 | """Unregister a handler instance by name with esc_strings.""" |
|
319 | """Unregister a handler instance by name with esc_strings.""" | |
320 | try: |
|
320 | try: | |
321 | del self._handlers[name] |
|
321 | del self._handlers[name] | |
322 | except KeyError: |
|
322 | except KeyError: | |
323 | pass |
|
323 | pass | |
324 | for esc_str in esc_strings: |
|
324 | for esc_str in esc_strings: | |
325 | h = self._esc_handlers.get(esc_str) |
|
325 | h = self._esc_handlers.get(esc_str) | |
326 | if h is handler: |
|
326 | if h is handler: | |
327 | del self._esc_handlers[esc_str] |
|
327 | del self._esc_handlers[esc_str] | |
328 |
|
328 | |||
329 | def get_handler_by_name(self, name): |
|
329 | def get_handler_by_name(self, name): | |
330 | """Get a handler by its name.""" |
|
330 | """Get a handler by its name.""" | |
331 | return self._handlers.get(name) |
|
331 | return self._handlers.get(name) | |
332 |
|
332 | |||
333 | def get_handler_by_esc(self, esc_str): |
|
333 | def get_handler_by_esc(self, esc_str): | |
334 | """Get a handler by its escape string.""" |
|
334 | """Get a handler by its escape string.""" | |
335 | return self._esc_handlers.get(esc_str) |
|
335 | return self._esc_handlers.get(esc_str) | |
336 |
|
336 | |||
337 | #------------------------------------------------------------------------- |
|
337 | #------------------------------------------------------------------------- | |
338 | # Main prefiltering API |
|
338 | # Main prefiltering API | |
339 | #------------------------------------------------------------------------- |
|
339 | #------------------------------------------------------------------------- | |
340 |
|
340 | |||
341 | def prefilter_line_info(self, line_info): |
|
341 | def prefilter_line_info(self, line_info): | |
342 | """Prefilter a line that has been converted to a LineInfo object. |
|
342 | """Prefilter a line that has been converted to a LineInfo object. | |
343 |
|
343 | |||
344 | This implements the checker/handler part of the prefilter pipe. |
|
344 | This implements the checker/handler part of the prefilter pipe. | |
345 | """ |
|
345 | """ | |
346 | # print "prefilter_line_info: ", line_info |
|
346 | # print "prefilter_line_info: ", line_info | |
347 | handler = self.find_handler(line_info) |
|
347 | handler = self.find_handler(line_info) | |
348 | return handler.handle(line_info) |
|
348 | return handler.handle(line_info) | |
349 |
|
349 | |||
350 | def find_handler(self, line_info): |
|
350 | def find_handler(self, line_info): | |
351 | """Find a handler for the line_info by trying checkers.""" |
|
351 | """Find a handler for the line_info by trying checkers.""" | |
352 | for checker in self.checkers: |
|
352 | for checker in self.checkers: | |
353 | if checker.enabled: |
|
353 | if checker.enabled: | |
354 | handler = checker.check(line_info) |
|
354 | handler = checker.check(line_info) | |
355 | if handler: |
|
355 | if handler: | |
356 | return handler |
|
356 | return handler | |
357 | return self.get_handler_by_name('normal') |
|
357 | return self.get_handler_by_name('normal') | |
358 |
|
358 | |||
359 | def transform_line(self, line, continue_prompt): |
|
359 | def transform_line(self, line, continue_prompt): | |
360 | """Calls the enabled transformers in order of increasing priority.""" |
|
360 | """Calls the enabled transformers in order of increasing priority.""" | |
361 | for transformer in self.transformers: |
|
361 | for transformer in self.transformers: | |
362 | if transformer.enabled: |
|
362 | if transformer.enabled: | |
363 | line = transformer.transform(line, continue_prompt) |
|
363 | line = transformer.transform(line, continue_prompt) | |
364 | return line |
|
364 | return line | |
365 |
|
365 | |||
366 | def prefilter_line(self, line, continue_prompt=False): |
|
366 | def prefilter_line(self, line, continue_prompt=False): | |
367 | """Prefilter a single input line as text. |
|
367 | """Prefilter a single input line as text. | |
368 |
|
368 | |||
369 | This method prefilters a single line of text by calling the |
|
369 | This method prefilters a single line of text by calling the | |
370 | transformers and then the checkers/handlers. |
|
370 | transformers and then the checkers/handlers. | |
371 | """ |
|
371 | """ | |
372 |
|
372 | |||
373 | # print "prefilter_line: ", line, continue_prompt |
|
373 | # print "prefilter_line: ", line, continue_prompt | |
374 | # All handlers *must* return a value, even if it's blank (''). |
|
374 | # All handlers *must* return a value, even if it's blank (''). | |
375 |
|
375 | |||
376 | # Lines are NOT logged here. Handlers should process the line as |
|
376 | # Lines are NOT logged here. Handlers should process the line as | |
377 | # needed, update the cache AND log it (so that the input cache array |
|
377 | # needed, update the cache AND log it (so that the input cache array | |
378 | # stays synced). |
|
378 | # stays synced). | |
379 |
|
379 | |||
380 | # save the line away in case we crash, so the post-mortem handler can |
|
380 | # save the line away in case we crash, so the post-mortem handler can | |
381 | # record it |
|
381 | # record it | |
382 | self.shell._last_input_line = line |
|
382 | self.shell._last_input_line = line | |
383 |
|
383 | |||
384 | if not line: |
|
384 | if not line: | |
385 | # Return immediately on purely empty lines, so that if the user |
|
385 | # Return immediately on purely empty lines, so that if the user | |
386 | # previously typed some whitespace that started a continuation |
|
386 | # previously typed some whitespace that started a continuation | |
387 | # prompt, he can break out of that loop with just an empty line. |
|
387 | # prompt, he can break out of that loop with just an empty line. | |
388 | # This is how the default python prompt works. |
|
388 | # This is how the default python prompt works. | |
389 |
|
389 | |||
390 | # Only return if the accumulated input buffer was just whitespace! |
|
390 | # Only return if the accumulated input buffer was just whitespace! | |
391 | if ''.join(self.shell.buffer).isspace(): |
|
391 | if ''.join(self.shell.buffer).isspace(): | |
392 | self.shell.buffer[:] = [] |
|
392 | self.shell.buffer[:] = [] | |
393 | return '' |
|
393 | return '' | |
394 |
|
394 | |||
395 | # At this point, we invoke our transformers. |
|
395 | # At this point, we invoke our transformers. | |
396 | if not continue_prompt or (continue_prompt and self.multi_line_specials): |
|
396 | if not continue_prompt or (continue_prompt and self.multi_line_specials): | |
397 | line = self.transform_line(line, continue_prompt) |
|
397 | line = self.transform_line(line, continue_prompt) | |
398 |
|
398 | |||
399 | # Now we compute line_info for the checkers and handlers |
|
399 | # Now we compute line_info for the checkers and handlers | |
400 | line_info = LineInfo(line, continue_prompt) |
|
400 | line_info = LineInfo(line, continue_prompt) | |
401 |
|
401 | |||
402 | # the input history needs to track even empty lines |
|
402 | # the input history needs to track even empty lines | |
403 | stripped = line.strip() |
|
403 | stripped = line.strip() | |
404 |
|
404 | |||
405 | normal_handler = self.get_handler_by_name('normal') |
|
405 | normal_handler = self.get_handler_by_name('normal') | |
406 | if not stripped: |
|
406 | if not stripped: | |
407 | if not continue_prompt: |
|
407 | if not continue_prompt: | |
408 | self.shell.displayhook.prompt_count -= 1 |
|
408 | self.shell.displayhook.prompt_count -= 1 | |
409 |
|
409 | |||
410 | return normal_handler.handle(line_info) |
|
410 | return normal_handler.handle(line_info) | |
411 |
|
411 | |||
412 | # special handlers are only allowed for single line statements |
|
412 | # special handlers are only allowed for single line statements | |
413 | if continue_prompt and not self.multi_line_specials: |
|
413 | if continue_prompt and not self.multi_line_specials: | |
414 | return normal_handler.handle(line_info) |
|
414 | return normal_handler.handle(line_info) | |
415 |
|
415 | |||
416 | prefiltered = self.prefilter_line_info(line_info) |
|
416 | prefiltered = self.prefilter_line_info(line_info) | |
417 | # print "prefiltered line: %r" % prefiltered |
|
417 | # print "prefiltered line: %r" % prefiltered | |
418 | return prefiltered |
|
418 | return prefiltered | |
419 |
|
419 | |||
420 | def prefilter_lines(self, lines, continue_prompt=False): |
|
420 | def prefilter_lines(self, lines, continue_prompt=False): | |
421 | """Prefilter multiple input lines of text. |
|
421 | """Prefilter multiple input lines of text. | |
422 |
|
422 | |||
423 | This is the main entry point for prefiltering multiple lines of |
|
423 | This is the main entry point for prefiltering multiple lines of | |
424 | input. This simply calls :meth:`prefilter_line` for each line of |
|
424 | input. This simply calls :meth:`prefilter_line` for each line of | |
425 | input. |
|
425 | input. | |
426 |
|
426 | |||
427 | This covers cases where there are multiple lines in the user entry, |
|
427 | This covers cases where there are multiple lines in the user entry, | |
428 | which is the case when the user goes back to a multiline history |
|
428 | which is the case when the user goes back to a multiline history | |
429 | entry and presses enter. |
|
429 | entry and presses enter. | |
430 | """ |
|
430 | """ | |
431 | llines = lines.rstrip('\n').split('\n') |
|
431 | llines = lines.rstrip('\n').split('\n') | |
432 | # We can get multiple lines in one shot, where multiline input 'blends' |
|
432 | # We can get multiple lines in one shot, where multiline input 'blends' | |
433 | # into one line, in cases like recalling from the readline history |
|
433 | # into one line, in cases like recalling from the readline history | |
434 | # buffer. We need to make sure that in such cases, we correctly |
|
434 | # buffer. We need to make sure that in such cases, we correctly | |
435 | # communicate downstream which line is first and which are continuation |
|
435 | # communicate downstream which line is first and which are continuation | |
436 | # ones. |
|
436 | # ones. | |
437 | if len(llines) > 1: |
|
437 | if len(llines) > 1: | |
438 | out = '\n'.join([self.prefilter_line(line, lnum>0) |
|
438 | out = '\n'.join([self.prefilter_line(line, lnum>0) | |
439 | for lnum, line in enumerate(llines) ]) |
|
439 | for lnum, line in enumerate(llines) ]) | |
440 | else: |
|
440 | else: | |
441 | out = self.prefilter_line(llines[0], continue_prompt) |
|
441 | out = self.prefilter_line(llines[0], continue_prompt) | |
442 |
|
442 | |||
443 | return out |
|
443 | return out | |
444 |
|
444 | |||
445 | #----------------------------------------------------------------------------- |
|
445 | #----------------------------------------------------------------------------- | |
446 | # Prefilter transformers |
|
446 | # Prefilter transformers | |
447 | #----------------------------------------------------------------------------- |
|
447 | #----------------------------------------------------------------------------- | |
448 |
|
448 | |||
449 |
|
449 | |||
450 | class PrefilterTransformer(Configurable): |
|
450 | class PrefilterTransformer(Configurable): | |
451 | """Transform a line of user input.""" |
|
451 | """Transform a line of user input.""" | |
452 |
|
452 | |||
453 | priority = Int(100, config=True) |
|
453 | priority = Int(100, config=True) | |
454 | # Transformers don't currently use shell or prefilter_manager, but as we |
|
454 | # Transformers don't currently use shell or prefilter_manager, but as we | |
455 | # move away from checkers and handlers, they will need them. |
|
455 | # move away from checkers and handlers, they will need them. | |
456 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
456 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
457 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
457 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
458 | enabled = Bool(True, config=True) |
|
458 | enabled = Bool(True, config=True) | |
459 |
|
459 | |||
460 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
460 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
461 | super(PrefilterTransformer, self).__init__( |
|
461 | super(PrefilterTransformer, self).__init__( | |
462 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
462 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
463 | ) |
|
463 | ) | |
464 | self.prefilter_manager.register_transformer(self) |
|
464 | self.prefilter_manager.register_transformer(self) | |
465 |
|
465 | |||
466 | def transform(self, line, continue_prompt): |
|
466 | def transform(self, line, continue_prompt): | |
467 | """Transform a line, returning the new one.""" |
|
467 | """Transform a line, returning the new one.""" | |
468 | return None |
|
468 | return None | |
469 |
|
469 | |||
470 | def __repr__(self): |
|
470 | def __repr__(self): | |
471 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
471 | return "<%s(priority=%r, enabled=%r)>" % ( | |
472 | self.__class__.__name__, self.priority, self.enabled) |
|
472 | self.__class__.__name__, self.priority, self.enabled) | |
473 |
|
473 | |||
474 |
|
474 | |||
475 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
475 | _assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
476 | r'\s*=\s*!(?P<cmd>.*)') |
|
476 | r'\s*=\s*!(?P<cmd>.*)') | |
477 |
|
477 | |||
478 |
|
478 | |||
479 | class AssignSystemTransformer(PrefilterTransformer): |
|
479 | class AssignSystemTransformer(PrefilterTransformer): | |
480 | """Handle the `files = !ls` syntax.""" |
|
480 | """Handle the `files = !ls` syntax.""" | |
481 |
|
481 | |||
482 | priority = Int(100, config=True) |
|
482 | priority = Int(100, config=True) | |
483 |
|
483 | |||
484 | def transform(self, line, continue_prompt): |
|
484 | def transform(self, line, continue_prompt): | |
485 | m = _assign_system_re.match(line) |
|
485 | m = _assign_system_re.match(line) | |
486 | if m is not None: |
|
486 | if m is not None: | |
487 | cmd = m.group('cmd') |
|
487 | cmd = m.group('cmd') | |
488 | lhs = m.group('lhs') |
|
488 | lhs = m.group('lhs') | |
489 |
expr = make_quoted_expr("sc |
|
489 | expr = make_quoted_expr("sc =%s" % cmd) | |
490 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) |
|
490 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) | |
491 | return new_line |
|
491 | return new_line | |
492 | return line |
|
492 | return line | |
493 |
|
493 | |||
494 |
|
494 | |||
495 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' |
|
495 | _assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))' | |
496 | r'\s*=\s*%(?P<cmd>.*)') |
|
496 | r'\s*=\s*%(?P<cmd>.*)') | |
497 |
|
497 | |||
498 | class AssignMagicTransformer(PrefilterTransformer): |
|
498 | class AssignMagicTransformer(PrefilterTransformer): | |
499 | """Handle the `a = %who` syntax.""" |
|
499 | """Handle the `a = %who` syntax.""" | |
500 |
|
500 | |||
501 | priority = Int(200, config=True) |
|
501 | priority = Int(200, config=True) | |
502 |
|
502 | |||
503 | def transform(self, line, continue_prompt): |
|
503 | def transform(self, line, continue_prompt): | |
504 | m = _assign_magic_re.match(line) |
|
504 | m = _assign_magic_re.match(line) | |
505 | if m is not None: |
|
505 | if m is not None: | |
506 | cmd = m.group('cmd') |
|
506 | cmd = m.group('cmd') | |
507 | lhs = m.group('lhs') |
|
507 | lhs = m.group('lhs') | |
508 | expr = make_quoted_expr(cmd) |
|
508 | expr = make_quoted_expr(cmd) | |
509 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) |
|
509 | new_line = '%s = get_ipython().magic(%s)' % (lhs, expr) | |
510 | return new_line |
|
510 | return new_line | |
511 | return line |
|
511 | return line | |
512 |
|
512 | |||
513 |
|
513 | |||
514 | _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') |
|
514 | _classic_prompt_re = re.compile(r'(^[ \t]*>>> |^[ \t]*\.\.\. )') | |
515 |
|
515 | |||
516 | class PyPromptTransformer(PrefilterTransformer): |
|
516 | class PyPromptTransformer(PrefilterTransformer): | |
517 | """Handle inputs that start with '>>> ' syntax.""" |
|
517 | """Handle inputs that start with '>>> ' syntax.""" | |
518 |
|
518 | |||
519 | priority = Int(50, config=True) |
|
519 | priority = Int(50, config=True) | |
520 |
|
520 | |||
521 | def transform(self, line, continue_prompt): |
|
521 | def transform(self, line, continue_prompt): | |
522 |
|
522 | |||
523 | if not line or line.isspace() or line.strip() == '...': |
|
523 | if not line or line.isspace() or line.strip() == '...': | |
524 | # This allows us to recognize multiple input prompts separated by |
|
524 | # This allows us to recognize multiple input prompts separated by | |
525 | # blank lines and pasted in a single chunk, very common when |
|
525 | # blank lines and pasted in a single chunk, very common when | |
526 | # pasting doctests or long tutorial passages. |
|
526 | # pasting doctests or long tutorial passages. | |
527 | return '' |
|
527 | return '' | |
528 | m = _classic_prompt_re.match(line) |
|
528 | m = _classic_prompt_re.match(line) | |
529 | if m: |
|
529 | if m: | |
530 | return line[len(m.group(0)):] |
|
530 | return line[len(m.group(0)):] | |
531 | else: |
|
531 | else: | |
532 | return line |
|
532 | return line | |
533 |
|
533 | |||
534 |
|
534 | |||
535 | _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') |
|
535 | _ipy_prompt_re = re.compile(r'(^[ \t]*In \[\d+\]: |^[ \t]*\ \ \ \.\.\.+: )') | |
536 |
|
536 | |||
537 | class IPyPromptTransformer(PrefilterTransformer): |
|
537 | class IPyPromptTransformer(PrefilterTransformer): | |
538 | """Handle inputs that start classic IPython prompt syntax.""" |
|
538 | """Handle inputs that start classic IPython prompt syntax.""" | |
539 |
|
539 | |||
540 | priority = Int(50, config=True) |
|
540 | priority = Int(50, config=True) | |
541 |
|
541 | |||
542 | def transform(self, line, continue_prompt): |
|
542 | def transform(self, line, continue_prompt): | |
543 |
|
543 | |||
544 | if not line or line.isspace() or line.strip() == '...': |
|
544 | if not line or line.isspace() or line.strip() == '...': | |
545 | # This allows us to recognize multiple input prompts separated by |
|
545 | # This allows us to recognize multiple input prompts separated by | |
546 | # blank lines and pasted in a single chunk, very common when |
|
546 | # blank lines and pasted in a single chunk, very common when | |
547 | # pasting doctests or long tutorial passages. |
|
547 | # pasting doctests or long tutorial passages. | |
548 | return '' |
|
548 | return '' | |
549 | m = _ipy_prompt_re.match(line) |
|
549 | m = _ipy_prompt_re.match(line) | |
550 | if m: |
|
550 | if m: | |
551 | return line[len(m.group(0)):] |
|
551 | return line[len(m.group(0)):] | |
552 | else: |
|
552 | else: | |
553 | return line |
|
553 | return line | |
554 |
|
554 | |||
555 | #----------------------------------------------------------------------------- |
|
555 | #----------------------------------------------------------------------------- | |
556 | # Prefilter checkers |
|
556 | # Prefilter checkers | |
557 | #----------------------------------------------------------------------------- |
|
557 | #----------------------------------------------------------------------------- | |
558 |
|
558 | |||
559 |
|
559 | |||
560 | class PrefilterChecker(Configurable): |
|
560 | class PrefilterChecker(Configurable): | |
561 | """Inspect an input line and return a handler for that line.""" |
|
561 | """Inspect an input line and return a handler for that line.""" | |
562 |
|
562 | |||
563 | priority = Int(100, config=True) |
|
563 | priority = Int(100, config=True) | |
564 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
564 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
565 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
565 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
566 | enabled = Bool(True, config=True) |
|
566 | enabled = Bool(True, config=True) | |
567 |
|
567 | |||
568 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
568 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
569 | super(PrefilterChecker, self).__init__( |
|
569 | super(PrefilterChecker, self).__init__( | |
570 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
570 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
571 | ) |
|
571 | ) | |
572 | self.prefilter_manager.register_checker(self) |
|
572 | self.prefilter_manager.register_checker(self) | |
573 |
|
573 | |||
574 | def check(self, line_info): |
|
574 | def check(self, line_info): | |
575 | """Inspect line_info and return a handler instance or None.""" |
|
575 | """Inspect line_info and return a handler instance or None.""" | |
576 | return None |
|
576 | return None | |
577 |
|
577 | |||
578 | def __repr__(self): |
|
578 | def __repr__(self): | |
579 | return "<%s(priority=%r, enabled=%r)>" % ( |
|
579 | return "<%s(priority=%r, enabled=%r)>" % ( | |
580 | self.__class__.__name__, self.priority, self.enabled) |
|
580 | self.__class__.__name__, self.priority, self.enabled) | |
581 |
|
581 | |||
582 |
|
582 | |||
583 | class EmacsChecker(PrefilterChecker): |
|
583 | class EmacsChecker(PrefilterChecker): | |
584 |
|
584 | |||
585 | priority = Int(100, config=True) |
|
585 | priority = Int(100, config=True) | |
586 | enabled = Bool(False, config=True) |
|
586 | enabled = Bool(False, config=True) | |
587 |
|
587 | |||
588 | def check(self, line_info): |
|
588 | def check(self, line_info): | |
589 | "Emacs ipython-mode tags certain input lines." |
|
589 | "Emacs ipython-mode tags certain input lines." | |
590 | if line_info.line.endswith('# PYTHON-MODE'): |
|
590 | if line_info.line.endswith('# PYTHON-MODE'): | |
591 | return self.prefilter_manager.get_handler_by_name('emacs') |
|
591 | return self.prefilter_manager.get_handler_by_name('emacs') | |
592 | else: |
|
592 | else: | |
593 | return None |
|
593 | return None | |
594 |
|
594 | |||
595 |
|
595 | |||
596 | class ShellEscapeChecker(PrefilterChecker): |
|
596 | class ShellEscapeChecker(PrefilterChecker): | |
597 |
|
597 | |||
598 | priority = Int(200, config=True) |
|
598 | priority = Int(200, config=True) | |
599 |
|
599 | |||
600 | def check(self, line_info): |
|
600 | def check(self, line_info): | |
601 | if line_info.line.lstrip().startswith(ESC_SHELL): |
|
601 | if line_info.line.lstrip().startswith(ESC_SHELL): | |
602 | return self.prefilter_manager.get_handler_by_name('shell') |
|
602 | return self.prefilter_manager.get_handler_by_name('shell') | |
603 |
|
603 | |||
604 |
|
604 | |||
605 | class IPyAutocallChecker(PrefilterChecker): |
|
605 | class IPyAutocallChecker(PrefilterChecker): | |
606 |
|
606 | |||
607 | priority = Int(300, config=True) |
|
607 | priority = Int(300, config=True) | |
608 |
|
608 | |||
609 | def check(self, line_info): |
|
609 | def check(self, line_info): | |
610 | "Instances of IPyAutocall in user_ns get autocalled immediately" |
|
610 | "Instances of IPyAutocall in user_ns get autocalled immediately" | |
611 | obj = self.shell.user_ns.get(line_info.ifun, None) |
|
611 | obj = self.shell.user_ns.get(line_info.ifun, None) | |
612 | if isinstance(obj, IPyAutocall): |
|
612 | if isinstance(obj, IPyAutocall): | |
613 | obj.set_ip(self.shell) |
|
613 | obj.set_ip(self.shell) | |
614 | return self.prefilter_manager.get_handler_by_name('auto') |
|
614 | return self.prefilter_manager.get_handler_by_name('auto') | |
615 | else: |
|
615 | else: | |
616 | return None |
|
616 | return None | |
617 |
|
617 | |||
618 |
|
618 | |||
619 | class MultiLineMagicChecker(PrefilterChecker): |
|
619 | class MultiLineMagicChecker(PrefilterChecker): | |
620 |
|
620 | |||
621 | priority = Int(400, config=True) |
|
621 | priority = Int(400, config=True) | |
622 |
|
622 | |||
623 | def check(self, line_info): |
|
623 | def check(self, line_info): | |
624 | "Allow ! and !! in multi-line statements if multi_line_specials is on" |
|
624 | "Allow ! and !! in multi-line statements if multi_line_specials is on" | |
625 | # Note that this one of the only places we check the first character of |
|
625 | # Note that this one of the only places we check the first character of | |
626 | # ifun and *not* the pre_char. Also note that the below test matches |
|
626 | # ifun and *not* the pre_char. Also note that the below test matches | |
627 | # both ! and !!. |
|
627 | # both ! and !!. | |
628 | if line_info.continue_prompt \ |
|
628 | if line_info.continue_prompt \ | |
629 | and self.prefilter_manager.multi_line_specials: |
|
629 | and self.prefilter_manager.multi_line_specials: | |
630 | if line_info.ifun.startswith(ESC_MAGIC): |
|
630 | if line_info.ifun.startswith(ESC_MAGIC): | |
631 | return self.prefilter_manager.get_handler_by_name('magic') |
|
631 | return self.prefilter_manager.get_handler_by_name('magic') | |
632 | else: |
|
632 | else: | |
633 | return None |
|
633 | return None | |
634 |
|
634 | |||
635 |
|
635 | |||
636 | class EscCharsChecker(PrefilterChecker): |
|
636 | class EscCharsChecker(PrefilterChecker): | |
637 |
|
637 | |||
638 | priority = Int(500, config=True) |
|
638 | priority = Int(500, config=True) | |
639 |
|
639 | |||
640 | def check(self, line_info): |
|
640 | def check(self, line_info): | |
641 | """Check for escape character and return either a handler to handle it, |
|
641 | """Check for escape character and return either a handler to handle it, | |
642 | or None if there is no escape char.""" |
|
642 | or None if there is no escape char.""" | |
643 | if line_info.line[-1] == ESC_HELP \ |
|
643 | if line_info.line[-1] == ESC_HELP \ | |
644 | and line_info.pre_char != ESC_SHELL \ |
|
644 | and line_info.pre_char != ESC_SHELL \ | |
645 | and line_info.pre_char != ESC_SH_CAP: |
|
645 | and line_info.pre_char != ESC_SH_CAP: | |
646 | # the ? can be at the end, but *not* for either kind of shell escape, |
|
646 | # the ? can be at the end, but *not* for either kind of shell escape, | |
647 | # because a ? can be a vaild final char in a shell cmd |
|
647 | # because a ? can be a vaild final char in a shell cmd | |
648 | return self.prefilter_manager.get_handler_by_name('help') |
|
648 | return self.prefilter_manager.get_handler_by_name('help') | |
649 | else: |
|
649 | else: | |
650 | # This returns None like it should if no handler exists |
|
650 | # This returns None like it should if no handler exists | |
651 | return self.prefilter_manager.get_handler_by_esc(line_info.pre_char) |
|
651 | return self.prefilter_manager.get_handler_by_esc(line_info.pre_char) | |
652 |
|
652 | |||
653 |
|
653 | |||
654 | class AssignmentChecker(PrefilterChecker): |
|
654 | class AssignmentChecker(PrefilterChecker): | |
655 |
|
655 | |||
656 | priority = Int(600, config=True) |
|
656 | priority = Int(600, config=True) | |
657 |
|
657 | |||
658 | def check(self, line_info): |
|
658 | def check(self, line_info): | |
659 | """Check to see if user is assigning to a var for the first time, in |
|
659 | """Check to see if user is assigning to a var for the first time, in | |
660 | which case we want to avoid any sort of automagic / autocall games. |
|
660 | which case we want to avoid any sort of automagic / autocall games. | |
661 |
|
661 | |||
662 | This allows users to assign to either alias or magic names true python |
|
662 | This allows users to assign to either alias or magic names true python | |
663 | variables (the magic/alias systems always take second seat to true |
|
663 | variables (the magic/alias systems always take second seat to true | |
664 | python code). E.g. ls='hi', or ls,that=1,2""" |
|
664 | python code). E.g. ls='hi', or ls,that=1,2""" | |
665 | if line_info.the_rest: |
|
665 | if line_info.the_rest: | |
666 | if line_info.the_rest[0] in '=,': |
|
666 | if line_info.the_rest[0] in '=,': | |
667 | return self.prefilter_manager.get_handler_by_name('normal') |
|
667 | return self.prefilter_manager.get_handler_by_name('normal') | |
668 | else: |
|
668 | else: | |
669 | return None |
|
669 | return None | |
670 |
|
670 | |||
671 |
|
671 | |||
672 | class AutoMagicChecker(PrefilterChecker): |
|
672 | class AutoMagicChecker(PrefilterChecker): | |
673 |
|
673 | |||
674 | priority = Int(700, config=True) |
|
674 | priority = Int(700, config=True) | |
675 |
|
675 | |||
676 | def check(self, line_info): |
|
676 | def check(self, line_info): | |
677 | """If the ifun is magic, and automagic is on, run it. Note: normal, |
|
677 | """If the ifun is magic, and automagic is on, run it. Note: normal, | |
678 | non-auto magic would already have been triggered via '%' in |
|
678 | non-auto magic would already have been triggered via '%' in | |
679 | check_esc_chars. This just checks for automagic. Also, before |
|
679 | check_esc_chars. This just checks for automagic. Also, before | |
680 | triggering the magic handler, make sure that there is nothing in the |
|
680 | triggering the magic handler, make sure that there is nothing in the | |
681 | user namespace which could shadow it.""" |
|
681 | user namespace which could shadow it.""" | |
682 | if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun): |
|
682 | if not self.shell.automagic or not hasattr(self.shell,'magic_'+line_info.ifun): | |
683 | return None |
|
683 | return None | |
684 |
|
684 | |||
685 | # We have a likely magic method. Make sure we should actually call it. |
|
685 | # We have a likely magic method. Make sure we should actually call it. | |
686 | if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: |
|
686 | if line_info.continue_prompt and not self.prefilter_manager.multi_line_specials: | |
687 | return None |
|
687 | return None | |
688 |
|
688 | |||
689 | head = line_info.ifun.split('.',1)[0] |
|
689 | head = line_info.ifun.split('.',1)[0] | |
690 | if is_shadowed(head, self.shell): |
|
690 | if is_shadowed(head, self.shell): | |
691 | return None |
|
691 | return None | |
692 |
|
692 | |||
693 | return self.prefilter_manager.get_handler_by_name('magic') |
|
693 | return self.prefilter_manager.get_handler_by_name('magic') | |
694 |
|
694 | |||
695 |
|
695 | |||
696 | class AliasChecker(PrefilterChecker): |
|
696 | class AliasChecker(PrefilterChecker): | |
697 |
|
697 | |||
698 | priority = Int(800, config=True) |
|
698 | priority = Int(800, config=True) | |
699 |
|
699 | |||
700 | def check(self, line_info): |
|
700 | def check(self, line_info): | |
701 | "Check if the initital identifier on the line is an alias." |
|
701 | "Check if the initital identifier on the line is an alias." | |
702 | # Note: aliases can not contain '.' |
|
702 | # Note: aliases can not contain '.' | |
703 | head = line_info.ifun.split('.',1)[0] |
|
703 | head = line_info.ifun.split('.',1)[0] | |
704 | if line_info.ifun not in self.shell.alias_manager \ |
|
704 | if line_info.ifun not in self.shell.alias_manager \ | |
705 | or head not in self.shell.alias_manager \ |
|
705 | or head not in self.shell.alias_manager \ | |
706 | or is_shadowed(head, self.shell): |
|
706 | or is_shadowed(head, self.shell): | |
707 | return None |
|
707 | return None | |
708 |
|
708 | |||
709 | return self.prefilter_manager.get_handler_by_name('alias') |
|
709 | return self.prefilter_manager.get_handler_by_name('alias') | |
710 |
|
710 | |||
711 |
|
711 | |||
712 | class PythonOpsChecker(PrefilterChecker): |
|
712 | class PythonOpsChecker(PrefilterChecker): | |
713 |
|
713 | |||
714 | priority = Int(900, config=True) |
|
714 | priority = Int(900, config=True) | |
715 |
|
715 | |||
716 | def check(self, line_info): |
|
716 | def check(self, line_info): | |
717 | """If the 'rest' of the line begins with a function call or pretty much |
|
717 | """If the 'rest' of the line begins with a function call or pretty much | |
718 | any python operator, we should simply execute the line (regardless of |
|
718 | any python operator, we should simply execute the line (regardless of | |
719 | whether or not there's a possible autocall expansion). This avoids |
|
719 | whether or not there's a possible autocall expansion). This avoids | |
720 | spurious (and very confusing) geattr() accesses.""" |
|
720 | spurious (and very confusing) geattr() accesses.""" | |
721 | if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': |
|
721 | if line_info.the_rest and line_info.the_rest[0] in '!=()<>,+*/%^&|': | |
722 | return self.prefilter_manager.get_handler_by_name('normal') |
|
722 | return self.prefilter_manager.get_handler_by_name('normal') | |
723 | else: |
|
723 | else: | |
724 | return None |
|
724 | return None | |
725 |
|
725 | |||
726 |
|
726 | |||
727 | class AutocallChecker(PrefilterChecker): |
|
727 | class AutocallChecker(PrefilterChecker): | |
728 |
|
728 | |||
729 | priority = Int(1000, config=True) |
|
729 | priority = Int(1000, config=True) | |
730 |
|
730 | |||
731 | def check(self, line_info): |
|
731 | def check(self, line_info): | |
732 | "Check if the initial word/function is callable and autocall is on." |
|
732 | "Check if the initial word/function is callable and autocall is on." | |
733 | if not self.shell.autocall: |
|
733 | if not self.shell.autocall: | |
734 | return None |
|
734 | return None | |
735 |
|
735 | |||
736 | oinfo = line_info.ofind(self.shell) # This can mutate state via getattr |
|
736 | oinfo = line_info.ofind(self.shell) # This can mutate state via getattr | |
737 | if not oinfo['found']: |
|
737 | if not oinfo['found']: | |
738 | return None |
|
738 | return None | |
739 |
|
739 | |||
740 | if callable(oinfo['obj']) \ |
|
740 | if callable(oinfo['obj']) \ | |
741 | and (not re_exclude_auto.match(line_info.the_rest)) \ |
|
741 | and (not re_exclude_auto.match(line_info.the_rest)) \ | |
742 | and re_fun_name.match(line_info.ifun): |
|
742 | and re_fun_name.match(line_info.ifun): | |
743 | return self.prefilter_manager.get_handler_by_name('auto') |
|
743 | return self.prefilter_manager.get_handler_by_name('auto') | |
744 | else: |
|
744 | else: | |
745 | return None |
|
745 | return None | |
746 |
|
746 | |||
747 |
|
747 | |||
748 | #----------------------------------------------------------------------------- |
|
748 | #----------------------------------------------------------------------------- | |
749 | # Prefilter handlers |
|
749 | # Prefilter handlers | |
750 | #----------------------------------------------------------------------------- |
|
750 | #----------------------------------------------------------------------------- | |
751 |
|
751 | |||
752 |
|
752 | |||
753 | class PrefilterHandler(Configurable): |
|
753 | class PrefilterHandler(Configurable): | |
754 |
|
754 | |||
755 | handler_name = Str('normal') |
|
755 | handler_name = Str('normal') | |
756 | esc_strings = List([]) |
|
756 | esc_strings = List([]) | |
757 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') |
|
757 | shell = Instance('IPython.core.interactiveshell.InteractiveShellABC') | |
758 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') |
|
758 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager') | |
759 |
|
759 | |||
760 | def __init__(self, shell=None, prefilter_manager=None, config=None): |
|
760 | def __init__(self, shell=None, prefilter_manager=None, config=None): | |
761 | super(PrefilterHandler, self).__init__( |
|
761 | super(PrefilterHandler, self).__init__( | |
762 | shell=shell, prefilter_manager=prefilter_manager, config=config |
|
762 | shell=shell, prefilter_manager=prefilter_manager, config=config | |
763 | ) |
|
763 | ) | |
764 | self.prefilter_manager.register_handler( |
|
764 | self.prefilter_manager.register_handler( | |
765 | self.handler_name, |
|
765 | self.handler_name, | |
766 | self, |
|
766 | self, | |
767 | self.esc_strings |
|
767 | self.esc_strings | |
768 | ) |
|
768 | ) | |
769 |
|
769 | |||
770 | def handle(self, line_info): |
|
770 | def handle(self, line_info): | |
771 | # print "normal: ", line_info |
|
771 | # print "normal: ", line_info | |
772 | """Handle normal input lines. Use as a template for handlers.""" |
|
772 | """Handle normal input lines. Use as a template for handlers.""" | |
773 |
|
773 | |||
774 | # With autoindent on, we need some way to exit the input loop, and I |
|
774 | # With autoindent on, we need some way to exit the input loop, and I | |
775 | # don't want to force the user to have to backspace all the way to |
|
775 | # don't want to force the user to have to backspace all the way to | |
776 | # clear the line. The rule will be in this case, that either two |
|
776 | # clear the line. The rule will be in this case, that either two | |
777 | # lines of pure whitespace in a row, or a line of pure whitespace but |
|
777 | # lines of pure whitespace in a row, or a line of pure whitespace but | |
778 | # of a size different to the indent level, will exit the input loop. |
|
778 | # of a size different to the indent level, will exit the input loop. | |
779 | line = line_info.line |
|
779 | line = line_info.line | |
780 | continue_prompt = line_info.continue_prompt |
|
780 | continue_prompt = line_info.continue_prompt | |
781 |
|
781 | |||
782 | if (continue_prompt and |
|
782 | if (continue_prompt and | |
783 | self.shell.autoindent and |
|
783 | self.shell.autoindent and | |
784 | line.isspace() and |
|
784 | line.isspace() and | |
785 |
|
785 | |||
786 | (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2 |
|
786 | (0 < abs(len(line) - self.shell.indent_current_nsp) <= 2 | |
787 | or |
|
787 | or | |
788 | not self.shell.buffer |
|
788 | not self.shell.buffer | |
789 | or |
|
789 | or | |
790 | (self.shell.buffer[-1]).isspace() |
|
790 | (self.shell.buffer[-1]).isspace() | |
791 | ) |
|
791 | ) | |
792 | ): |
|
792 | ): | |
793 | line = '' |
|
793 | line = '' | |
794 |
|
794 | |||
795 | self.shell.log(line, line, continue_prompt) |
|
795 | self.shell.log(line, line, continue_prompt) | |
796 | return line |
|
796 | return line | |
797 |
|
797 | |||
798 | def __str__(self): |
|
798 | def __str__(self): | |
799 | return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) |
|
799 | return "<%s(name=%s)>" % (self.__class__.__name__, self.handler_name) | |
800 |
|
800 | |||
801 |
|
801 | |||
802 | class AliasHandler(PrefilterHandler): |
|
802 | class AliasHandler(PrefilterHandler): | |
803 |
|
803 | |||
804 | handler_name = Str('alias') |
|
804 | handler_name = Str('alias') | |
805 |
|
805 | |||
806 | def handle(self, line_info): |
|
806 | def handle(self, line_info): | |
807 | """Handle alias input lines. """ |
|
807 | """Handle alias input lines. """ | |
808 | transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) |
|
808 | transformed = self.shell.alias_manager.expand_aliases(line_info.ifun,line_info.the_rest) | |
809 | # pre is needed, because it carries the leading whitespace. Otherwise |
|
809 | # pre is needed, because it carries the leading whitespace. Otherwise | |
810 | # aliases won't work in indented sections. |
|
810 | # aliases won't work in indented sections. | |
811 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, |
|
811 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, | |
812 | make_quoted_expr(transformed)) |
|
812 | make_quoted_expr(transformed)) | |
813 |
|
813 | |||
814 | self.shell.log(line_info.line, line_out, line_info.continue_prompt) |
|
814 | self.shell.log(line_info.line, line_out, line_info.continue_prompt) | |
815 | return line_out |
|
815 | return line_out | |
816 |
|
816 | |||
817 |
|
817 | |||
818 | class ShellEscapeHandler(PrefilterHandler): |
|
818 | class ShellEscapeHandler(PrefilterHandler): | |
819 |
|
819 | |||
820 | handler_name = Str('shell') |
|
820 | handler_name = Str('shell') | |
821 | esc_strings = List([ESC_SHELL, ESC_SH_CAP]) |
|
821 | esc_strings = List([ESC_SHELL, ESC_SH_CAP]) | |
822 |
|
822 | |||
823 | def handle(self, line_info): |
|
823 | def handle(self, line_info): | |
824 | """Execute the line in a shell, empty return value""" |
|
824 | """Execute the line in a shell, empty return value""" | |
825 | magic_handler = self.prefilter_manager.get_handler_by_name('magic') |
|
825 | magic_handler = self.prefilter_manager.get_handler_by_name('magic') | |
826 |
|
826 | |||
827 | line = line_info.line |
|
827 | line = line_info.line | |
828 | if line.lstrip().startswith(ESC_SH_CAP): |
|
828 | if line.lstrip().startswith(ESC_SH_CAP): | |
829 | # rewrite LineInfo's line, ifun and the_rest to properly hold the |
|
829 | # rewrite LineInfo's line, ifun and the_rest to properly hold the | |
830 | # call to %sx and the actual command to be executed, so |
|
830 | # call to %sx and the actual command to be executed, so | |
831 | # handle_magic can work correctly. Note that this works even if |
|
831 | # handle_magic can work correctly. Note that this works even if | |
832 | # the line is indented, so it handles multi_line_specials |
|
832 | # the line is indented, so it handles multi_line_specials | |
833 | # properly. |
|
833 | # properly. | |
834 | new_rest = line.lstrip()[2:] |
|
834 | new_rest = line.lstrip()[2:] | |
835 | line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) |
|
835 | line_info.line = '%ssx %s' % (ESC_MAGIC, new_rest) | |
836 | line_info.ifun = 'sx' |
|
836 | line_info.ifun = 'sx' | |
837 | line_info.the_rest = new_rest |
|
837 | line_info.the_rest = new_rest | |
838 | return magic_handler.handle(line_info) |
|
838 | return magic_handler.handle(line_info) | |
839 | else: |
|
839 | else: | |
840 | cmd = line.lstrip().lstrip(ESC_SHELL) |
|
840 | cmd = line.lstrip().lstrip(ESC_SHELL) | |
841 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, |
|
841 | line_out = '%sget_ipython().system(%s)' % (line_info.pre_whitespace, | |
842 | make_quoted_expr(cmd)) |
|
842 | make_quoted_expr(cmd)) | |
843 | # update cache/log and return |
|
843 | # update cache/log and return | |
844 | self.shell.log(line, line_out, line_info.continue_prompt) |
|
844 | self.shell.log(line, line_out, line_info.continue_prompt) | |
845 | return line_out |
|
845 | return line_out | |
846 |
|
846 | |||
847 |
|
847 | |||
848 | class MagicHandler(PrefilterHandler): |
|
848 | class MagicHandler(PrefilterHandler): | |
849 |
|
849 | |||
850 | handler_name = Str('magic') |
|
850 | handler_name = Str('magic') | |
851 | esc_strings = List([ESC_MAGIC]) |
|
851 | esc_strings = List([ESC_MAGIC]) | |
852 |
|
852 | |||
853 | def handle(self, line_info): |
|
853 | def handle(self, line_info): | |
854 | """Execute magic functions.""" |
|
854 | """Execute magic functions.""" | |
855 | ifun = line_info.ifun |
|
855 | ifun = line_info.ifun | |
856 | the_rest = line_info.the_rest |
|
856 | the_rest = line_info.the_rest | |
857 | cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace, |
|
857 | cmd = '%sget_ipython().magic(%s)' % (line_info.pre_whitespace, | |
858 | make_quoted_expr(ifun + " " + the_rest)) |
|
858 | make_quoted_expr(ifun + " " + the_rest)) | |
859 | self.shell.log(line_info.line, cmd, line_info.continue_prompt) |
|
859 | self.shell.log(line_info.line, cmd, line_info.continue_prompt) | |
860 | return cmd |
|
860 | return cmd | |
861 |
|
861 | |||
862 |
|
862 | |||
863 | class AutoHandler(PrefilterHandler): |
|
863 | class AutoHandler(PrefilterHandler): | |
864 |
|
864 | |||
865 | handler_name = Str('auto') |
|
865 | handler_name = Str('auto') | |
866 | esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) |
|
866 | esc_strings = List([ESC_PAREN, ESC_QUOTE, ESC_QUOTE2]) | |
867 |
|
867 | |||
868 | def handle(self, line_info): |
|
868 | def handle(self, line_info): | |
869 | """Handle lines which can be auto-executed, quoting if requested.""" |
|
869 | """Handle lines which can be auto-executed, quoting if requested.""" | |
870 | line = line_info.line |
|
870 | line = line_info.line | |
871 | ifun = line_info.ifun |
|
871 | ifun = line_info.ifun | |
872 | the_rest = line_info.the_rest |
|
872 | the_rest = line_info.the_rest | |
873 | pre = line_info.pre |
|
873 | pre = line_info.pre | |
874 | continue_prompt = line_info.continue_prompt |
|
874 | continue_prompt = line_info.continue_prompt | |
875 | obj = line_info.ofind(self)['obj'] |
|
875 | obj = line_info.ofind(self)['obj'] | |
876 | #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg |
|
876 | #print 'pre <%s> ifun <%s> rest <%s>' % (pre,ifun,the_rest) # dbg | |
877 |
|
877 | |||
878 | # This should only be active for single-line input! |
|
878 | # This should only be active for single-line input! | |
879 | if continue_prompt: |
|
879 | if continue_prompt: | |
880 | self.shell.log(line,line,continue_prompt) |
|
880 | self.shell.log(line,line,continue_prompt) | |
881 | return line |
|
881 | return line | |
882 |
|
882 | |||
883 | force_auto = isinstance(obj, IPyAutocall) |
|
883 | force_auto = isinstance(obj, IPyAutocall) | |
884 | auto_rewrite = True |
|
884 | auto_rewrite = True | |
885 |
|
885 | |||
886 | if pre == ESC_QUOTE: |
|
886 | if pre == ESC_QUOTE: | |
887 | # Auto-quote splitting on whitespace |
|
887 | # Auto-quote splitting on whitespace | |
888 | newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) |
|
888 | newcmd = '%s("%s")' % (ifun,'", "'.join(the_rest.split()) ) | |
889 | elif pre == ESC_QUOTE2: |
|
889 | elif pre == ESC_QUOTE2: | |
890 | # Auto-quote whole string |
|
890 | # Auto-quote whole string | |
891 | newcmd = '%s("%s")' % (ifun,the_rest) |
|
891 | newcmd = '%s("%s")' % (ifun,the_rest) | |
892 | elif pre == ESC_PAREN: |
|
892 | elif pre == ESC_PAREN: | |
893 | newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) |
|
893 | newcmd = '%s(%s)' % (ifun,",".join(the_rest.split())) | |
894 | else: |
|
894 | else: | |
895 | # Auto-paren. |
|
895 | # Auto-paren. | |
896 | # We only apply it to argument-less calls if the autocall |
|
896 | # We only apply it to argument-less calls if the autocall | |
897 | # parameter is set to 2. We only need to check that autocall is < |
|
897 | # parameter is set to 2. We only need to check that autocall is < | |
898 | # 2, since this function isn't called unless it's at least 1. |
|
898 | # 2, since this function isn't called unless it's at least 1. | |
899 | if not the_rest and (self.shell.autocall < 2) and not force_auto: |
|
899 | if not the_rest and (self.shell.autocall < 2) and not force_auto: | |
900 | newcmd = '%s %s' % (ifun,the_rest) |
|
900 | newcmd = '%s %s' % (ifun,the_rest) | |
901 | auto_rewrite = False |
|
901 | auto_rewrite = False | |
902 | else: |
|
902 | else: | |
903 | if not force_auto and the_rest.startswith('['): |
|
903 | if not force_auto and the_rest.startswith('['): | |
904 | if hasattr(obj,'__getitem__'): |
|
904 | if hasattr(obj,'__getitem__'): | |
905 | # Don't autocall in this case: item access for an object |
|
905 | # Don't autocall in this case: item access for an object | |
906 | # which is BOTH callable and implements __getitem__. |
|
906 | # which is BOTH callable and implements __getitem__. | |
907 | newcmd = '%s %s' % (ifun,the_rest) |
|
907 | newcmd = '%s %s' % (ifun,the_rest) | |
908 | auto_rewrite = False |
|
908 | auto_rewrite = False | |
909 | else: |
|
909 | else: | |
910 | # if the object doesn't support [] access, go ahead and |
|
910 | # if the object doesn't support [] access, go ahead and | |
911 | # autocall |
|
911 | # autocall | |
912 | newcmd = '%s(%s)' % (ifun.rstrip(),the_rest) |
|
912 | newcmd = '%s(%s)' % (ifun.rstrip(),the_rest) | |
913 | elif the_rest.endswith(';'): |
|
913 | elif the_rest.endswith(';'): | |
914 | newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) |
|
914 | newcmd = '%s(%s);' % (ifun.rstrip(),the_rest[:-1]) | |
915 | else: |
|
915 | else: | |
916 | newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) |
|
916 | newcmd = '%s(%s)' % (ifun.rstrip(), the_rest) | |
917 |
|
917 | |||
918 | if auto_rewrite: |
|
918 | if auto_rewrite: | |
919 | self.shell.auto_rewrite_input(newcmd) |
|
919 | self.shell.auto_rewrite_input(newcmd) | |
920 |
|
920 | |||
921 | # log what is now valid Python, not the actual user input (without the |
|
921 | # log what is now valid Python, not the actual user input (without the | |
922 | # final newline) |
|
922 | # final newline) | |
923 | self.shell.log(line,newcmd,continue_prompt) |
|
923 | self.shell.log(line,newcmd,continue_prompt) | |
924 | return newcmd |
|
924 | return newcmd | |
925 |
|
925 | |||
926 |
|
926 | |||
927 | class HelpHandler(PrefilterHandler): |
|
927 | class HelpHandler(PrefilterHandler): | |
928 |
|
928 | |||
929 | handler_name = Str('help') |
|
929 | handler_name = Str('help') | |
930 | esc_strings = List([ESC_HELP]) |
|
930 | esc_strings = List([ESC_HELP]) | |
931 |
|
931 | |||
932 | def handle(self, line_info): |
|
932 | def handle(self, line_info): | |
933 | """Try to get some help for the object. |
|
933 | """Try to get some help for the object. | |
934 |
|
934 | |||
935 | obj? or ?obj -> basic information. |
|
935 | obj? or ?obj -> basic information. | |
936 | obj?? or ??obj -> more details. |
|
936 | obj?? or ??obj -> more details. | |
937 | """ |
|
937 | """ | |
938 | normal_handler = self.prefilter_manager.get_handler_by_name('normal') |
|
938 | normal_handler = self.prefilter_manager.get_handler_by_name('normal') | |
939 | line = line_info.line |
|
939 | line = line_info.line | |
940 | # We need to make sure that we don't process lines which would be |
|
940 | # We need to make sure that we don't process lines which would be | |
941 | # otherwise valid python, such as "x=1 # what?" |
|
941 | # otherwise valid python, such as "x=1 # what?" | |
942 | try: |
|
942 | try: | |
943 | codeop.compile_command(line) |
|
943 | codeop.compile_command(line) | |
944 | except SyntaxError: |
|
944 | except SyntaxError: | |
945 | # We should only handle as help stuff which is NOT valid syntax |
|
945 | # We should only handle as help stuff which is NOT valid syntax | |
946 | if line[0]==ESC_HELP: |
|
946 | if line[0]==ESC_HELP: | |
947 | line = line[1:] |
|
947 | line = line[1:] | |
948 | elif line[-1]==ESC_HELP: |
|
948 | elif line[-1]==ESC_HELP: | |
949 | line = line[:-1] |
|
949 | line = line[:-1] | |
950 | self.shell.log(line, '#?'+line, line_info.continue_prompt) |
|
950 | self.shell.log(line, '#?'+line, line_info.continue_prompt) | |
951 | if line: |
|
951 | if line: | |
952 | #print 'line:<%r>' % line # dbg |
|
952 | #print 'line:<%r>' % line # dbg | |
953 | self.shell.magic_pinfo(line) |
|
953 | self.shell.magic_pinfo(line) | |
954 | else: |
|
954 | else: | |
955 | self.shell.show_usage() |
|
955 | self.shell.show_usage() | |
956 | return '' # Empty string is needed here! |
|
956 | return '' # Empty string is needed here! | |
957 | except: |
|
957 | except: | |
958 | raise |
|
958 | raise | |
959 | # Pass any other exceptions through to the normal handler |
|
959 | # Pass any other exceptions through to the normal handler | |
960 | return normal_handler.handle(line_info) |
|
960 | return normal_handler.handle(line_info) | |
961 | else: |
|
961 | else: | |
962 | # If the code compiles ok, we should handle it normally |
|
962 | # If the code compiles ok, we should handle it normally | |
963 | return normal_handler.handle(line_info) |
|
963 | return normal_handler.handle(line_info) | |
964 |
|
964 | |||
965 |
|
965 | |||
966 | class EmacsHandler(PrefilterHandler): |
|
966 | class EmacsHandler(PrefilterHandler): | |
967 |
|
967 | |||
968 | handler_name = Str('emacs') |
|
968 | handler_name = Str('emacs') | |
969 | esc_strings = List([]) |
|
969 | esc_strings = List([]) | |
970 |
|
970 | |||
971 | def handle(self, line_info): |
|
971 | def handle(self, line_info): | |
972 | """Handle input lines marked by python-mode.""" |
|
972 | """Handle input lines marked by python-mode.""" | |
973 |
|
973 | |||
974 | # Currently, nothing is done. Later more functionality can be added |
|
974 | # Currently, nothing is done. Later more functionality can be added | |
975 | # here if needed. |
|
975 | # here if needed. | |
976 |
|
976 | |||
977 | # The input cache shouldn't be updated |
|
977 | # The input cache shouldn't be updated | |
978 | return line_info.line |
|
978 | return line_info.line | |
979 |
|
979 | |||
980 |
|
980 | |||
981 | #----------------------------------------------------------------------------- |
|
981 | #----------------------------------------------------------------------------- | |
982 | # Defaults |
|
982 | # Defaults | |
983 | #----------------------------------------------------------------------------- |
|
983 | #----------------------------------------------------------------------------- | |
984 |
|
984 | |||
985 |
|
985 | |||
986 | _default_transformers = [ |
|
986 | _default_transformers = [ | |
987 | AssignSystemTransformer, |
|
987 | AssignSystemTransformer, | |
988 | AssignMagicTransformer, |
|
988 | AssignMagicTransformer, | |
989 | PyPromptTransformer, |
|
989 | PyPromptTransformer, | |
990 | IPyPromptTransformer, |
|
990 | IPyPromptTransformer, | |
991 | ] |
|
991 | ] | |
992 |
|
992 | |||
993 | _default_checkers = [ |
|
993 | _default_checkers = [ | |
994 | EmacsChecker, |
|
994 | EmacsChecker, | |
995 | ShellEscapeChecker, |
|
995 | ShellEscapeChecker, | |
996 | IPyAutocallChecker, |
|
996 | IPyAutocallChecker, | |
997 | MultiLineMagicChecker, |
|
997 | MultiLineMagicChecker, | |
998 | EscCharsChecker, |
|
998 | EscCharsChecker, | |
999 | AssignmentChecker, |
|
999 | AssignmentChecker, | |
1000 | AutoMagicChecker, |
|
1000 | AutoMagicChecker, | |
1001 | AliasChecker, |
|
1001 | AliasChecker, | |
1002 | PythonOpsChecker, |
|
1002 | PythonOpsChecker, | |
1003 | AutocallChecker |
|
1003 | AutocallChecker | |
1004 | ] |
|
1004 | ] | |
1005 |
|
1005 | |||
1006 | _default_handlers = [ |
|
1006 | _default_handlers = [ | |
1007 | PrefilterHandler, |
|
1007 | PrefilterHandler, | |
1008 | AliasHandler, |
|
1008 | AliasHandler, | |
1009 | ShellEscapeHandler, |
|
1009 | ShellEscapeHandler, | |
1010 | MagicHandler, |
|
1010 | MagicHandler, | |
1011 | AutoHandler, |
|
1011 | AutoHandler, | |
1012 | HelpHandler, |
|
1012 | HelpHandler, | |
1013 | EmacsHandler |
|
1013 | EmacsHandler | |
1014 | ] |
|
1014 | ] |
@@ -1,649 +1,649 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Tests for the inputsplitter module. |
|
2 | """Tests for the inputsplitter module. | |
3 | """ |
|
3 | """ | |
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2010 The IPython Development Team |
|
5 | # Copyright (C) 2010 The IPython Development Team | |
6 | # |
|
6 | # | |
7 | # Distributed under the terms of the BSD License. The full license is in |
|
7 | # Distributed under the terms of the BSD License. The full license is in | |
8 | # the file COPYING, distributed as part of this software. |
|
8 | # the file COPYING, distributed as part of this software. | |
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 |
|
10 | |||
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 | # Imports |
|
12 | # Imports | |
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # stdlib |
|
14 | # stdlib | |
15 | import unittest |
|
15 | import unittest | |
16 | import sys |
|
16 | import sys | |
17 |
|
17 | |||
18 | # Third party |
|
18 | # Third party | |
19 | import nose.tools as nt |
|
19 | import nose.tools as nt | |
20 |
|
20 | |||
21 | # Our own |
|
21 | # Our own | |
22 | from IPython.core import inputsplitter as isp |
|
22 | from IPython.core import inputsplitter as isp | |
23 |
|
23 | |||
24 | #----------------------------------------------------------------------------- |
|
24 | #----------------------------------------------------------------------------- | |
25 | # Semi-complete examples (also used as tests) |
|
25 | # Semi-complete examples (also used as tests) | |
26 | #----------------------------------------------------------------------------- |
|
26 | #----------------------------------------------------------------------------- | |
27 |
|
27 | |||
28 | # Note: at the bottom, there's a slightly more complete version of this that |
|
28 | # Note: at the bottom, there's a slightly more complete version of this that | |
29 | # can be useful during development of code here. |
|
29 | # can be useful during development of code here. | |
30 |
|
30 | |||
31 | def mini_interactive_loop(raw_input): |
|
31 | def mini_interactive_loop(raw_input): | |
32 | """Minimal example of the logic of an interactive interpreter loop. |
|
32 | """Minimal example of the logic of an interactive interpreter loop. | |
33 |
|
33 | |||
34 | This serves as an example, and it is used by the test system with a fake |
|
34 | This serves as an example, and it is used by the test system with a fake | |
35 | raw_input that simulates interactive input.""" |
|
35 | raw_input that simulates interactive input.""" | |
36 |
|
36 | |||
37 | from IPython.core.inputsplitter import InputSplitter |
|
37 | from IPython.core.inputsplitter import InputSplitter | |
38 |
|
38 | |||
39 | isp = InputSplitter() |
|
39 | isp = InputSplitter() | |
40 | # In practice, this input loop would be wrapped in an outside loop to read |
|
40 | # In practice, this input loop would be wrapped in an outside loop to read | |
41 | # input indefinitely, until some exit/quit command was issued. Here we |
|
41 | # input indefinitely, until some exit/quit command was issued. Here we | |
42 | # only illustrate the basic inner loop. |
|
42 | # only illustrate the basic inner loop. | |
43 | while isp.push_accepts_more(): |
|
43 | while isp.push_accepts_more(): | |
44 | indent = ' '*isp.indent_spaces |
|
44 | indent = ' '*isp.indent_spaces | |
45 | prompt = '>>> ' + indent |
|
45 | prompt = '>>> ' + indent | |
46 | line = indent + raw_input(prompt) |
|
46 | line = indent + raw_input(prompt) | |
47 | isp.push(line) |
|
47 | isp.push(line) | |
48 |
|
48 | |||
49 | # Here we just return input so we can use it in a test suite, but a real |
|
49 | # Here we just return input so we can use it in a test suite, but a real | |
50 | # interpreter would instead send it for execution somewhere. |
|
50 | # interpreter would instead send it for execution somewhere. | |
51 | src = isp.source_reset() |
|
51 | src = isp.source_reset() | |
52 | #print 'Input source was:\n', src # dbg |
|
52 | #print 'Input source was:\n', src # dbg | |
53 | return src |
|
53 | return src | |
54 |
|
54 | |||
55 | #----------------------------------------------------------------------------- |
|
55 | #----------------------------------------------------------------------------- | |
56 | # Test utilities, just for local use |
|
56 | # Test utilities, just for local use | |
57 | #----------------------------------------------------------------------------- |
|
57 | #----------------------------------------------------------------------------- | |
58 |
|
58 | |||
59 | def assemble(block): |
|
59 | def assemble(block): | |
60 | """Assemble a block into multi-line sub-blocks.""" |
|
60 | """Assemble a block into multi-line sub-blocks.""" | |
61 | return ['\n'.join(sub_block)+'\n' for sub_block in block] |
|
61 | return ['\n'.join(sub_block)+'\n' for sub_block in block] | |
62 |
|
62 | |||
63 |
|
63 | |||
64 | def pseudo_input(lines): |
|
64 | def pseudo_input(lines): | |
65 | """Return a function that acts like raw_input but feeds the input list.""" |
|
65 | """Return a function that acts like raw_input but feeds the input list.""" | |
66 | ilines = iter(lines) |
|
66 | ilines = iter(lines) | |
67 | def raw_in(prompt): |
|
67 | def raw_in(prompt): | |
68 | try: |
|
68 | try: | |
69 | return next(ilines) |
|
69 | return next(ilines) | |
70 | except StopIteration: |
|
70 | except StopIteration: | |
71 | return '' |
|
71 | return '' | |
72 | return raw_in |
|
72 | return raw_in | |
73 |
|
73 | |||
74 | #----------------------------------------------------------------------------- |
|
74 | #----------------------------------------------------------------------------- | |
75 | # Tests |
|
75 | # Tests | |
76 | #----------------------------------------------------------------------------- |
|
76 | #----------------------------------------------------------------------------- | |
77 | def test_spaces(): |
|
77 | def test_spaces(): | |
78 | tests = [('', 0), |
|
78 | tests = [('', 0), | |
79 | (' ', 1), |
|
79 | (' ', 1), | |
80 | ('\n', 0), |
|
80 | ('\n', 0), | |
81 | (' \n', 1), |
|
81 | (' \n', 1), | |
82 | ('x', 0), |
|
82 | ('x', 0), | |
83 | (' x', 1), |
|
83 | (' x', 1), | |
84 | (' x',2), |
|
84 | (' x',2), | |
85 | (' x',4), |
|
85 | (' x',4), | |
86 | # Note: tabs are counted as a single whitespace! |
|
86 | # Note: tabs are counted as a single whitespace! | |
87 | ('\tx', 1), |
|
87 | ('\tx', 1), | |
88 | ('\t x', 2), |
|
88 | ('\t x', 2), | |
89 | ] |
|
89 | ] | |
90 |
|
90 | |||
91 | for s, nsp in tests: |
|
91 | for s, nsp in tests: | |
92 | nt.assert_equal(isp.num_ini_spaces(s), nsp) |
|
92 | nt.assert_equal(isp.num_ini_spaces(s), nsp) | |
93 |
|
93 | |||
94 |
|
94 | |||
95 | def test_remove_comments(): |
|
95 | def test_remove_comments(): | |
96 | tests = [('text', 'text'), |
|
96 | tests = [('text', 'text'), | |
97 | ('text # comment', 'text '), |
|
97 | ('text # comment', 'text '), | |
98 | ('text # comment\n', 'text \n'), |
|
98 | ('text # comment\n', 'text \n'), | |
99 | ('text # comment \n', 'text \n'), |
|
99 | ('text # comment \n', 'text \n'), | |
100 | ('line # c \nline\n','line \nline\n'), |
|
100 | ('line # c \nline\n','line \nline\n'), | |
101 | ('line # c \nline#c2 \nline\nline #c\n\n', |
|
101 | ('line # c \nline#c2 \nline\nline #c\n\n', | |
102 | 'line \nline\nline\nline \n\n'), |
|
102 | 'line \nline\nline\nline \n\n'), | |
103 | ] |
|
103 | ] | |
104 |
|
104 | |||
105 | for inp, out in tests: |
|
105 | for inp, out in tests: | |
106 | nt.assert_equal(isp.remove_comments(inp), out) |
|
106 | nt.assert_equal(isp.remove_comments(inp), out) | |
107 |
|
107 | |||
108 |
|
108 | |||
109 | def test_get_input_encoding(): |
|
109 | def test_get_input_encoding(): | |
110 | encoding = isp.get_input_encoding() |
|
110 | encoding = isp.get_input_encoding() | |
111 | nt.assert_true(isinstance(encoding, basestring)) |
|
111 | nt.assert_true(isinstance(encoding, basestring)) | |
112 | # simple-minded check that at least encoding a simple string works with the |
|
112 | # simple-minded check that at least encoding a simple string works with the | |
113 | # encoding we got. |
|
113 | # encoding we got. | |
114 | nt.assert_equal('test'.encode(encoding), 'test') |
|
114 | nt.assert_equal('test'.encode(encoding), 'test') | |
115 |
|
115 | |||
116 |
|
116 | |||
117 | class NoInputEncodingTestCase(unittest.TestCase): |
|
117 | class NoInputEncodingTestCase(unittest.TestCase): | |
118 | def setUp(self): |
|
118 | def setUp(self): | |
119 | self.old_stdin = sys.stdin |
|
119 | self.old_stdin = sys.stdin | |
120 | class X: pass |
|
120 | class X: pass | |
121 | fake_stdin = X() |
|
121 | fake_stdin = X() | |
122 | sys.stdin = fake_stdin |
|
122 | sys.stdin = fake_stdin | |
123 |
|
123 | |||
124 | def test(self): |
|
124 | def test(self): | |
125 | # Verify that if sys.stdin has no 'encoding' attribute we do the right |
|
125 | # Verify that if sys.stdin has no 'encoding' attribute we do the right | |
126 | # thing |
|
126 | # thing | |
127 | enc = isp.get_input_encoding() |
|
127 | enc = isp.get_input_encoding() | |
128 | self.assertEqual(enc, 'ascii') |
|
128 | self.assertEqual(enc, 'ascii') | |
129 |
|
129 | |||
130 | def tearDown(self): |
|
130 | def tearDown(self): | |
131 | sys.stdin = self.old_stdin |
|
131 | sys.stdin = self.old_stdin | |
132 |
|
132 | |||
133 |
|
133 | |||
134 | class InputSplitterTestCase(unittest.TestCase): |
|
134 | class InputSplitterTestCase(unittest.TestCase): | |
135 | def setUp(self): |
|
135 | def setUp(self): | |
136 | self.isp = isp.InputSplitter() |
|
136 | self.isp = isp.InputSplitter() | |
137 |
|
137 | |||
138 | def test_reset(self): |
|
138 | def test_reset(self): | |
139 | isp = self.isp |
|
139 | isp = self.isp | |
140 | isp.push('x=1') |
|
140 | isp.push('x=1') | |
141 | isp.reset() |
|
141 | isp.reset() | |
142 | self.assertEqual(isp._buffer, []) |
|
142 | self.assertEqual(isp._buffer, []) | |
143 | self.assertEqual(isp.indent_spaces, 0) |
|
143 | self.assertEqual(isp.indent_spaces, 0) | |
144 | self.assertEqual(isp.source, '') |
|
144 | self.assertEqual(isp.source, '') | |
145 | self.assertEqual(isp.code, None) |
|
145 | self.assertEqual(isp.code, None) | |
146 | self.assertEqual(isp._is_complete, False) |
|
146 | self.assertEqual(isp._is_complete, False) | |
147 |
|
147 | |||
148 | def test_source(self): |
|
148 | def test_source(self): | |
149 | self.isp._store('1') |
|
149 | self.isp._store('1') | |
150 | self.isp._store('2') |
|
150 | self.isp._store('2') | |
151 | self.assertEqual(self.isp.source, '1\n2\n') |
|
151 | self.assertEqual(self.isp.source, '1\n2\n') | |
152 | self.assertTrue(len(self.isp._buffer)>0) |
|
152 | self.assertTrue(len(self.isp._buffer)>0) | |
153 | self.assertEqual(self.isp.source_reset(), '1\n2\n') |
|
153 | self.assertEqual(self.isp.source_reset(), '1\n2\n') | |
154 | self.assertEqual(self.isp._buffer, []) |
|
154 | self.assertEqual(self.isp._buffer, []) | |
155 | self.assertEqual(self.isp.source, '') |
|
155 | self.assertEqual(self.isp.source, '') | |
156 |
|
156 | |||
157 | def test_indent(self): |
|
157 | def test_indent(self): | |
158 | isp = self.isp # shorthand |
|
158 | isp = self.isp # shorthand | |
159 | isp.push('x=1') |
|
159 | isp.push('x=1') | |
160 | self.assertEqual(isp.indent_spaces, 0) |
|
160 | self.assertEqual(isp.indent_spaces, 0) | |
161 | isp.push('if 1:\n x=1') |
|
161 | isp.push('if 1:\n x=1') | |
162 | self.assertEqual(isp.indent_spaces, 4) |
|
162 | self.assertEqual(isp.indent_spaces, 4) | |
163 | isp.push('y=2\n') |
|
163 | isp.push('y=2\n') | |
164 | self.assertEqual(isp.indent_spaces, 0) |
|
164 | self.assertEqual(isp.indent_spaces, 0) | |
165 | isp.push('if 1:') |
|
165 | isp.push('if 1:') | |
166 | self.assertEqual(isp.indent_spaces, 4) |
|
166 | self.assertEqual(isp.indent_spaces, 4) | |
167 | isp.push(' x=1') |
|
167 | isp.push(' x=1') | |
168 | self.assertEqual(isp.indent_spaces, 4) |
|
168 | self.assertEqual(isp.indent_spaces, 4) | |
169 | # Blank lines shouldn't change the indent level |
|
169 | # Blank lines shouldn't change the indent level | |
170 | isp.push(' '*2) |
|
170 | isp.push(' '*2) | |
171 | self.assertEqual(isp.indent_spaces, 4) |
|
171 | self.assertEqual(isp.indent_spaces, 4) | |
172 |
|
172 | |||
173 | def test_indent2(self): |
|
173 | def test_indent2(self): | |
174 | isp = self.isp |
|
174 | isp = self.isp | |
175 | # When a multiline statement contains parens or multiline strings, we |
|
175 | # When a multiline statement contains parens or multiline strings, we | |
176 | # shouldn't get confused. |
|
176 | # shouldn't get confused. | |
177 | isp.push("if 1:") |
|
177 | isp.push("if 1:") | |
178 | isp.push(" x = (1+\n 2)") |
|
178 | isp.push(" x = (1+\n 2)") | |
179 | self.assertEqual(isp.indent_spaces, 4) |
|
179 | self.assertEqual(isp.indent_spaces, 4) | |
180 |
|
180 | |||
181 | def test_dedent(self): |
|
181 | def test_dedent(self): | |
182 | isp = self.isp # shorthand |
|
182 | isp = self.isp # shorthand | |
183 | isp.push('if 1:') |
|
183 | isp.push('if 1:') | |
184 | self.assertEqual(isp.indent_spaces, 4) |
|
184 | self.assertEqual(isp.indent_spaces, 4) | |
185 | isp.push(' pass') |
|
185 | isp.push(' pass') | |
186 | self.assertEqual(isp.indent_spaces, 0) |
|
186 | self.assertEqual(isp.indent_spaces, 0) | |
187 |
|
187 | |||
188 | def test_push(self): |
|
188 | def test_push(self): | |
189 | isp = self.isp |
|
189 | isp = self.isp | |
190 | self.assertTrue(isp.push('x=1')) |
|
190 | self.assertTrue(isp.push('x=1')) | |
191 |
|
191 | |||
192 | def test_push2(self): |
|
192 | def test_push2(self): | |
193 | isp = self.isp |
|
193 | isp = self.isp | |
194 | self.assertFalse(isp.push('if 1:')) |
|
194 | self.assertFalse(isp.push('if 1:')) | |
195 | for line in [' x=1', '# a comment', ' y=2']: |
|
195 | for line in [' x=1', '# a comment', ' y=2']: | |
196 | self.assertTrue(isp.push(line)) |
|
196 | self.assertTrue(isp.push(line)) | |
197 |
|
197 | |||
198 | def test_push3(self): |
|
198 | def test_push3(self): | |
199 | """Test input with leading whitespace""" |
|
199 | """Test input with leading whitespace""" | |
200 | isp = self.isp |
|
200 | isp = self.isp | |
201 | isp.push(' x=1') |
|
201 | isp.push(' x=1') | |
202 | isp.push(' y=2') |
|
202 | isp.push(' y=2') | |
203 | self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n') |
|
203 | self.assertEqual(isp.source, 'if 1:\n x=1\n y=2\n') | |
204 |
|
204 | |||
205 | def test_replace_mode(self): |
|
205 | def test_replace_mode(self): | |
206 | isp = self.isp |
|
206 | isp = self.isp | |
207 | isp.input_mode = 'block' |
|
207 | isp.input_mode = 'block' | |
208 | isp.push('x=1') |
|
208 | isp.push('x=1') | |
209 | self.assertEqual(isp.source, 'x=1\n') |
|
209 | self.assertEqual(isp.source, 'x=1\n') | |
210 | isp.push('x=2') |
|
210 | isp.push('x=2') | |
211 | self.assertEqual(isp.source, 'x=2\n') |
|
211 | self.assertEqual(isp.source, 'x=2\n') | |
212 |
|
212 | |||
213 | def test_push_accepts_more(self): |
|
213 | def test_push_accepts_more(self): | |
214 | isp = self.isp |
|
214 | isp = self.isp | |
215 | isp.push('x=1') |
|
215 | isp.push('x=1') | |
216 | self.assertFalse(isp.push_accepts_more()) |
|
216 | self.assertFalse(isp.push_accepts_more()) | |
217 |
|
217 | |||
218 | def test_push_accepts_more2(self): |
|
218 | def test_push_accepts_more2(self): | |
219 | isp = self.isp |
|
219 | isp = self.isp | |
220 | isp.push('if 1:') |
|
220 | isp.push('if 1:') | |
221 | self.assertTrue(isp.push_accepts_more()) |
|
221 | self.assertTrue(isp.push_accepts_more()) | |
222 | isp.push(' x=1') |
|
222 | isp.push(' x=1') | |
223 | self.assertTrue(isp.push_accepts_more()) |
|
223 | self.assertTrue(isp.push_accepts_more()) | |
224 | isp.push('') |
|
224 | isp.push('') | |
225 | self.assertFalse(isp.push_accepts_more()) |
|
225 | self.assertFalse(isp.push_accepts_more()) | |
226 |
|
226 | |||
227 | def test_push_accepts_more3(self): |
|
227 | def test_push_accepts_more3(self): | |
228 | isp = self.isp |
|
228 | isp = self.isp | |
229 | isp.push("x = (2+\n3)") |
|
229 | isp.push("x = (2+\n3)") | |
230 | self.assertFalse(isp.push_accepts_more()) |
|
230 | self.assertFalse(isp.push_accepts_more()) | |
231 |
|
231 | |||
232 | def test_push_accepts_more4(self): |
|
232 | def test_push_accepts_more4(self): | |
233 | isp = self.isp |
|
233 | isp = self.isp | |
234 | # When a multiline statement contains parens or multiline strings, we |
|
234 | # When a multiline statement contains parens or multiline strings, we | |
235 | # shouldn't get confused. |
|
235 | # shouldn't get confused. | |
236 | # FIXME: we should be able to better handle de-dents in statements like |
|
236 | # FIXME: we should be able to better handle de-dents in statements like | |
237 | # multiline strings and multiline expressions (continued with \ or |
|
237 | # multiline strings and multiline expressions (continued with \ or | |
238 | # parens). Right now we aren't handling the indentation tracking quite |
|
238 | # parens). Right now we aren't handling the indentation tracking quite | |
239 | # correctly with this, though in practice it may not be too much of a |
|
239 | # correctly with this, though in practice it may not be too much of a | |
240 | # problem. We'll need to see. |
|
240 | # problem. We'll need to see. | |
241 | isp.push("if 1:") |
|
241 | isp.push("if 1:") | |
242 | isp.push(" x = (2+") |
|
242 | isp.push(" x = (2+") | |
243 | isp.push(" 3)") |
|
243 | isp.push(" 3)") | |
244 | self.assertTrue(isp.push_accepts_more()) |
|
244 | self.assertTrue(isp.push_accepts_more()) | |
245 | isp.push(" y = 3") |
|
245 | isp.push(" y = 3") | |
246 | self.assertTrue(isp.push_accepts_more()) |
|
246 | self.assertTrue(isp.push_accepts_more()) | |
247 | isp.push('') |
|
247 | isp.push('') | |
248 | self.assertFalse(isp.push_accepts_more()) |
|
248 | self.assertFalse(isp.push_accepts_more()) | |
249 |
|
249 | |||
250 | def test_syntax_error(self): |
|
250 | def test_syntax_error(self): | |
251 | isp = self.isp |
|
251 | isp = self.isp | |
252 | # Syntax errors immediately produce a 'ready' block, so the invalid |
|
252 | # Syntax errors immediately produce a 'ready' block, so the invalid | |
253 | # Python can be sent to the kernel for evaluation with possible ipython |
|
253 | # Python can be sent to the kernel for evaluation with possible ipython | |
254 | # special-syntax conversion. |
|
254 | # special-syntax conversion. | |
255 | isp.push('run foo') |
|
255 | isp.push('run foo') | |
256 | self.assertFalse(isp.push_accepts_more()) |
|
256 | self.assertFalse(isp.push_accepts_more()) | |
257 |
|
257 | |||
258 | def check_split(self, block_lines, compile=True): |
|
258 | def check_split(self, block_lines, compile=True): | |
259 | blocks = assemble(block_lines) |
|
259 | blocks = assemble(block_lines) | |
260 | lines = ''.join(blocks) |
|
260 | lines = ''.join(blocks) | |
261 | oblock = self.isp.split_blocks(lines) |
|
261 | oblock = self.isp.split_blocks(lines) | |
262 | self.assertEqual(oblock, blocks) |
|
262 | self.assertEqual(oblock, blocks) | |
263 | if compile: |
|
263 | if compile: | |
264 | for block in blocks: |
|
264 | for block in blocks: | |
265 | self.isp._compile(block) |
|
265 | self.isp._compile(block) | |
266 |
|
266 | |||
267 | def test_split(self): |
|
267 | def test_split(self): | |
268 | # All blocks of input we want to test in a list. The format for each |
|
268 | # All blocks of input we want to test in a list. The format for each | |
269 | # block is a list of lists, with each inner lists consisting of all the |
|
269 | # block is a list of lists, with each inner lists consisting of all the | |
270 | # lines (as single-lines) that should make up a sub-block. |
|
270 | # lines (as single-lines) that should make up a sub-block. | |
271 |
|
271 | |||
272 | # Note: do NOT put here sub-blocks that don't compile, as the |
|
272 | # Note: do NOT put here sub-blocks that don't compile, as the | |
273 | # check_split() routine makes a final verification pass to check that |
|
273 | # check_split() routine makes a final verification pass to check that | |
274 | # each sub_block, as returned by split_blocks(), does compile |
|
274 | # each sub_block, as returned by split_blocks(), does compile | |
275 | # correctly. |
|
275 | # correctly. | |
276 | all_blocks = [ [['x=1']], |
|
276 | all_blocks = [ [['x=1']], | |
277 |
|
277 | |||
278 | [['x=1'], |
|
278 | [['x=1'], | |
279 | ['y=2']], |
|
279 | ['y=2']], | |
280 |
|
280 | |||
281 | [['x=1', |
|
281 | [['x=1', | |
282 | '# a comment'], |
|
282 | '# a comment'], | |
283 | ['y=11']], |
|
283 | ['y=11']], | |
284 |
|
284 | |||
285 | [['if 1:', |
|
285 | [['if 1:', | |
286 | ' x=1'], |
|
286 | ' x=1'], | |
287 | ['y=3']], |
|
287 | ['y=3']], | |
288 |
|
288 | |||
289 | [['def f(x):', |
|
289 | [['def f(x):', | |
290 | ' return x'], |
|
290 | ' return x'], | |
291 | ['x=1']], |
|
291 | ['x=1']], | |
292 |
|
292 | |||
293 | [['def f(x):', |
|
293 | [['def f(x):', | |
294 | ' x+=1', |
|
294 | ' x+=1', | |
295 | ' ', |
|
295 | ' ', | |
296 | ' return x'], |
|
296 | ' return x'], | |
297 | ['x=1']], |
|
297 | ['x=1']], | |
298 |
|
298 | |||
299 | [['def f(x):', |
|
299 | [['def f(x):', | |
300 | ' if x>0:', |
|
300 | ' if x>0:', | |
301 | ' y=1', |
|
301 | ' y=1', | |
302 | ' # a comment', |
|
302 | ' # a comment', | |
303 | ' else:', |
|
303 | ' else:', | |
304 | ' y=4', |
|
304 | ' y=4', | |
305 | ' ', |
|
305 | ' ', | |
306 | ' return y'], |
|
306 | ' return y'], | |
307 | ['x=1'], |
|
307 | ['x=1'], | |
308 | ['if 1:', |
|
308 | ['if 1:', | |
309 | ' y=11'] ], |
|
309 | ' y=11'] ], | |
310 |
|
310 | |||
311 | [['for i in range(10):' |
|
311 | [['for i in range(10):' | |
312 | ' x=i**2']], |
|
312 | ' x=i**2']], | |
313 |
|
313 | |||
314 | [['for i in range(10):' |
|
314 | [['for i in range(10):' | |
315 | ' x=i**2'], |
|
315 | ' x=i**2'], | |
316 | ['z = 1']], |
|
316 | ['z = 1']], | |
317 | ] |
|
317 | ] | |
318 | for block_lines in all_blocks: |
|
318 | for block_lines in all_blocks: | |
319 | self.check_split(block_lines) |
|
319 | self.check_split(block_lines) | |
320 |
|
320 | |||
321 | def test_split_syntax_errors(self): |
|
321 | def test_split_syntax_errors(self): | |
322 | # Block splitting with invalid syntax |
|
322 | # Block splitting with invalid syntax | |
323 | all_blocks = [ [['a syntax error']], |
|
323 | all_blocks = [ [['a syntax error']], | |
324 |
|
324 | |||
325 | [['x=1', |
|
325 | [['x=1', | |
326 | 'another syntax error']], |
|
326 | 'another syntax error']], | |
327 |
|
327 | |||
328 | [['for i in range(10):' |
|
328 | [['for i in range(10):' | |
329 | ' yet another error']], |
|
329 | ' yet another error']], | |
330 |
|
330 | |||
331 | ] |
|
331 | ] | |
332 | for block_lines in all_blocks: |
|
332 | for block_lines in all_blocks: | |
333 | self.check_split(block_lines, compile=False) |
|
333 | self.check_split(block_lines, compile=False) | |
334 |
|
334 | |||
335 |
|
335 | |||
336 | class InteractiveLoopTestCase(unittest.TestCase): |
|
336 | class InteractiveLoopTestCase(unittest.TestCase): | |
337 | """Tests for an interactive loop like a python shell. |
|
337 | """Tests for an interactive loop like a python shell. | |
338 | """ |
|
338 | """ | |
339 | def check_ns(self, lines, ns): |
|
339 | def check_ns(self, lines, ns): | |
340 | """Validate that the given input lines produce the resulting namespace. |
|
340 | """Validate that the given input lines produce the resulting namespace. | |
341 |
|
341 | |||
342 | Note: the input lines are given exactly as they would be typed in an |
|
342 | Note: the input lines are given exactly as they would be typed in an | |
343 | auto-indenting environment, as mini_interactive_loop above already does |
|
343 | auto-indenting environment, as mini_interactive_loop above already does | |
344 | auto-indenting and prepends spaces to the input. |
|
344 | auto-indenting and prepends spaces to the input. | |
345 | """ |
|
345 | """ | |
346 | src = mini_interactive_loop(pseudo_input(lines)) |
|
346 | src = mini_interactive_loop(pseudo_input(lines)) | |
347 | test_ns = {} |
|
347 | test_ns = {} | |
348 | exec src in test_ns |
|
348 | exec src in test_ns | |
349 | # We can't check that the provided ns is identical to the test_ns, |
|
349 | # We can't check that the provided ns is identical to the test_ns, | |
350 | # because Python fills test_ns with extra keys (copyright, etc). But |
|
350 | # because Python fills test_ns with extra keys (copyright, etc). But | |
351 | # we can check that the given dict is *contained* in test_ns |
|
351 | # we can check that the given dict is *contained* in test_ns | |
352 | for k,v in ns.items(): |
|
352 | for k,v in ns.items(): | |
353 | self.assertEqual(test_ns[k], v) |
|
353 | self.assertEqual(test_ns[k], v) | |
354 |
|
354 | |||
355 | def test_simple(self): |
|
355 | def test_simple(self): | |
356 | self.check_ns(['x=1'], dict(x=1)) |
|
356 | self.check_ns(['x=1'], dict(x=1)) | |
357 |
|
357 | |||
358 | def test_simple2(self): |
|
358 | def test_simple2(self): | |
359 | self.check_ns(['if 1:', 'x=2'], dict(x=2)) |
|
359 | self.check_ns(['if 1:', 'x=2'], dict(x=2)) | |
360 |
|
360 | |||
361 | def test_xy(self): |
|
361 | def test_xy(self): | |
362 | self.check_ns(['x=1; y=2'], dict(x=1, y=2)) |
|
362 | self.check_ns(['x=1; y=2'], dict(x=1, y=2)) | |
363 |
|
363 | |||
364 | def test_abc(self): |
|
364 | def test_abc(self): | |
365 | self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3)) |
|
365 | self.check_ns(['if 1:','a=1','b=2','c=3'], dict(a=1, b=2, c=3)) | |
366 |
|
366 | |||
367 | def test_multi(self): |
|
367 | def test_multi(self): | |
368 | self.check_ns(['x =(1+','1+','2)'], dict(x=4)) |
|
368 | self.check_ns(['x =(1+','1+','2)'], dict(x=4)) | |
369 |
|
369 | |||
370 |
|
370 | |||
371 | def test_LineInfo(): |
|
371 | def test_LineInfo(): | |
372 | """Simple test for LineInfo construction and str()""" |
|
372 | """Simple test for LineInfo construction and str()""" | |
373 | linfo = isp.LineInfo(' %cd /home') |
|
373 | linfo = isp.LineInfo(' %cd /home') | |
374 | nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]') |
|
374 | nt.assert_equals(str(linfo), 'LineInfo [ |%|cd|/home]') | |
375 |
|
375 | |||
376 |
|
376 | |||
377 | def test_split_user_input(): |
|
377 | def test_split_user_input(): | |
378 | """Unicode test - split_user_input already has good doctests""" |
|
378 | """Unicode test - split_user_input already has good doctests""" | |
379 | line = u"PΓ©rez Fernando" |
|
379 | line = u"PΓ©rez Fernando" | |
380 | parts = isp.split_user_input(line) |
|
380 | parts = isp.split_user_input(line) | |
381 | parts_expected = (u'', u'', u'', line) |
|
381 | parts_expected = (u'', u'', u'', line) | |
382 | nt.assert_equal(parts, parts_expected) |
|
382 | nt.assert_equal(parts, parts_expected) | |
383 |
|
383 | |||
384 |
|
384 | |||
385 | # Transformer tests |
|
385 | # Transformer tests | |
386 | def transform_checker(tests, func): |
|
386 | def transform_checker(tests, func): | |
387 | """Utility to loop over test inputs""" |
|
387 | """Utility to loop over test inputs""" | |
388 | for inp, tr in tests: |
|
388 | for inp, tr in tests: | |
389 | nt.assert_equals(func(inp), tr) |
|
389 | nt.assert_equals(func(inp), tr) | |
390 |
|
390 | |||
391 | # Data for all the syntax tests in the form of lists of pairs of |
|
391 | # Data for all the syntax tests in the form of lists of pairs of | |
392 | # raw/transformed input. We store it here as a global dict so that we can use |
|
392 | # raw/transformed input. We store it here as a global dict so that we can use | |
393 | # it both within single-function tests and also to validate the behavior of the |
|
393 | # it both within single-function tests and also to validate the behavior of the | |
394 | # larger objects |
|
394 | # larger objects | |
395 |
|
395 | |||
396 | syntax = \ |
|
396 | syntax = \ | |
397 | dict(assign_system = |
|
397 | dict(assign_system = | |
398 |
[('a =! ls', 'a = get_ipython(). |
|
398 | [('a =! ls', 'a = get_ipython().getoutput("ls")'), | |
399 |
('b = !ls', 'b = get_ipython(). |
|
399 | ('b = !ls', 'b = get_ipython().getoutput("ls")'), | |
400 | ('x=1', 'x=1'), # normal input is unmodified |
|
400 | ('x=1', 'x=1'), # normal input is unmodified | |
401 | (' ',' '), # blank lines are kept intact |
|
401 | (' ',' '), # blank lines are kept intact | |
402 | ], |
|
402 | ], | |
403 |
|
403 | |||
404 | assign_magic = |
|
404 | assign_magic = | |
405 | [('a =% who', 'a = get_ipython().magic("who")'), |
|
405 | [('a =% who', 'a = get_ipython().magic("who")'), | |
406 | ('b = %who', 'b = get_ipython().magic("who")'), |
|
406 | ('b = %who', 'b = get_ipython().magic("who")'), | |
407 | ('x=1', 'x=1'), # normal input is unmodified |
|
407 | ('x=1', 'x=1'), # normal input is unmodified | |
408 | (' ',' '), # blank lines are kept intact |
|
408 | (' ',' '), # blank lines are kept intact | |
409 | ], |
|
409 | ], | |
410 |
|
410 | |||
411 | classic_prompt = |
|
411 | classic_prompt = | |
412 | [('>>> x=1', 'x=1'), |
|
412 | [('>>> x=1', 'x=1'), | |
413 | ('x=1', 'x=1'), # normal input is unmodified |
|
413 | ('x=1', 'x=1'), # normal input is unmodified | |
414 | (' ', ' '), # blank lines are kept intact |
|
414 | (' ', ' '), # blank lines are kept intact | |
415 | ('... ', ''), # continuation prompts |
|
415 | ('... ', ''), # continuation prompts | |
416 | ], |
|
416 | ], | |
417 |
|
417 | |||
418 | ipy_prompt = |
|
418 | ipy_prompt = | |
419 | [('In [1]: x=1', 'x=1'), |
|
419 | [('In [1]: x=1', 'x=1'), | |
420 | ('x=1', 'x=1'), # normal input is unmodified |
|
420 | ('x=1', 'x=1'), # normal input is unmodified | |
421 | (' ',' '), # blank lines are kept intact |
|
421 | (' ',' '), # blank lines are kept intact | |
422 | (' ....: ', ''), # continuation prompts |
|
422 | (' ....: ', ''), # continuation prompts | |
423 | ], |
|
423 | ], | |
424 |
|
424 | |||
425 | # Tests for the escape transformer to leave normal code alone |
|
425 | # Tests for the escape transformer to leave normal code alone | |
426 | escaped_noesc = |
|
426 | escaped_noesc = | |
427 | [ (' ', ' '), |
|
427 | [ (' ', ' '), | |
428 | ('x=1', 'x=1'), |
|
428 | ('x=1', 'x=1'), | |
429 | ], |
|
429 | ], | |
430 |
|
430 | |||
431 | # System calls |
|
431 | # System calls | |
432 | escaped_shell = |
|
432 | escaped_shell = | |
433 | [ ('!ls', 'get_ipython().system("ls")'), |
|
433 | [ ('!ls', 'get_ipython().system("ls")'), | |
434 | # Double-escape shell, this means to capture the output of the |
|
434 | # Double-escape shell, this means to capture the output of the | |
435 | # subprocess and return it |
|
435 | # subprocess and return it | |
436 | ('!!ls', 'get_ipython().getoutput("ls")'), |
|
436 | ('!!ls', 'get_ipython().getoutput("ls")'), | |
437 | ], |
|
437 | ], | |
438 |
|
438 | |||
439 | # Help/object info |
|
439 | # Help/object info | |
440 | escaped_help = |
|
440 | escaped_help = | |
441 | [ ('?', 'get_ipython().show_usage()'), |
|
441 | [ ('?', 'get_ipython().show_usage()'), | |
442 | ('?x1', 'get_ipython().magic("pinfo x1")'), |
|
442 | ('?x1', 'get_ipython().magic("pinfo x1")'), | |
443 | ('??x2', 'get_ipython().magic("pinfo2 x2")'), |
|
443 | ('??x2', 'get_ipython().magic("pinfo2 x2")'), | |
444 | ('x3?', 'get_ipython().magic("pinfo x3")'), |
|
444 | ('x3?', 'get_ipython().magic("pinfo x3")'), | |
445 | ('x4??', 'get_ipython().magic("pinfo2 x4")'), |
|
445 | ('x4??', 'get_ipython().magic("pinfo2 x4")'), | |
446 | ('%hist?', 'get_ipython().magic("pinfo %hist")'), |
|
446 | ('%hist?', 'get_ipython().magic("pinfo %hist")'), | |
447 | ], |
|
447 | ], | |
448 |
|
448 | |||
449 | # Explicit magic calls |
|
449 | # Explicit magic calls | |
450 | escaped_magic = |
|
450 | escaped_magic = | |
451 | [ ('%cd', 'get_ipython().magic("cd")'), |
|
451 | [ ('%cd', 'get_ipython().magic("cd")'), | |
452 | ('%cd /home', 'get_ipython().magic("cd /home")'), |
|
452 | ('%cd /home', 'get_ipython().magic("cd /home")'), | |
453 | (' %magic', ' get_ipython().magic("magic")'), |
|
453 | (' %magic', ' get_ipython().magic("magic")'), | |
454 | ], |
|
454 | ], | |
455 |
|
455 | |||
456 | # Quoting with separate arguments |
|
456 | # Quoting with separate arguments | |
457 | escaped_quote = |
|
457 | escaped_quote = | |
458 | [ (',f', 'f("")'), |
|
458 | [ (',f', 'f("")'), | |
459 | (',f x', 'f("x")'), |
|
459 | (',f x', 'f("x")'), | |
460 | (' ,f y', ' f("y")'), |
|
460 | (' ,f y', ' f("y")'), | |
461 | (',f a b', 'f("a", "b")'), |
|
461 | (',f a b', 'f("a", "b")'), | |
462 | ], |
|
462 | ], | |
463 |
|
463 | |||
464 | # Quoting with single argument |
|
464 | # Quoting with single argument | |
465 | escaped_quote2 = |
|
465 | escaped_quote2 = | |
466 | [ (';f', 'f("")'), |
|
466 | [ (';f', 'f("")'), | |
467 | (';f x', 'f("x")'), |
|
467 | (';f x', 'f("x")'), | |
468 | (' ;f y', ' f("y")'), |
|
468 | (' ;f y', ' f("y")'), | |
469 | (';f a b', 'f("a b")'), |
|
469 | (';f a b', 'f("a b")'), | |
470 | ], |
|
470 | ], | |
471 |
|
471 | |||
472 | # Simply apply parens |
|
472 | # Simply apply parens | |
473 | escaped_paren = |
|
473 | escaped_paren = | |
474 | [ ('/f', 'f()'), |
|
474 | [ ('/f', 'f()'), | |
475 | ('/f x', 'f(x)'), |
|
475 | ('/f x', 'f(x)'), | |
476 | (' /f y', ' f(y)'), |
|
476 | (' /f y', ' f(y)'), | |
477 | ('/f a b', 'f(a, b)'), |
|
477 | ('/f a b', 'f(a, b)'), | |
478 | ], |
|
478 | ], | |
479 |
|
479 | |||
480 | ) |
|
480 | ) | |
481 |
|
481 | |||
482 | # multiline syntax examples. Each of these should be a list of lists, with |
|
482 | # multiline syntax examples. Each of these should be a list of lists, with | |
483 | # each entry itself having pairs of raw/transformed input. The union (with |
|
483 | # each entry itself having pairs of raw/transformed input. The union (with | |
484 | # '\n'.join() of the transformed inputs is what the splitter should produce |
|
484 | # '\n'.join() of the transformed inputs is what the splitter should produce | |
485 | # when fed the raw lines one at a time via push. |
|
485 | # when fed the raw lines one at a time via push. | |
486 | syntax_ml = \ |
|
486 | syntax_ml = \ | |
487 | dict(classic_prompt = |
|
487 | dict(classic_prompt = | |
488 | [ [('>>> for i in range(10):','for i in range(10):'), |
|
488 | [ [('>>> for i in range(10):','for i in range(10):'), | |
489 | ('... print i',' print i'), |
|
489 | ('... print i',' print i'), | |
490 | ('... ', ''), |
|
490 | ('... ', ''), | |
491 | ], |
|
491 | ], | |
492 | ], |
|
492 | ], | |
493 |
|
493 | |||
494 | ipy_prompt = |
|
494 | ipy_prompt = | |
495 | [ [('In [24]: for i in range(10):','for i in range(10):'), |
|
495 | [ [('In [24]: for i in range(10):','for i in range(10):'), | |
496 | (' ....: print i',' print i'), |
|
496 | (' ....: print i',' print i'), | |
497 | (' ....: ', ''), |
|
497 | (' ....: ', ''), | |
498 | ], |
|
498 | ], | |
499 | ], |
|
499 | ], | |
500 | ) |
|
500 | ) | |
501 |
|
501 | |||
502 |
|
502 | |||
503 | def test_assign_system(): |
|
503 | def test_assign_system(): | |
504 | transform_checker(syntax['assign_system'], isp.transform_assign_system) |
|
504 | transform_checker(syntax['assign_system'], isp.transform_assign_system) | |
505 |
|
505 | |||
506 |
|
506 | |||
507 | def test_assign_magic(): |
|
507 | def test_assign_magic(): | |
508 | transform_checker(syntax['assign_magic'], isp.transform_assign_magic) |
|
508 | transform_checker(syntax['assign_magic'], isp.transform_assign_magic) | |
509 |
|
509 | |||
510 |
|
510 | |||
511 | def test_classic_prompt(): |
|
511 | def test_classic_prompt(): | |
512 | transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt) |
|
512 | transform_checker(syntax['classic_prompt'], isp.transform_classic_prompt) | |
513 | for example in syntax_ml['classic_prompt']: |
|
513 | for example in syntax_ml['classic_prompt']: | |
514 | transform_checker(example, isp.transform_classic_prompt) |
|
514 | transform_checker(example, isp.transform_classic_prompt) | |
515 |
|
515 | |||
516 |
|
516 | |||
517 | def test_ipy_prompt(): |
|
517 | def test_ipy_prompt(): | |
518 | transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt) |
|
518 | transform_checker(syntax['ipy_prompt'], isp.transform_ipy_prompt) | |
519 | for example in syntax_ml['ipy_prompt']: |
|
519 | for example in syntax_ml['ipy_prompt']: | |
520 | transform_checker(example, isp.transform_ipy_prompt) |
|
520 | transform_checker(example, isp.transform_ipy_prompt) | |
521 |
|
521 | |||
522 |
|
522 | |||
523 | def test_escaped_noesc(): |
|
523 | def test_escaped_noesc(): | |
524 | transform_checker(syntax['escaped_noesc'], isp.transform_escaped) |
|
524 | transform_checker(syntax['escaped_noesc'], isp.transform_escaped) | |
525 |
|
525 | |||
526 |
|
526 | |||
527 | def test_escaped_shell(): |
|
527 | def test_escaped_shell(): | |
528 | transform_checker(syntax['escaped_shell'], isp.transform_escaped) |
|
528 | transform_checker(syntax['escaped_shell'], isp.transform_escaped) | |
529 |
|
529 | |||
530 |
|
530 | |||
531 | def test_escaped_help(): |
|
531 | def test_escaped_help(): | |
532 | transform_checker(syntax['escaped_help'], isp.transform_escaped) |
|
532 | transform_checker(syntax['escaped_help'], isp.transform_escaped) | |
533 |
|
533 | |||
534 |
|
534 | |||
535 | def test_escaped_magic(): |
|
535 | def test_escaped_magic(): | |
536 | transform_checker(syntax['escaped_magic'], isp.transform_escaped) |
|
536 | transform_checker(syntax['escaped_magic'], isp.transform_escaped) | |
537 |
|
537 | |||
538 |
|
538 | |||
539 | def test_escaped_quote(): |
|
539 | def test_escaped_quote(): | |
540 | transform_checker(syntax['escaped_quote'], isp.transform_escaped) |
|
540 | transform_checker(syntax['escaped_quote'], isp.transform_escaped) | |
541 |
|
541 | |||
542 |
|
542 | |||
543 | def test_escaped_quote2(): |
|
543 | def test_escaped_quote2(): | |
544 | transform_checker(syntax['escaped_quote2'], isp.transform_escaped) |
|
544 | transform_checker(syntax['escaped_quote2'], isp.transform_escaped) | |
545 |
|
545 | |||
546 |
|
546 | |||
547 | def test_escaped_paren(): |
|
547 | def test_escaped_paren(): | |
548 | transform_checker(syntax['escaped_paren'], isp.transform_escaped) |
|
548 | transform_checker(syntax['escaped_paren'], isp.transform_escaped) | |
549 |
|
549 | |||
550 |
|
550 | |||
551 | class IPythonInputTestCase(InputSplitterTestCase): |
|
551 | class IPythonInputTestCase(InputSplitterTestCase): | |
552 | """By just creating a new class whose .isp is a different instance, we |
|
552 | """By just creating a new class whose .isp is a different instance, we | |
553 | re-run the same test battery on the new input splitter. |
|
553 | re-run the same test battery on the new input splitter. | |
554 |
|
554 | |||
555 | In addition, this runs the tests over the syntax and syntax_ml dicts that |
|
555 | In addition, this runs the tests over the syntax and syntax_ml dicts that | |
556 | were tested by individual functions, as part of the OO interface. |
|
556 | were tested by individual functions, as part of the OO interface. | |
557 | """ |
|
557 | """ | |
558 |
|
558 | |||
559 | def setUp(self): |
|
559 | def setUp(self): | |
560 | self.isp = isp.IPythonInputSplitter(input_mode='line') |
|
560 | self.isp = isp.IPythonInputSplitter(input_mode='line') | |
561 |
|
561 | |||
562 | def test_syntax(self): |
|
562 | def test_syntax(self): | |
563 | """Call all single-line syntax tests from the main object""" |
|
563 | """Call all single-line syntax tests from the main object""" | |
564 | isp = self.isp |
|
564 | isp = self.isp | |
565 | for example in syntax.itervalues(): |
|
565 | for example in syntax.itervalues(): | |
566 | for raw, out_t in example: |
|
566 | for raw, out_t in example: | |
567 | if raw.startswith(' '): |
|
567 | if raw.startswith(' '): | |
568 | continue |
|
568 | continue | |
569 |
|
569 | |||
570 | isp.push(raw) |
|
570 | isp.push(raw) | |
571 | out = isp.source_reset().rstrip() |
|
571 | out = isp.source_reset().rstrip() | |
572 | self.assertEqual(out, out_t) |
|
572 | self.assertEqual(out, out_t) | |
573 |
|
573 | |||
574 | def test_syntax_multiline(self): |
|
574 | def test_syntax_multiline(self): | |
575 | isp = self.isp |
|
575 | isp = self.isp | |
576 | for example in syntax_ml.itervalues(): |
|
576 | for example in syntax_ml.itervalues(): | |
577 | out_t_parts = [] |
|
577 | out_t_parts = [] | |
578 | for line_pairs in example: |
|
578 | for line_pairs in example: | |
579 | for raw, out_t_part in line_pairs: |
|
579 | for raw, out_t_part in line_pairs: | |
580 | isp.push(raw) |
|
580 | isp.push(raw) | |
581 | out_t_parts.append(out_t_part) |
|
581 | out_t_parts.append(out_t_part) | |
582 |
|
582 | |||
583 | out = isp.source_reset().rstrip() |
|
583 | out = isp.source_reset().rstrip() | |
584 | out_t = '\n'.join(out_t_parts).rstrip() |
|
584 | out_t = '\n'.join(out_t_parts).rstrip() | |
585 | self.assertEqual(out, out_t) |
|
585 | self.assertEqual(out, out_t) | |
586 |
|
586 | |||
587 |
|
587 | |||
588 | class BlockIPythonInputTestCase(IPythonInputTestCase): |
|
588 | class BlockIPythonInputTestCase(IPythonInputTestCase): | |
589 |
|
589 | |||
590 | # Deactivate tests that don't make sense for the block mode |
|
590 | # Deactivate tests that don't make sense for the block mode | |
591 | test_push3 = test_split = lambda s: None |
|
591 | test_push3 = test_split = lambda s: None | |
592 |
|
592 | |||
593 | def setUp(self): |
|
593 | def setUp(self): | |
594 | self.isp = isp.IPythonInputSplitter(input_mode='block') |
|
594 | self.isp = isp.IPythonInputSplitter(input_mode='block') | |
595 |
|
595 | |||
596 | def test_syntax_multiline(self): |
|
596 | def test_syntax_multiline(self): | |
597 | isp = self.isp |
|
597 | isp = self.isp | |
598 | for example in syntax_ml.itervalues(): |
|
598 | for example in syntax_ml.itervalues(): | |
599 | raw_parts = [] |
|
599 | raw_parts = [] | |
600 | out_t_parts = [] |
|
600 | out_t_parts = [] | |
601 | for line_pairs in example: |
|
601 | for line_pairs in example: | |
602 | for raw, out_t_part in line_pairs: |
|
602 | for raw, out_t_part in line_pairs: | |
603 | raw_parts.append(raw) |
|
603 | raw_parts.append(raw) | |
604 | out_t_parts.append(out_t_part) |
|
604 | out_t_parts.append(out_t_part) | |
605 |
|
605 | |||
606 | raw = '\n'.join(raw_parts) |
|
606 | raw = '\n'.join(raw_parts) | |
607 | out_t = '\n'.join(out_t_parts) |
|
607 | out_t = '\n'.join(out_t_parts) | |
608 |
|
608 | |||
609 | isp.push(raw) |
|
609 | isp.push(raw) | |
610 | out = isp.source_reset() |
|
610 | out = isp.source_reset() | |
611 | # Match ignoring trailing whitespace |
|
611 | # Match ignoring trailing whitespace | |
612 | self.assertEqual(out.rstrip(), out_t.rstrip()) |
|
612 | self.assertEqual(out.rstrip(), out_t.rstrip()) | |
613 |
|
613 | |||
614 |
|
614 | |||
615 | #----------------------------------------------------------------------------- |
|
615 | #----------------------------------------------------------------------------- | |
616 | # Main - use as a script, mostly for developer experiments |
|
616 | # Main - use as a script, mostly for developer experiments | |
617 | #----------------------------------------------------------------------------- |
|
617 | #----------------------------------------------------------------------------- | |
618 |
|
618 | |||
619 | if __name__ == '__main__': |
|
619 | if __name__ == '__main__': | |
620 | # A simple demo for interactive experimentation. This code will not get |
|
620 | # A simple demo for interactive experimentation. This code will not get | |
621 | # picked up by any test suite. |
|
621 | # picked up by any test suite. | |
622 | from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter |
|
622 | from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter | |
623 |
|
623 | |||
624 | # configure here the syntax to use, prompt and whether to autoindent |
|
624 | # configure here the syntax to use, prompt and whether to autoindent | |
625 | #isp, start_prompt = InputSplitter(), '>>> ' |
|
625 | #isp, start_prompt = InputSplitter(), '>>> ' | |
626 | isp, start_prompt = IPythonInputSplitter(), 'In> ' |
|
626 | isp, start_prompt = IPythonInputSplitter(), 'In> ' | |
627 |
|
627 | |||
628 | autoindent = True |
|
628 | autoindent = True | |
629 | #autoindent = False |
|
629 | #autoindent = False | |
630 |
|
630 | |||
631 | try: |
|
631 | try: | |
632 | while True: |
|
632 | while True: | |
633 | prompt = start_prompt |
|
633 | prompt = start_prompt | |
634 | while isp.push_accepts_more(): |
|
634 | while isp.push_accepts_more(): | |
635 | indent = ' '*isp.indent_spaces |
|
635 | indent = ' '*isp.indent_spaces | |
636 | if autoindent: |
|
636 | if autoindent: | |
637 | line = indent + raw_input(prompt+indent) |
|
637 | line = indent + raw_input(prompt+indent) | |
638 | else: |
|
638 | else: | |
639 | line = raw_input(prompt) |
|
639 | line = raw_input(prompt) | |
640 | isp.push(line) |
|
640 | isp.push(line) | |
641 | prompt = '... ' |
|
641 | prompt = '... ' | |
642 |
|
642 | |||
643 | # Here we just return input so we can use it in a test suite, but a |
|
643 | # Here we just return input so we can use it in a test suite, but a | |
644 | # real interpreter would instead send it for execution somewhere. |
|
644 | # real interpreter would instead send it for execution somewhere. | |
645 | #src = isp.source; raise EOFError # dbg |
|
645 | #src = isp.source; raise EOFError # dbg | |
646 | src = isp.source_reset() |
|
646 | src = isp.source_reset() | |
647 | print 'Input source was:\n', src |
|
647 | print 'Input source was:\n', src | |
648 | except EOFError: |
|
648 | except EOFError: | |
649 | print 'Bye' |
|
649 | print 'Bye' |
@@ -1,121 +1,142 b'' | |||||
1 | """Common utilities for the various process_* implementations. |
|
1 | """Common utilities for the various process_* implementations. | |
2 |
|
2 | |||
3 | This file is only meant to be imported by the platform-specific implementations |
|
3 | This file is only meant to be imported by the platform-specific implementations | |
4 | of subprocess utilities, and it contains tools that are common to all of them. |
|
4 | of subprocess utilities, and it contains tools that are common to all of them. | |
5 | """ |
|
5 | """ | |
6 |
|
6 | |||
7 | #----------------------------------------------------------------------------- |
|
7 | #----------------------------------------------------------------------------- | |
8 | # Copyright (C) 2010 The IPython Development Team |
|
8 | # Copyright (C) 2010 The IPython Development Team | |
9 | # |
|
9 | # | |
10 | # Distributed under the terms of the BSD License. The full license is in |
|
10 | # Distributed under the terms of the BSD License. The full license is in | |
11 | # the file COPYING, distributed as part of this software. |
|
11 | # the file COPYING, distributed as part of this software. | |
12 | #----------------------------------------------------------------------------- |
|
12 | #----------------------------------------------------------------------------- | |
13 |
|
13 | |||
14 | #----------------------------------------------------------------------------- |
|
14 | #----------------------------------------------------------------------------- | |
15 | # Imports |
|
15 | # Imports | |
16 | #----------------------------------------------------------------------------- |
|
16 | #----------------------------------------------------------------------------- | |
17 | import subprocess |
|
17 | import subprocess | |
18 | import sys |
|
18 | import sys | |
19 |
|
19 | |||
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 | # Function definitions |
|
21 | # Function definitions | |
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 |
|
23 | |||
24 | def read_no_interrupt(p): |
|
24 | def read_no_interrupt(p): | |
25 | """Read from a pipe ignoring EINTR errors. |
|
25 | """Read from a pipe ignoring EINTR errors. | |
26 |
|
26 | |||
27 | This is necessary because when reading from pipes with GUI event loops |
|
27 | This is necessary because when reading from pipes with GUI event loops | |
28 | running in the background, often interrupts are raised that stop the |
|
28 | running in the background, often interrupts are raised that stop the | |
29 | command from completing.""" |
|
29 | command from completing.""" | |
30 | import errno |
|
30 | import errno | |
31 |
|
31 | |||
32 | try: |
|
32 | try: | |
33 | return p.read() |
|
33 | return p.read() | |
34 | except IOError, err: |
|
34 | except IOError, err: | |
35 | if err.errno != errno.EINTR: |
|
35 | if err.errno != errno.EINTR: | |
36 | raise |
|
36 | raise | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | def process_handler(cmd, callback, stderr=subprocess.PIPE): |
|
39 | def process_handler(cmd, callback, stderr=subprocess.PIPE): | |
40 | """Open a command in a shell subprocess and execute a callback. |
|
40 | """Open a command in a shell subprocess and execute a callback. | |
41 |
|
41 | |||
42 | This function provides common scaffolding for creating subprocess.Popen() |
|
42 | This function provides common scaffolding for creating subprocess.Popen() | |
43 | calls. It creates a Popen object and then calls the callback with it. |
|
43 | calls. It creates a Popen object and then calls the callback with it. | |
44 |
|
44 | |||
45 | Parameters |
|
45 | Parameters | |
46 | ---------- |
|
46 | ---------- | |
47 | cmd : str |
|
47 | cmd : str | |
48 | A string to be executed with the underlying system shell (by calling |
|
48 | A string to be executed with the underlying system shell (by calling | |
49 | :func:`Popen` with ``shell=True``. |
|
49 | :func:`Popen` with ``shell=True``. | |
50 |
|
50 | |||
51 | callback : callable |
|
51 | callback : callable | |
52 | A one-argument function that will be called with the Popen object. |
|
52 | A one-argument function that will be called with the Popen object. | |
53 |
|
53 | |||
54 | stderr : file descriptor number, optional |
|
54 | stderr : file descriptor number, optional | |
55 | By default this is set to ``subprocess.PIPE``, but you can also pass the |
|
55 | By default this is set to ``subprocess.PIPE``, but you can also pass the | |
56 | value ``subprocess.STDOUT`` to force the subprocess' stderr to go into |
|
56 | value ``subprocess.STDOUT`` to force the subprocess' stderr to go into | |
57 | the same file descriptor as its stdout. This is useful to read stdout |
|
57 | the same file descriptor as its stdout. This is useful to read stdout | |
58 | and stderr combined in the order they are generated. |
|
58 | and stderr combined in the order they are generated. | |
59 |
|
59 | |||
60 | Returns |
|
60 | Returns | |
61 | ------- |
|
61 | ------- | |
62 | The return value of the provided callback is returned. |
|
62 | The return value of the provided callback is returned. | |
63 | """ |
|
63 | """ | |
64 | sys.stdout.flush() |
|
64 | sys.stdout.flush() | |
65 | sys.stderr.flush() |
|
65 | sys.stderr.flush() | |
66 | # On win32, close_fds can't be true when using pipes for stdin/out/err |
|
66 | # On win32, close_fds can't be true when using pipes for stdin/out/err | |
67 | close_fds = sys.platform != 'win32' |
|
67 | close_fds = sys.platform != 'win32' | |
68 | p = subprocess.Popen(cmd, shell=True, |
|
68 | p = subprocess.Popen(cmd, shell=True, | |
69 | stdin=subprocess.PIPE, |
|
69 | stdin=subprocess.PIPE, | |
70 | stdout=subprocess.PIPE, |
|
70 | stdout=subprocess.PIPE, | |
71 | stderr=stderr, |
|
71 | stderr=stderr, | |
72 | close_fds=close_fds) |
|
72 | close_fds=close_fds) | |
73 |
|
73 | |||
74 | try: |
|
74 | try: | |
75 | out = callback(p) |
|
75 | out = callback(p) | |
76 | except KeyboardInterrupt: |
|
76 | except KeyboardInterrupt: | |
77 | print('^C') |
|
77 | print('^C') | |
78 | sys.stdout.flush() |
|
78 | sys.stdout.flush() | |
79 | sys.stderr.flush() |
|
79 | sys.stderr.flush() | |
80 | out = None |
|
80 | out = None | |
81 | finally: |
|
81 | finally: | |
82 | # Make really sure that we don't leave processes behind, in case the |
|
82 | # Make really sure that we don't leave processes behind, in case the | |
83 | # call above raises an exception |
|
83 | # call above raises an exception | |
84 | # We start by assuming the subprocess finished (to avoid NameErrors |
|
84 | # We start by assuming the subprocess finished (to avoid NameErrors | |
85 | # later depending on the path taken) |
|
85 | # later depending on the path taken) | |
86 | if p.returncode is None: |
|
86 | if p.returncode is None: | |
87 | try: |
|
87 | try: | |
88 | p.terminate() |
|
88 | p.terminate() | |
89 | p.poll() |
|
89 | p.poll() | |
90 | except OSError: |
|
90 | except OSError: | |
91 | pass |
|
91 | pass | |
92 | # One last try on our way out |
|
92 | # One last try on our way out | |
93 | if p.returncode is None: |
|
93 | if p.returncode is None: | |
94 | try: |
|
94 | try: | |
95 | p.kill() |
|
95 | p.kill() | |
96 | except OSError: |
|
96 | except OSError: | |
97 | pass |
|
97 | pass | |
98 |
|
98 | |||
99 | return out |
|
99 | return out | |
100 |
|
100 | |||
101 |
|
101 | |||
|
102 | def getoutput(cmd): | |||
|
103 | """Return standard output of executing cmd in a shell. | |||
|
104 | ||||
|
105 | Accepts the same arguments as os.system(). | |||
|
106 | ||||
|
107 | Parameters | |||
|
108 | ---------- | |||
|
109 | cmd : str | |||
|
110 | A command to be executed in the system shell. | |||
|
111 | ||||
|
112 | Returns | |||
|
113 | ------- | |||
|
114 | stdout : str | |||
|
115 | """ | |||
|
116 | ||||
|
117 | out = process_handler(cmd, lambda p: p.communicate()[0], subprocess.STDOUT) | |||
|
118 | if out is None: | |||
|
119 | out = '' | |||
|
120 | return out | |||
|
121 | ||||
|
122 | ||||
102 | def getoutputerror(cmd): |
|
123 | def getoutputerror(cmd): | |
103 | """Return (standard output, standard error) of executing cmd in a shell. |
|
124 | """Return (standard output, standard error) of executing cmd in a shell. | |
104 |
|
125 | |||
105 | Accepts the same arguments as os.system(). |
|
126 | Accepts the same arguments as os.system(). | |
106 |
|
127 | |||
107 | Parameters |
|
128 | Parameters | |
108 | ---------- |
|
129 | ---------- | |
109 | cmd : str |
|
130 | cmd : str | |
110 | A command to be executed in the system shell. |
|
131 | A command to be executed in the system shell. | |
111 |
|
132 | |||
112 | Returns |
|
133 | Returns | |
113 | ------- |
|
134 | ------- | |
114 | stdout : str |
|
135 | stdout : str | |
115 | stderr : str |
|
136 | stderr : str | |
116 | """ |
|
137 | """ | |
117 |
|
138 | |||
118 | out_err = process_handler(cmd, lambda p: p.communicate()) |
|
139 | out_err = process_handler(cmd, lambda p: p.communicate()) | |
119 | if out_err is None: |
|
140 | if out_err is None: | |
120 | out_err = '', '' |
|
141 | out_err = '', '' | |
121 | return out_err |
|
142 | return out_err |
@@ -1,169 +1,192 b'' | |||||
1 | """Posix-specific implementation of process utilities. |
|
1 | """Posix-specific implementation of process utilities. | |
2 |
|
2 | |||
3 | This file is only meant to be imported by process.py, not by end-users. |
|
3 | This file is only meant to be imported by process.py, not by end-users. | |
4 | """ |
|
4 | """ | |
5 |
|
5 | |||
6 | #----------------------------------------------------------------------------- |
|
6 | #----------------------------------------------------------------------------- | |
7 | # Copyright (C) 2010 The IPython Development Team |
|
7 | # Copyright (C) 2010 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 | #----------------------------------------------------------------------------- |
|
13 | #----------------------------------------------------------------------------- | |
14 | # Imports |
|
14 | # Imports | |
15 | #----------------------------------------------------------------------------- |
|
15 | #----------------------------------------------------------------------------- | |
16 | from __future__ import print_function |
|
16 | from __future__ import print_function | |
17 |
|
17 | |||
18 | # Stdlib |
|
18 | # Stdlib | |
19 | import subprocess as sp |
|
19 | import subprocess as sp | |
20 | import sys |
|
20 | import sys | |
21 |
|
21 | |||
22 | # Third-party |
|
22 | # Third-party | |
23 | # We ship our own copy of pexpect (it's a single file) to minimize dependencies |
|
23 | # We ship our own copy of pexpect (it's a single file) to minimize dependencies | |
24 | # for users, but it's only used if we don't find the system copy. |
|
24 | # for users, but it's only used if we don't find the system copy. | |
25 | try: |
|
25 | try: | |
26 | import pexpect |
|
26 | import pexpect | |
27 | except ImportError: |
|
27 | except ImportError: | |
28 | from IPython.external import pexpect |
|
28 | from IPython.external import pexpect | |
29 |
|
29 | |||
30 | # Our own |
|
30 | # Our own | |
31 | from .autoattr import auto_attr |
|
31 | from .autoattr import auto_attr | |
|
32 | from ._process_common import getoutput | |||
32 |
|
33 | |||
33 | #----------------------------------------------------------------------------- |
|
34 | #----------------------------------------------------------------------------- | |
34 | # Function definitions |
|
35 | # Function definitions | |
35 | #----------------------------------------------------------------------------- |
|
36 | #----------------------------------------------------------------------------- | |
36 |
|
37 | |||
37 | def _find_cmd(cmd): |
|
38 | def _find_cmd(cmd): | |
38 | """Find the full path to a command using which.""" |
|
39 | """Find the full path to a command using which.""" | |
39 |
|
40 | |||
40 | return sp.Popen(['/usr/bin/env', 'which', cmd], |
|
41 | return sp.Popen(['/usr/bin/env', 'which', cmd], | |
41 | stdout=sp.PIPE).communicate()[0] |
|
42 | stdout=sp.PIPE).communicate()[0] | |
42 |
|
43 | |||
43 |
|
44 | |||
44 | class ProcessHandler(object): |
|
45 | class ProcessHandler(object): | |
45 | """Execute subprocesses under the control of pexpect. |
|
46 | """Execute subprocesses under the control of pexpect. | |
46 | """ |
|
47 | """ | |
47 | # Timeout in seconds to wait on each reading of the subprocess' output. |
|
48 | # Timeout in seconds to wait on each reading of the subprocess' output. | |
48 | # This should not be set too low to avoid cpu overusage from our side, |
|
49 | # This should not be set too low to avoid cpu overusage from our side, | |
49 | # since we read in a loop whose period is controlled by this timeout. |
|
50 | # since we read in a loop whose period is controlled by this timeout. | |
50 | read_timeout = 0.05 |
|
51 | read_timeout = 0.05 | |
51 |
|
52 | |||
52 | # Timeout to give a process if we receive SIGINT, between sending the |
|
53 | # Timeout to give a process if we receive SIGINT, between sending the | |
53 | # SIGINT to the process and forcefully terminating it. |
|
54 | # SIGINT to the process and forcefully terminating it. | |
54 | terminate_timeout = 0.2 |
|
55 | terminate_timeout = 0.2 | |
55 |
|
56 | |||
56 | # File object where stdout and stderr of the subprocess will be written |
|
57 | # File object where stdout and stderr of the subprocess will be written | |
57 | logfile = None |
|
58 | logfile = None | |
58 |
|
59 | |||
59 | # Shell to call for subprocesses to execute |
|
60 | # Shell to call for subprocesses to execute | |
60 | sh = None |
|
61 | sh = None | |
61 |
|
62 | |||
62 | @auto_attr |
|
63 | @auto_attr | |
63 | def sh(self): |
|
64 | def sh(self): | |
64 | sh = pexpect.which('sh') |
|
65 | sh = pexpect.which('sh') | |
65 | if sh is None: |
|
66 | if sh is None: | |
66 | raise OSError('"sh" shell not found') |
|
67 | raise OSError('"sh" shell not found') | |
67 | return sh |
|
68 | return sh | |
68 |
|
69 | |||
69 | def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None): |
|
70 | def __init__(self, logfile=None, read_timeout=None, terminate_timeout=None): | |
70 | """Arguments are used for pexpect calls.""" |
|
71 | """Arguments are used for pexpect calls.""" | |
71 | self.read_timeout = (ProcessHandler.read_timeout if read_timeout is |
|
72 | self.read_timeout = (ProcessHandler.read_timeout if read_timeout is | |
72 | None else read_timeout) |
|
73 | None else read_timeout) | |
73 | self.terminate_timeout = (ProcessHandler.terminate_timeout if |
|
74 | self.terminate_timeout = (ProcessHandler.terminate_timeout if | |
74 | terminate_timeout is None else |
|
75 | terminate_timeout is None else | |
75 | terminate_timeout) |
|
76 | terminate_timeout) | |
76 | self.logfile = sys.stdout if logfile is None else logfile |
|
77 | self.logfile = sys.stdout if logfile is None else logfile | |
77 |
|
78 | |||
78 | def getoutput(self, cmd): |
|
79 | def getoutput(self, cmd): | |
79 | """Run a command and return its stdout/stderr as a string. |
|
80 | """Run a command and return its stdout/stderr as a string. | |
80 |
|
81 | |||
81 | Parameters |
|
82 | Parameters | |
82 | ---------- |
|
83 | ---------- | |
83 | cmd : str |
|
84 | cmd : str | |
84 | A command to be executed in the system shell. |
|
85 | A command to be executed in the system shell. | |
85 |
|
86 | |||
86 | Returns |
|
87 | Returns | |
87 | ------- |
|
88 | ------- | |
88 | output : str |
|
89 | output : str | |
89 | A string containing the combination of stdout and stderr from the |
|
90 | A string containing the combination of stdout and stderr from the | |
90 | subprocess, in whatever order the subprocess originally wrote to its |
|
91 | subprocess, in whatever order the subprocess originally wrote to its | |
91 | file descriptors (so the order of the information in this string is the |
|
92 | file descriptors (so the order of the information in this string is the | |
92 | correct order as would be seen if running the command in a terminal). |
|
93 | correct order as would be seen if running the command in a terminal). | |
93 | """ |
|
94 | """ | |
94 | pcmd = self._make_cmd(cmd) |
|
95 | pcmd = self._make_cmd(cmd) | |
95 | try: |
|
96 | try: | |
96 | return pexpect.run(pcmd).replace('\r\n', '\n') |
|
97 | return pexpect.run(pcmd).replace('\r\n', '\n') | |
97 | except KeyboardInterrupt: |
|
98 | except KeyboardInterrupt: | |
98 | print('^C', file=sys.stderr, end='') |
|
99 | print('^C', file=sys.stderr, end='') | |
99 |
|
100 | |||
|
101 | def getoutput_pexpect(self, cmd): | |||
|
102 | """Run a command and return its stdout/stderr as a string. | |||
|
103 | ||||
|
104 | Parameters | |||
|
105 | ---------- | |||
|
106 | cmd : str | |||
|
107 | A command to be executed in the system shell. | |||
|
108 | ||||
|
109 | Returns | |||
|
110 | ------- | |||
|
111 | output : str | |||
|
112 | A string containing the combination of stdout and stderr from the | |||
|
113 | subprocess, in whatever order the subprocess originally wrote to its | |||
|
114 | file descriptors (so the order of the information in this string is the | |||
|
115 | correct order as would be seen if running the command in a terminal). | |||
|
116 | """ | |||
|
117 | pcmd = self._make_cmd(cmd) | |||
|
118 | try: | |||
|
119 | return pexpect.run(pcmd).replace('\r\n', '\n') | |||
|
120 | except KeyboardInterrupt: | |||
|
121 | print('^C', file=sys.stderr, end='') | |||
|
122 | ||||
100 | def system(self, cmd): |
|
123 | def system(self, cmd): | |
101 | """Execute a command in a subshell. |
|
124 | """Execute a command in a subshell. | |
102 |
|
125 | |||
103 | Parameters |
|
126 | Parameters | |
104 | ---------- |
|
127 | ---------- | |
105 | cmd : str |
|
128 | cmd : str | |
106 | A command to be executed in the system shell. |
|
129 | A command to be executed in the system shell. | |
107 |
|
130 | |||
108 | Returns |
|
131 | Returns | |
109 | ------- |
|
132 | ------- | |
110 | None : we explicitly do NOT return the subprocess status code, as this |
|
133 | None : we explicitly do NOT return the subprocess status code, as this | |
111 | utility is meant to be used extensively in IPython, where any return |
|
134 | utility is meant to be used extensively in IPython, where any return | |
112 | value would trigger :func:`sys.displayhook` calls. |
|
135 | value would trigger :func:`sys.displayhook` calls. | |
113 | """ |
|
136 | """ | |
114 | pcmd = self._make_cmd(cmd) |
|
137 | pcmd = self._make_cmd(cmd) | |
115 | # Patterns to match on the output, for pexpect. We read input and |
|
138 | # Patterns to match on the output, for pexpect. We read input and | |
116 | # allow either a short timeout or EOF |
|
139 | # allow either a short timeout or EOF | |
117 | patterns = [pexpect.TIMEOUT, pexpect.EOF] |
|
140 | patterns = [pexpect.TIMEOUT, pexpect.EOF] | |
118 | # the index of the EOF pattern in the list. |
|
141 | # the index of the EOF pattern in the list. | |
119 | EOF_index = 1 # Fix this index if you change the list!! |
|
142 | EOF_index = 1 # Fix this index if you change the list!! | |
120 | # The size of the output stored so far in the process output buffer. |
|
143 | # The size of the output stored so far in the process output buffer. | |
121 | # Since pexpect only appends to this buffer, each time we print we |
|
144 | # Since pexpect only appends to this buffer, each time we print we | |
122 | # record how far we've printed, so that next time we only print *new* |
|
145 | # record how far we've printed, so that next time we only print *new* | |
123 | # content from the buffer. |
|
146 | # content from the buffer. | |
124 | out_size = 0 |
|
147 | out_size = 0 | |
125 | try: |
|
148 | try: | |
126 | # Since we're not really searching the buffer for text patterns, we |
|
149 | # Since we're not really searching the buffer for text patterns, we | |
127 | # can set pexpect's search window to be tiny and it won't matter. |
|
150 | # can set pexpect's search window to be tiny and it won't matter. | |
128 | # We only search for the 'patterns' timeout or EOF, which aren't in |
|
151 | # We only search for the 'patterns' timeout or EOF, which aren't in | |
129 | # the text itself. |
|
152 | # the text itself. | |
130 | child = pexpect.spawn(pcmd, searchwindowsize=1) |
|
153 | child = pexpect.spawn(pcmd, searchwindowsize=1) | |
131 | flush = sys.stdout.flush |
|
154 | flush = sys.stdout.flush | |
132 | while True: |
|
155 | while True: | |
133 | # res is the index of the pattern that caused the match, so we |
|
156 | # res is the index of the pattern that caused the match, so we | |
134 | # know whether we've finished (if we matched EOF) or not |
|
157 | # know whether we've finished (if we matched EOF) or not | |
135 | res_idx = child.expect_list(patterns, self.read_timeout) |
|
158 | res_idx = child.expect_list(patterns, self.read_timeout) | |
136 | print(child.before[out_size:], end='') |
|
159 | print(child.before[out_size:], end='') | |
137 | flush() |
|
160 | flush() | |
138 | # Update the pointer to what we've already printed |
|
161 | # Update the pointer to what we've already printed | |
139 | out_size = len(child.before) |
|
162 | out_size = len(child.before) | |
140 | if res_idx==EOF_index: |
|
163 | if res_idx==EOF_index: | |
141 | break |
|
164 | break | |
142 | except KeyboardInterrupt: |
|
165 | except KeyboardInterrupt: | |
143 | # We need to send ^C to the process. The ascii code for '^C' is 3 |
|
166 | # We need to send ^C to the process. The ascii code for '^C' is 3 | |
144 | # (the character is known as ETX for 'End of Text', see |
|
167 | # (the character is known as ETX for 'End of Text', see | |
145 | # curses.ascii.ETX). |
|
168 | # curses.ascii.ETX). | |
146 | child.sendline(chr(3)) |
|
169 | child.sendline(chr(3)) | |
147 | # Read and print any more output the program might produce on its |
|
170 | # Read and print any more output the program might produce on its | |
148 | # way out. |
|
171 | # way out. | |
149 | try: |
|
172 | try: | |
150 | out_size = len(child.before) |
|
173 | out_size = len(child.before) | |
151 | child.expect_list(patterns, self.terminate_timeout) |
|
174 | child.expect_list(patterns, self.terminate_timeout) | |
152 | print(child.before[out_size:], end='') |
|
175 | print(child.before[out_size:], end='') | |
153 | except KeyboardInterrupt: |
|
176 | except KeyboardInterrupt: | |
154 | # Impatient users tend to type it multiple times |
|
177 | # Impatient users tend to type it multiple times | |
155 | pass |
|
178 | pass | |
156 | finally: |
|
179 | finally: | |
157 | # Ensure the subprocess really is terminated |
|
180 | # Ensure the subprocess really is terminated | |
158 | child.terminate(force=True) |
|
181 | child.terminate(force=True) | |
159 |
|
182 | |||
160 | def _make_cmd(self, cmd): |
|
183 | def _make_cmd(self, cmd): | |
161 | return '%s -c "%s"' % (self.sh, cmd) |
|
184 | return '%s -c "%s"' % (self.sh, cmd) | |
162 |
|
185 | |||
163 |
|
186 | |||
164 |
|
187 | # Make system() with a functional interface for outside use. Note that we use | ||
165 | # Make objects with a functional interface for outside use |
|
188 | # getoutput() from the _common utils, which is built on top of popen(). Using | |
166 | __ph = ProcessHandler() |
|
189 | # pexpect to get subprocess output produces difficult to parse output, since | |
167 |
|
190 | # programs think they are talking to a tty and produce highly formatted output | ||
168 | system = __ph.system |
|
191 | # (ls is a good example) that makes them hard. | |
169 | getoutput = __ph.getoutput |
|
192 | system = ProcessHandler().system |
General Comments 0
You need to be logged in to leave comments.
Login now