Show More
@@ -1,768 +1,773 b'' | |||||
1 | """DEPRECATED: Input handling and transformation machinery. |
|
1 | """DEPRECATED: Input handling and transformation machinery. | |
2 |
|
2 | |||
3 | This module was deprecated in IPython 7.0, in favour of inputtransformer2. |
|
3 | This module was deprecated in IPython 7.0, in favour of inputtransformer2. | |
4 |
|
4 | |||
5 | The first class in this module, :class:`InputSplitter`, is designed to tell when |
|
5 | The first class in this module, :class:`InputSplitter`, is designed to tell when | |
6 | input from a line-oriented frontend is complete and should be executed, and when |
|
6 | input from a line-oriented frontend is complete and should be executed, and when | |
7 | the user should be prompted for another line of code instead. The name 'input |
|
7 | the user should be prompted for another line of code instead. The name 'input | |
8 | splitter' is largely for historical reasons. |
|
8 | splitter' is largely for historical reasons. | |
9 |
|
9 | |||
10 | A companion, :class:`IPythonInputSplitter`, provides the same functionality but |
|
10 | A companion, :class:`IPythonInputSplitter`, provides the same functionality but | |
11 | with full support for the extended IPython syntax (magics, system calls, etc). |
|
11 | with full support for the extended IPython syntax (magics, system calls, etc). | |
12 | The code to actually do these transformations is in :mod:`IPython.core.inputtransformer`. |
|
12 | The code to actually do these transformations is in :mod:`IPython.core.inputtransformer`. | |
13 | :class:`IPythonInputSplitter` feeds the raw code to the transformers in order |
|
13 | :class:`IPythonInputSplitter` feeds the raw code to the transformers in order | |
14 | and stores the results. |
|
14 | and stores the results. | |
15 |
|
15 | |||
16 | For more details, see the class docstrings below. |
|
16 | For more details, see the class docstrings below. | |
17 | """ |
|
17 | """ | |
18 |
|
18 | |||
|
19 | from warnings import warn | |||
|
20 | ||||
|
21 | warn('IPython.core.inputsplitter is deprecated since IPython 7 in favor of `IPython.core.inputtransformer2`', | |||
|
22 | DeprecationWarning) | |||
|
23 | ||||
19 | # Copyright (c) IPython Development Team. |
|
24 | # Copyright (c) IPython Development Team. | |
20 | # Distributed under the terms of the Modified BSD License. |
|
25 | # Distributed under the terms of the Modified BSD License. | |
21 | import ast |
|
26 | import ast | |
22 | import codeop |
|
27 | import codeop | |
23 | import io |
|
28 | import io | |
24 | import re |
|
29 | import re | |
25 | import sys |
|
30 | import sys | |
26 | import tokenize |
|
31 | import tokenize | |
27 | import warnings |
|
32 | import warnings | |
28 |
|
33 | |||
29 | from IPython.utils.py3compat import cast_unicode |
|
34 | from IPython.utils.py3compat import cast_unicode | |
30 | from IPython.core.inputtransformer import (leading_indent, |
|
35 | from IPython.core.inputtransformer import (leading_indent, | |
31 | classic_prompt, |
|
36 | classic_prompt, | |
32 | ipy_prompt, |
|
37 | ipy_prompt, | |
33 | cellmagic, |
|
38 | cellmagic, | |
34 | assemble_logical_lines, |
|
39 | assemble_logical_lines, | |
35 | help_end, |
|
40 | help_end, | |
36 | escaped_commands, |
|
41 | escaped_commands, | |
37 | assign_from_magic, |
|
42 | assign_from_magic, | |
38 | assign_from_system, |
|
43 | assign_from_system, | |
39 | assemble_python_lines, |
|
44 | assemble_python_lines, | |
40 | ) |
|
45 | ) | |
41 |
|
46 | |||
42 | # These are available in this module for backwards compatibility. |
|
47 | # These are available in this module for backwards compatibility. | |
43 | from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP, |
|
48 | from IPython.core.inputtransformer import (ESC_SHELL, ESC_SH_CAP, ESC_HELP, | |
44 | ESC_HELP2, ESC_MAGIC, ESC_MAGIC2, |
|
49 | ESC_HELP2, ESC_MAGIC, ESC_MAGIC2, | |
45 | ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES) |
|
50 | ESC_QUOTE, ESC_QUOTE2, ESC_PAREN, ESC_SEQUENCES) | |
46 |
|
51 | |||
47 | #----------------------------------------------------------------------------- |
|
52 | #----------------------------------------------------------------------------- | |
48 | # Utilities |
|
53 | # Utilities | |
49 | #----------------------------------------------------------------------------- |
|
54 | #----------------------------------------------------------------------------- | |
50 |
|
55 | |||
51 | # FIXME: These are general-purpose utilities that later can be moved to the |
|
56 | # FIXME: These are general-purpose utilities that later can be moved to the | |
52 | # general ward. Kept here for now because we're being very strict about test |
|
57 | # general ward. Kept here for now because we're being very strict about test | |
53 | # coverage with this code, and this lets us ensure that we keep 100% coverage |
|
58 | # coverage with this code, and this lets us ensure that we keep 100% coverage | |
54 | # while developing. |
|
59 | # while developing. | |
55 |
|
60 | |||
56 | # compiled regexps for autoindent management |
|
61 | # compiled regexps for autoindent management | |
57 | dedent_re = re.compile('|'.join([ |
|
62 | dedent_re = re.compile('|'.join([ | |
58 | r'^\s+raise(\s.*)?$', # raise statement (+ space + other stuff, maybe) |
|
63 | r'^\s+raise(\s.*)?$', # raise statement (+ space + other stuff, maybe) | |
59 | r'^\s+raise\([^\)]*\).*$', # wacky raise with immediate open paren |
|
64 | r'^\s+raise\([^\)]*\).*$', # wacky raise with immediate open paren | |
60 | r'^\s+return(\s.*)?$', # normal return (+ space + other stuff, maybe) |
|
65 | r'^\s+return(\s.*)?$', # normal return (+ space + other stuff, maybe) | |
61 | r'^\s+return\([^\)]*\).*$', # wacky return with immediate open paren |
|
66 | r'^\s+return\([^\)]*\).*$', # wacky return with immediate open paren | |
62 | r'^\s+pass\s*$', # pass (optionally followed by trailing spaces) |
|
67 | r'^\s+pass\s*$', # pass (optionally followed by trailing spaces) | |
63 | r'^\s+break\s*$', # break (optionally followed by trailing spaces) |
|
68 | r'^\s+break\s*$', # break (optionally followed by trailing spaces) | |
64 | r'^\s+continue\s*$', # continue (optionally followed by trailing spaces) |
|
69 | r'^\s+continue\s*$', # continue (optionally followed by trailing spaces) | |
65 | ])) |
|
70 | ])) | |
66 | ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)') |
|
71 | ini_spaces_re = re.compile(r'^([ \t\r\f\v]+)') | |
67 |
|
72 | |||
68 | # regexp to match pure comment lines so we don't accidentally insert 'if 1:' |
|
73 | # regexp to match pure comment lines so we don't accidentally insert 'if 1:' | |
69 | # before pure comments |
|
74 | # before pure comments | |
70 | comment_line_re = re.compile('^\s*\#') |
|
75 | comment_line_re = re.compile('^\s*\#') | |
71 |
|
76 | |||
72 |
|
77 | |||
73 | def num_ini_spaces(s): |
|
78 | def num_ini_spaces(s): | |
74 | """Return the number of initial spaces in a string. |
|
79 | """Return the number of initial spaces in a string. | |
75 |
|
80 | |||
76 | Note that tabs are counted as a single space. For now, we do *not* support |
|
81 | Note that tabs are counted as a single space. For now, we do *not* support | |
77 | mixing of tabs and spaces in the user's input. |
|
82 | mixing of tabs and spaces in the user's input. | |
78 |
|
83 | |||
79 | Parameters |
|
84 | Parameters | |
80 | ---------- |
|
85 | ---------- | |
81 | s : string |
|
86 | s : string | |
82 |
|
87 | |||
83 | Returns |
|
88 | Returns | |
84 | ------- |
|
89 | ------- | |
85 | n : int |
|
90 | n : int | |
86 | """ |
|
91 | """ | |
87 |
|
92 | |||
88 | ini_spaces = ini_spaces_re.match(s) |
|
93 | ini_spaces = ini_spaces_re.match(s) | |
89 | if ini_spaces: |
|
94 | if ini_spaces: | |
90 | return ini_spaces.end() |
|
95 | return ini_spaces.end() | |
91 | else: |
|
96 | else: | |
92 | return 0 |
|
97 | return 0 | |
93 |
|
98 | |||
94 | # Fake token types for partial_tokenize: |
|
99 | # Fake token types for partial_tokenize: | |
95 | INCOMPLETE_STRING = tokenize.N_TOKENS |
|
100 | INCOMPLETE_STRING = tokenize.N_TOKENS | |
96 | IN_MULTILINE_STATEMENT = tokenize.N_TOKENS + 1 |
|
101 | IN_MULTILINE_STATEMENT = tokenize.N_TOKENS + 1 | |
97 |
|
102 | |||
98 | # The 2 classes below have the same API as TokenInfo, but don't try to look up |
|
103 | # The 2 classes below have the same API as TokenInfo, but don't try to look up | |
99 | # a token type name that they won't find. |
|
104 | # a token type name that they won't find. | |
100 | class IncompleteString: |
|
105 | class IncompleteString: | |
101 | type = exact_type = INCOMPLETE_STRING |
|
106 | type = exact_type = INCOMPLETE_STRING | |
102 | def __init__(self, s, start, end, line): |
|
107 | def __init__(self, s, start, end, line): | |
103 | self.s = s |
|
108 | self.s = s | |
104 | self.start = start |
|
109 | self.start = start | |
105 | self.end = end |
|
110 | self.end = end | |
106 | self.line = line |
|
111 | self.line = line | |
107 |
|
112 | |||
108 | class InMultilineStatement: |
|
113 | class InMultilineStatement: | |
109 | type = exact_type = IN_MULTILINE_STATEMENT |
|
114 | type = exact_type = IN_MULTILINE_STATEMENT | |
110 | def __init__(self, pos, line): |
|
115 | def __init__(self, pos, line): | |
111 | self.s = '' |
|
116 | self.s = '' | |
112 | self.start = self.end = pos |
|
117 | self.start = self.end = pos | |
113 | self.line = line |
|
118 | self.line = line | |
114 |
|
119 | |||
115 | def partial_tokens(s): |
|
120 | def partial_tokens(s): | |
116 | """Iterate over tokens from a possibly-incomplete string of code. |
|
121 | """Iterate over tokens from a possibly-incomplete string of code. | |
117 |
|
122 | |||
118 | This adds two special token types: INCOMPLETE_STRING and |
|
123 | This adds two special token types: INCOMPLETE_STRING and | |
119 | IN_MULTILINE_STATEMENT. These can only occur as the last token yielded, and |
|
124 | IN_MULTILINE_STATEMENT. These can only occur as the last token yielded, and | |
120 | represent the two main ways for code to be incomplete. |
|
125 | represent the two main ways for code to be incomplete. | |
121 | """ |
|
126 | """ | |
122 | readline = io.StringIO(s).readline |
|
127 | readline = io.StringIO(s).readline | |
123 | token = tokenize.TokenInfo(tokenize.NEWLINE, '', (1, 0), (1, 0), '') |
|
128 | token = tokenize.TokenInfo(tokenize.NEWLINE, '', (1, 0), (1, 0), '') | |
124 | try: |
|
129 | try: | |
125 | for token in tokenize.generate_tokens(readline): |
|
130 | for token in tokenize.generate_tokens(readline): | |
126 | yield token |
|
131 | yield token | |
127 | except tokenize.TokenError as e: |
|
132 | except tokenize.TokenError as e: | |
128 | # catch EOF error |
|
133 | # catch EOF error | |
129 | lines = s.splitlines(keepends=True) |
|
134 | lines = s.splitlines(keepends=True) | |
130 | end = len(lines), len(lines[-1]) |
|
135 | end = len(lines), len(lines[-1]) | |
131 | if 'multi-line string' in e.args[0]: |
|
136 | if 'multi-line string' in e.args[0]: | |
132 | l, c = start = token.end |
|
137 | l, c = start = token.end | |
133 | s = lines[l-1][c:] + ''.join(lines[l:]) |
|
138 | s = lines[l-1][c:] + ''.join(lines[l:]) | |
134 | yield IncompleteString(s, start, end, lines[-1]) |
|
139 | yield IncompleteString(s, start, end, lines[-1]) | |
135 | elif 'multi-line statement' in e.args[0]: |
|
140 | elif 'multi-line statement' in e.args[0]: | |
136 | yield InMultilineStatement(end, lines[-1]) |
|
141 | yield InMultilineStatement(end, lines[-1]) | |
137 | else: |
|
142 | else: | |
138 | raise |
|
143 | raise | |
139 |
|
144 | |||
140 | def find_next_indent(code): |
|
145 | def find_next_indent(code): | |
141 | """Find the number of spaces for the next line of indentation""" |
|
146 | """Find the number of spaces for the next line of indentation""" | |
142 | tokens = list(partial_tokens(code)) |
|
147 | tokens = list(partial_tokens(code)) | |
143 | if tokens[-1].type == tokenize.ENDMARKER: |
|
148 | if tokens[-1].type == tokenize.ENDMARKER: | |
144 | tokens.pop() |
|
149 | tokens.pop() | |
145 | if not tokens: |
|
150 | if not tokens: | |
146 | return 0 |
|
151 | return 0 | |
147 | while (tokens[-1].type in {tokenize.DEDENT, tokenize.NEWLINE, tokenize.COMMENT}): |
|
152 | while (tokens[-1].type in {tokenize.DEDENT, tokenize.NEWLINE, tokenize.COMMENT}): | |
148 | tokens.pop() |
|
153 | tokens.pop() | |
149 |
|
154 | |||
150 | if tokens[-1].type == INCOMPLETE_STRING: |
|
155 | if tokens[-1].type == INCOMPLETE_STRING: | |
151 | # Inside a multiline string |
|
156 | # Inside a multiline string | |
152 | return 0 |
|
157 | return 0 | |
153 |
|
158 | |||
154 | # Find the indents used before |
|
159 | # Find the indents used before | |
155 | prev_indents = [0] |
|
160 | prev_indents = [0] | |
156 | def _add_indent(n): |
|
161 | def _add_indent(n): | |
157 | if n != prev_indents[-1]: |
|
162 | if n != prev_indents[-1]: | |
158 | prev_indents.append(n) |
|
163 | prev_indents.append(n) | |
159 |
|
164 | |||
160 | tokiter = iter(tokens) |
|
165 | tokiter = iter(tokens) | |
161 | for tok in tokiter: |
|
166 | for tok in tokiter: | |
162 | if tok.type in {tokenize.INDENT, tokenize.DEDENT}: |
|
167 | if tok.type in {tokenize.INDENT, tokenize.DEDENT}: | |
163 | _add_indent(tok.end[1]) |
|
168 | _add_indent(tok.end[1]) | |
164 | elif (tok.type == tokenize.NL): |
|
169 | elif (tok.type == tokenize.NL): | |
165 | try: |
|
170 | try: | |
166 | _add_indent(next(tokiter).start[1]) |
|
171 | _add_indent(next(tokiter).start[1]) | |
167 | except StopIteration: |
|
172 | except StopIteration: | |
168 | break |
|
173 | break | |
169 |
|
174 | |||
170 | last_indent = prev_indents.pop() |
|
175 | last_indent = prev_indents.pop() | |
171 |
|
176 | |||
172 | # If we've just opened a multiline statement (e.g. 'a = ['), indent more |
|
177 | # If we've just opened a multiline statement (e.g. 'a = ['), indent more | |
173 | if tokens[-1].type == IN_MULTILINE_STATEMENT: |
|
178 | if tokens[-1].type == IN_MULTILINE_STATEMENT: | |
174 | if tokens[-2].exact_type in {tokenize.LPAR, tokenize.LSQB, tokenize.LBRACE}: |
|
179 | if tokens[-2].exact_type in {tokenize.LPAR, tokenize.LSQB, tokenize.LBRACE}: | |
175 | return last_indent + 4 |
|
180 | return last_indent + 4 | |
176 | return last_indent |
|
181 | return last_indent | |
177 |
|
182 | |||
178 | if tokens[-1].exact_type == tokenize.COLON: |
|
183 | if tokens[-1].exact_type == tokenize.COLON: | |
179 | # Line ends with colon - indent |
|
184 | # Line ends with colon - indent | |
180 | return last_indent + 4 |
|
185 | return last_indent + 4 | |
181 |
|
186 | |||
182 | if last_indent: |
|
187 | if last_indent: | |
183 | # Examine the last line for dedent cues - statements like return or |
|
188 | # Examine the last line for dedent cues - statements like return or | |
184 | # raise which normally end a block of code. |
|
189 | # raise which normally end a block of code. | |
185 | last_line_starts = 0 |
|
190 | last_line_starts = 0 | |
186 | for i, tok in enumerate(tokens): |
|
191 | for i, tok in enumerate(tokens): | |
187 | if tok.type == tokenize.NEWLINE: |
|
192 | if tok.type == tokenize.NEWLINE: | |
188 | last_line_starts = i + 1 |
|
193 | last_line_starts = i + 1 | |
189 |
|
194 | |||
190 | last_line_tokens = tokens[last_line_starts:] |
|
195 | last_line_tokens = tokens[last_line_starts:] | |
191 | names = [t.string for t in last_line_tokens if t.type == tokenize.NAME] |
|
196 | names = [t.string for t in last_line_tokens if t.type == tokenize.NAME] | |
192 | if names and names[0] in {'raise', 'return', 'pass', 'break', 'continue'}: |
|
197 | if names and names[0] in {'raise', 'return', 'pass', 'break', 'continue'}: | |
193 | # Find the most recent indentation less than the current level |
|
198 | # Find the most recent indentation less than the current level | |
194 | for indent in reversed(prev_indents): |
|
199 | for indent in reversed(prev_indents): | |
195 | if indent < last_indent: |
|
200 | if indent < last_indent: | |
196 | return indent |
|
201 | return indent | |
197 |
|
202 | |||
198 | return last_indent |
|
203 | return last_indent | |
199 |
|
204 | |||
200 |
|
205 | |||
201 | def last_blank(src): |
|
206 | def last_blank(src): | |
202 | """Determine if the input source ends in a blank. |
|
207 | """Determine if the input source ends in a blank. | |
203 |
|
208 | |||
204 | A blank is either a newline or a line consisting of whitespace. |
|
209 | A blank is either a newline or a line consisting of whitespace. | |
205 |
|
210 | |||
206 | Parameters |
|
211 | Parameters | |
207 | ---------- |
|
212 | ---------- | |
208 | src : string |
|
213 | src : string | |
209 | A single or multiline string. |
|
214 | A single or multiline string. | |
210 | """ |
|
215 | """ | |
211 | if not src: return False |
|
216 | if not src: return False | |
212 | ll = src.splitlines()[-1] |
|
217 | ll = src.splitlines()[-1] | |
213 | return (ll == '') or ll.isspace() |
|
218 | return (ll == '') or ll.isspace() | |
214 |
|
219 | |||
215 |
|
220 | |||
216 | last_two_blanks_re = re.compile(r'\n\s*\n\s*$', re.MULTILINE) |
|
221 | last_two_blanks_re = re.compile(r'\n\s*\n\s*$', re.MULTILINE) | |
217 | last_two_blanks_re2 = re.compile(r'.+\n\s*\n\s+$', re.MULTILINE) |
|
222 | last_two_blanks_re2 = re.compile(r'.+\n\s*\n\s+$', re.MULTILINE) | |
218 |
|
223 | |||
219 | def last_two_blanks(src): |
|
224 | def last_two_blanks(src): | |
220 | """Determine if the input source ends in two blanks. |
|
225 | """Determine if the input source ends in two blanks. | |
221 |
|
226 | |||
222 | A blank is either a newline or a line consisting of whitespace. |
|
227 | A blank is either a newline or a line consisting of whitespace. | |
223 |
|
228 | |||
224 | Parameters |
|
229 | Parameters | |
225 | ---------- |
|
230 | ---------- | |
226 | src : string |
|
231 | src : string | |
227 | A single or multiline string. |
|
232 | A single or multiline string. | |
228 | """ |
|
233 | """ | |
229 | if not src: return False |
|
234 | if not src: return False | |
230 | # The logic here is tricky: I couldn't get a regexp to work and pass all |
|
235 | # The logic here is tricky: I couldn't get a regexp to work and pass all | |
231 | # the tests, so I took a different approach: split the source by lines, |
|
236 | # the tests, so I took a different approach: split the source by lines, | |
232 | # grab the last two and prepend '###\n' as a stand-in for whatever was in |
|
237 | # grab the last two and prepend '###\n' as a stand-in for whatever was in | |
233 | # the body before the last two lines. Then, with that structure, it's |
|
238 | # the body before the last two lines. Then, with that structure, it's | |
234 | # possible to analyze with two regexps. Not the most elegant solution, but |
|
239 | # possible to analyze with two regexps. Not the most elegant solution, but | |
235 | # it works. If anyone tries to change this logic, make sure to validate |
|
240 | # it works. If anyone tries to change this logic, make sure to validate | |
236 | # the whole test suite first! |
|
241 | # the whole test suite first! | |
237 | new_src = '\n'.join(['###\n'] + src.splitlines()[-2:]) |
|
242 | new_src = '\n'.join(['###\n'] + src.splitlines()[-2:]) | |
238 | return (bool(last_two_blanks_re.match(new_src)) or |
|
243 | return (bool(last_two_blanks_re.match(new_src)) or | |
239 | bool(last_two_blanks_re2.match(new_src)) ) |
|
244 | bool(last_two_blanks_re2.match(new_src)) ) | |
240 |
|
245 | |||
241 |
|
246 | |||
242 | def remove_comments(src): |
|
247 | def remove_comments(src): | |
243 | """Remove all comments from input source. |
|
248 | """Remove all comments from input source. | |
244 |
|
249 | |||
245 | Note: comments are NOT recognized inside of strings! |
|
250 | Note: comments are NOT recognized inside of strings! | |
246 |
|
251 | |||
247 | Parameters |
|
252 | Parameters | |
248 | ---------- |
|
253 | ---------- | |
249 | src : string |
|
254 | src : string | |
250 | A single or multiline input string. |
|
255 | A single or multiline input string. | |
251 |
|
256 | |||
252 | Returns |
|
257 | Returns | |
253 | ------- |
|
258 | ------- | |
254 | String with all Python comments removed. |
|
259 | String with all Python comments removed. | |
255 | """ |
|
260 | """ | |
256 |
|
261 | |||
257 | return re.sub('#.*', '', src) |
|
262 | return re.sub('#.*', '', src) | |
258 |
|
263 | |||
259 |
|
264 | |||
260 | def get_input_encoding(): |
|
265 | def get_input_encoding(): | |
261 | """Return the default standard input encoding. |
|
266 | """Return the default standard input encoding. | |
262 |
|
267 | |||
263 | If sys.stdin has no encoding, 'ascii' is returned.""" |
|
268 | If sys.stdin has no encoding, 'ascii' is returned.""" | |
264 | # There are strange environments for which sys.stdin.encoding is None. We |
|
269 | # There are strange environments for which sys.stdin.encoding is None. We | |
265 | # ensure that a valid encoding is returned. |
|
270 | # ensure that a valid encoding is returned. | |
266 | encoding = getattr(sys.stdin, 'encoding', None) |
|
271 | encoding = getattr(sys.stdin, 'encoding', None) | |
267 | if encoding is None: |
|
272 | if encoding is None: | |
268 | encoding = 'ascii' |
|
273 | encoding = 'ascii' | |
269 | return encoding |
|
274 | return encoding | |
270 |
|
275 | |||
271 | #----------------------------------------------------------------------------- |
|
276 | #----------------------------------------------------------------------------- | |
272 | # Classes and functions for normal Python syntax handling |
|
277 | # Classes and functions for normal Python syntax handling | |
273 | #----------------------------------------------------------------------------- |
|
278 | #----------------------------------------------------------------------------- | |
274 |
|
279 | |||
275 | class InputSplitter(object): |
|
280 | class InputSplitter(object): | |
276 | r"""An object that can accumulate lines of Python source before execution. |
|
281 | r"""An object that can accumulate lines of Python source before execution. | |
277 |
|
282 | |||
278 | This object is designed to be fed python source line-by-line, using |
|
283 | This object is designed to be fed python source line-by-line, using | |
279 | :meth:`push`. It will return on each push whether the currently pushed |
|
284 | :meth:`push`. It will return on each push whether the currently pushed | |
280 | code could be executed already. In addition, it provides a method called |
|
285 | code could be executed already. In addition, it provides a method called | |
281 | :meth:`push_accepts_more` that can be used to query whether more input |
|
286 | :meth:`push_accepts_more` that can be used to query whether more input | |
282 | can be pushed into a single interactive block. |
|
287 | can be pushed into a single interactive block. | |
283 |
|
288 | |||
284 | This is a simple example of how an interactive terminal-based client can use |
|
289 | This is a simple example of how an interactive terminal-based client can use | |
285 | this tool:: |
|
290 | this tool:: | |
286 |
|
291 | |||
287 | isp = InputSplitter() |
|
292 | isp = InputSplitter() | |
288 | while isp.push_accepts_more(): |
|
293 | while isp.push_accepts_more(): | |
289 | indent = ' '*isp.indent_spaces |
|
294 | indent = ' '*isp.indent_spaces | |
290 | prompt = '>>> ' + indent |
|
295 | prompt = '>>> ' + indent | |
291 | line = indent + raw_input(prompt) |
|
296 | line = indent + raw_input(prompt) | |
292 | isp.push(line) |
|
297 | isp.push(line) | |
293 | print 'Input source was:\n', isp.source_reset(), |
|
298 | print 'Input source was:\n', isp.source_reset(), | |
294 | """ |
|
299 | """ | |
295 | # A cache for storing the current indentation |
|
300 | # A cache for storing the current indentation | |
296 | # The first value stores the most recently processed source input |
|
301 | # The first value stores the most recently processed source input | |
297 | # The second value is the number of spaces for the current indentation |
|
302 | # The second value is the number of spaces for the current indentation | |
298 | # If self.source matches the first value, the second value is a valid |
|
303 | # If self.source matches the first value, the second value is a valid | |
299 | # current indentation. Otherwise, the cache is invalid and the indentation |
|
304 | # current indentation. Otherwise, the cache is invalid and the indentation | |
300 | # must be recalculated. |
|
305 | # must be recalculated. | |
301 | _indent_spaces_cache = None, None |
|
306 | _indent_spaces_cache = None, None | |
302 | # String, indicating the default input encoding. It is computed by default |
|
307 | # String, indicating the default input encoding. It is computed by default | |
303 | # at initialization time via get_input_encoding(), but it can be reset by a |
|
308 | # at initialization time via get_input_encoding(), but it can be reset by a | |
304 | # client with specific knowledge of the encoding. |
|
309 | # client with specific knowledge of the encoding. | |
305 | encoding = '' |
|
310 | encoding = '' | |
306 | # String where the current full source input is stored, properly encoded. |
|
311 | # String where the current full source input is stored, properly encoded. | |
307 | # Reading this attribute is the normal way of querying the currently pushed |
|
312 | # Reading this attribute is the normal way of querying the currently pushed | |
308 | # source code, that has been properly encoded. |
|
313 | # source code, that has been properly encoded. | |
309 | source = '' |
|
314 | source = '' | |
310 | # Code object corresponding to the current source. It is automatically |
|
315 | # Code object corresponding to the current source. It is automatically | |
311 | # synced to the source, so it can be queried at any time to obtain the code |
|
316 | # synced to the source, so it can be queried at any time to obtain the code | |
312 | # object; it will be None if the source doesn't compile to valid Python. |
|
317 | # object; it will be None if the source doesn't compile to valid Python. | |
313 | code = None |
|
318 | code = None | |
314 |
|
319 | |||
315 | # Private attributes |
|
320 | # Private attributes | |
316 |
|
321 | |||
317 | # List with lines of input accumulated so far |
|
322 | # List with lines of input accumulated so far | |
318 | _buffer = None |
|
323 | _buffer = None | |
319 | # Command compiler |
|
324 | # Command compiler | |
320 | _compile = None |
|
325 | _compile = None | |
321 | # Boolean indicating whether the current block is complete |
|
326 | # Boolean indicating whether the current block is complete | |
322 | _is_complete = None |
|
327 | _is_complete = None | |
323 | # Boolean indicating whether the current block has an unrecoverable syntax error |
|
328 | # Boolean indicating whether the current block has an unrecoverable syntax error | |
324 | _is_invalid = False |
|
329 | _is_invalid = False | |
325 |
|
330 | |||
326 | def __init__(self): |
|
331 | def __init__(self): | |
327 | """Create a new InputSplitter instance. |
|
332 | """Create a new InputSplitter instance. | |
328 | """ |
|
333 | """ | |
329 | self._buffer = [] |
|
334 | self._buffer = [] | |
330 | self._compile = codeop.CommandCompiler() |
|
335 | self._compile = codeop.CommandCompiler() | |
331 | self.encoding = get_input_encoding() |
|
336 | self.encoding = get_input_encoding() | |
332 |
|
337 | |||
333 | def reset(self): |
|
338 | def reset(self): | |
334 | """Reset the input buffer and associated state.""" |
|
339 | """Reset the input buffer and associated state.""" | |
335 | self._buffer[:] = [] |
|
340 | self._buffer[:] = [] | |
336 | self.source = '' |
|
341 | self.source = '' | |
337 | self.code = None |
|
342 | self.code = None | |
338 | self._is_complete = False |
|
343 | self._is_complete = False | |
339 | self._is_invalid = False |
|
344 | self._is_invalid = False | |
340 |
|
345 | |||
341 | def source_reset(self): |
|
346 | def source_reset(self): | |
342 | """Return the input source and perform a full reset. |
|
347 | """Return the input source and perform a full reset. | |
343 | """ |
|
348 | """ | |
344 | out = self.source |
|
349 | out = self.source | |
345 | self.reset() |
|
350 | self.reset() | |
346 | return out |
|
351 | return out | |
347 |
|
352 | |||
348 | def check_complete(self, source): |
|
353 | def check_complete(self, source): | |
349 | """Return whether a block of code is ready to execute, or should be continued |
|
354 | """Return whether a block of code is ready to execute, or should be continued | |
350 |
|
355 | |||
351 | This is a non-stateful API, and will reset the state of this InputSplitter. |
|
356 | This is a non-stateful API, and will reset the state of this InputSplitter. | |
352 |
|
357 | |||
353 | Parameters |
|
358 | Parameters | |
354 | ---------- |
|
359 | ---------- | |
355 | source : string |
|
360 | source : string | |
356 | Python input code, which can be multiline. |
|
361 | Python input code, which can be multiline. | |
357 |
|
362 | |||
358 | Returns |
|
363 | Returns | |
359 | ------- |
|
364 | ------- | |
360 | status : str |
|
365 | status : str | |
361 | One of 'complete', 'incomplete', or 'invalid' if source is not a |
|
366 | One of 'complete', 'incomplete', or 'invalid' if source is not a | |
362 | prefix of valid code. |
|
367 | prefix of valid code. | |
363 | indent_spaces : int or None |
|
368 | indent_spaces : int or None | |
364 | The number of spaces by which to indent the next line of code. If |
|
369 | The number of spaces by which to indent the next line of code. If | |
365 | status is not 'incomplete', this is None. |
|
370 | status is not 'incomplete', this is None. | |
366 | """ |
|
371 | """ | |
367 | self.reset() |
|
372 | self.reset() | |
368 | try: |
|
373 | try: | |
369 | self.push(source) |
|
374 | self.push(source) | |
370 | except SyntaxError: |
|
375 | except SyntaxError: | |
371 | # Transformers in IPythonInputSplitter can raise SyntaxError, |
|
376 | # Transformers in IPythonInputSplitter can raise SyntaxError, | |
372 | # which push() will not catch. |
|
377 | # which push() will not catch. | |
373 | return 'invalid', None |
|
378 | return 'invalid', None | |
374 | else: |
|
379 | else: | |
375 | if self._is_invalid: |
|
380 | if self._is_invalid: | |
376 | return 'invalid', None |
|
381 | return 'invalid', None | |
377 | elif self.push_accepts_more(): |
|
382 | elif self.push_accepts_more(): | |
378 | return 'incomplete', self.get_indent_spaces() |
|
383 | return 'incomplete', self.get_indent_spaces() | |
379 | else: |
|
384 | else: | |
380 | return 'complete', None |
|
385 | return 'complete', None | |
381 | finally: |
|
386 | finally: | |
382 | self.reset() |
|
387 | self.reset() | |
383 |
|
388 | |||
384 | def push(self, lines): |
|
389 | def push(self, lines): | |
385 | """Push one or more lines of input. |
|
390 | """Push one or more lines of input. | |
386 |
|
391 | |||
387 | This stores the given lines and returns a status code indicating |
|
392 | This stores the given lines and returns a status code indicating | |
388 | whether the code forms a complete Python block or not. |
|
393 | whether the code forms a complete Python block or not. | |
389 |
|
394 | |||
390 | Any exceptions generated in compilation are swallowed, but if an |
|
395 | Any exceptions generated in compilation are swallowed, but if an | |
391 | exception was produced, the method returns True. |
|
396 | exception was produced, the method returns True. | |
392 |
|
397 | |||
393 | Parameters |
|
398 | Parameters | |
394 | ---------- |
|
399 | ---------- | |
395 | lines : string |
|
400 | lines : string | |
396 | One or more lines of Python input. |
|
401 | One or more lines of Python input. | |
397 |
|
402 | |||
398 | Returns |
|
403 | Returns | |
399 | ------- |
|
404 | ------- | |
400 | is_complete : boolean |
|
405 | is_complete : boolean | |
401 | True if the current input source (the result of the current input |
|
406 | True if the current input source (the result of the current input | |
402 | plus prior inputs) forms a complete Python execution block. Note that |
|
407 | plus prior inputs) forms a complete Python execution block. Note that | |
403 | this value is also stored as a private attribute (``_is_complete``), so it |
|
408 | this value is also stored as a private attribute (``_is_complete``), so it | |
404 | can be queried at any time. |
|
409 | can be queried at any time. | |
405 | """ |
|
410 | """ | |
406 | self._store(lines) |
|
411 | self._store(lines) | |
407 | source = self.source |
|
412 | source = self.source | |
408 |
|
413 | |||
409 | # Before calling _compile(), reset the code object to None so that if an |
|
414 | # Before calling _compile(), reset the code object to None so that if an | |
410 | # exception is raised in compilation, we don't mislead by having |
|
415 | # exception is raised in compilation, we don't mislead by having | |
411 | # inconsistent code/source attributes. |
|
416 | # inconsistent code/source attributes. | |
412 | self.code, self._is_complete = None, None |
|
417 | self.code, self._is_complete = None, None | |
413 | self._is_invalid = False |
|
418 | self._is_invalid = False | |
414 |
|
419 | |||
415 | # Honor termination lines properly |
|
420 | # Honor termination lines properly | |
416 | if source.endswith('\\\n'): |
|
421 | if source.endswith('\\\n'): | |
417 | return False |
|
422 | return False | |
418 |
|
423 | |||
419 | try: |
|
424 | try: | |
420 | with warnings.catch_warnings(): |
|
425 | with warnings.catch_warnings(): | |
421 | warnings.simplefilter('error', SyntaxWarning) |
|
426 | warnings.simplefilter('error', SyntaxWarning) | |
422 | self.code = self._compile(source, symbol="exec") |
|
427 | self.code = self._compile(source, symbol="exec") | |
423 | # Invalid syntax can produce any of a number of different errors from |
|
428 | # Invalid syntax can produce any of a number of different errors from | |
424 | # inside the compiler, so we have to catch them all. Syntax errors |
|
429 | # inside the compiler, so we have to catch them all. Syntax errors | |
425 | # immediately produce a 'ready' block, so the invalid Python can be |
|
430 | # immediately produce a 'ready' block, so the invalid Python can be | |
426 | # sent to the kernel for evaluation with possible ipython |
|
431 | # sent to the kernel for evaluation with possible ipython | |
427 | # special-syntax conversion. |
|
432 | # special-syntax conversion. | |
428 | except (SyntaxError, OverflowError, ValueError, TypeError, |
|
433 | except (SyntaxError, OverflowError, ValueError, TypeError, | |
429 | MemoryError, SyntaxWarning): |
|
434 | MemoryError, SyntaxWarning): | |
430 | self._is_complete = True |
|
435 | self._is_complete = True | |
431 | self._is_invalid = True |
|
436 | self._is_invalid = True | |
432 | else: |
|
437 | else: | |
433 | # Compilation didn't produce any exceptions (though it may not have |
|
438 | # Compilation didn't produce any exceptions (though it may not have | |
434 | # given a complete code object) |
|
439 | # given a complete code object) | |
435 | self._is_complete = self.code is not None |
|
440 | self._is_complete = self.code is not None | |
436 |
|
441 | |||
437 | return self._is_complete |
|
442 | return self._is_complete | |
438 |
|
443 | |||
439 | def push_accepts_more(self): |
|
444 | def push_accepts_more(self): | |
440 | """Return whether a block of interactive input can accept more input. |
|
445 | """Return whether a block of interactive input can accept more input. | |
441 |
|
446 | |||
442 | This method is meant to be used by line-oriented frontends, who need to |
|
447 | This method is meant to be used by line-oriented frontends, who need to | |
443 | guess whether a block is complete or not based solely on prior and |
|
448 | guess whether a block is complete or not based solely on prior and | |
444 | current input lines. The InputSplitter considers it has a complete |
|
449 | current input lines. The InputSplitter considers it has a complete | |
445 | interactive block and will not accept more input when either: |
|
450 | interactive block and will not accept more input when either: | |
446 |
|
451 | |||
447 | * A SyntaxError is raised |
|
452 | * A SyntaxError is raised | |
448 |
|
453 | |||
449 | * The code is complete and consists of a single line or a single |
|
454 | * The code is complete and consists of a single line or a single | |
450 | non-compound statement |
|
455 | non-compound statement | |
451 |
|
456 | |||
452 | * The code is complete and has a blank line at the end |
|
457 | * The code is complete and has a blank line at the end | |
453 |
|
458 | |||
454 | If the current input produces a syntax error, this method immediately |
|
459 | If the current input produces a syntax error, this method immediately | |
455 | returns False but does *not* raise the syntax error exception, as |
|
460 | returns False but does *not* raise the syntax error exception, as | |
456 | typically clients will want to send invalid syntax to an execution |
|
461 | typically clients will want to send invalid syntax to an execution | |
457 | backend which might convert the invalid syntax into valid Python via |
|
462 | backend which might convert the invalid syntax into valid Python via | |
458 | one of the dynamic IPython mechanisms. |
|
463 | one of the dynamic IPython mechanisms. | |
459 | """ |
|
464 | """ | |
460 |
|
465 | |||
461 | # With incomplete input, unconditionally accept more |
|
466 | # With incomplete input, unconditionally accept more | |
462 | # A syntax error also sets _is_complete to True - see push() |
|
467 | # A syntax error also sets _is_complete to True - see push() | |
463 | if not self._is_complete: |
|
468 | if not self._is_complete: | |
464 | #print("Not complete") # debug |
|
469 | #print("Not complete") # debug | |
465 | return True |
|
470 | return True | |
466 |
|
471 | |||
467 | # The user can make any (complete) input execute by leaving a blank line |
|
472 | # The user can make any (complete) input execute by leaving a blank line | |
468 | last_line = self.source.splitlines()[-1] |
|
473 | last_line = self.source.splitlines()[-1] | |
469 | if (not last_line) or last_line.isspace(): |
|
474 | if (not last_line) or last_line.isspace(): | |
470 | #print("Blank line") # debug |
|
475 | #print("Blank line") # debug | |
471 | return False |
|
476 | return False | |
472 |
|
477 | |||
473 | # If there's just a single line or AST node, and we're flush left, as is |
|
478 | # If there's just a single line or AST node, and we're flush left, as is | |
474 | # the case after a simple statement such as 'a=1', we want to execute it |
|
479 | # the case after a simple statement such as 'a=1', we want to execute it | |
475 | # straight away. |
|
480 | # straight away. | |
476 | if self.get_indent_spaces() == 0: |
|
481 | if self.get_indent_spaces() == 0: | |
477 | if len(self.source.splitlines()) <= 1: |
|
482 | if len(self.source.splitlines()) <= 1: | |
478 | return False |
|
483 | return False | |
479 |
|
484 | |||
480 | try: |
|
485 | try: | |
481 | code_ast = ast.parse(u''.join(self._buffer)) |
|
486 | code_ast = ast.parse(u''.join(self._buffer)) | |
482 | except Exception: |
|
487 | except Exception: | |
483 | #print("Can't parse AST") # debug |
|
488 | #print("Can't parse AST") # debug | |
484 | return False |
|
489 | return False | |
485 | else: |
|
490 | else: | |
486 | if len(code_ast.body) == 1 and \ |
|
491 | if len(code_ast.body) == 1 and \ | |
487 | not hasattr(code_ast.body[0], 'body'): |
|
492 | not hasattr(code_ast.body[0], 'body'): | |
488 | #print("Simple statement") # debug |
|
493 | #print("Simple statement") # debug | |
489 | return False |
|
494 | return False | |
490 |
|
495 | |||
491 | # General fallback - accept more code |
|
496 | # General fallback - accept more code | |
492 | return True |
|
497 | return True | |
493 |
|
498 | |||
494 | def get_indent_spaces(self): |
|
499 | def get_indent_spaces(self): | |
495 | sourcefor, n = self._indent_spaces_cache |
|
500 | sourcefor, n = self._indent_spaces_cache | |
496 | if sourcefor == self.source: |
|
501 | if sourcefor == self.source: | |
497 | return n |
|
502 | return n | |
498 |
|
503 | |||
499 | # self.source always has a trailing newline |
|
504 | # self.source always has a trailing newline | |
500 | n = find_next_indent(self.source[:-1]) |
|
505 | n = find_next_indent(self.source[:-1]) | |
501 | self._indent_spaces_cache = (self.source, n) |
|
506 | self._indent_spaces_cache = (self.source, n) | |
502 | return n |
|
507 | return n | |
503 |
|
508 | |||
504 | # Backwards compatibility. I think all code that used .indent_spaces was |
|
509 | # Backwards compatibility. I think all code that used .indent_spaces was | |
505 | # inside IPython, but we can leave this here until IPython 7 in case any |
|
510 | # inside IPython, but we can leave this here until IPython 7 in case any | |
506 | # other modules are using it. -TK, November 2017 |
|
511 | # other modules are using it. -TK, November 2017 | |
507 | indent_spaces = property(get_indent_spaces) |
|
512 | indent_spaces = property(get_indent_spaces) | |
508 |
|
513 | |||
509 | def _store(self, lines, buffer=None, store='source'): |
|
514 | def _store(self, lines, buffer=None, store='source'): | |
510 | """Store one or more lines of input. |
|
515 | """Store one or more lines of input. | |
511 |
|
516 | |||
512 | If input lines are not newline-terminated, a newline is automatically |
|
517 | If input lines are not newline-terminated, a newline is automatically | |
513 | appended.""" |
|
518 | appended.""" | |
514 |
|
519 | |||
515 | if buffer is None: |
|
520 | if buffer is None: | |
516 | buffer = self._buffer |
|
521 | buffer = self._buffer | |
517 |
|
522 | |||
518 | if lines.endswith('\n'): |
|
523 | if lines.endswith('\n'): | |
519 | buffer.append(lines) |
|
524 | buffer.append(lines) | |
520 | else: |
|
525 | else: | |
521 | buffer.append(lines+'\n') |
|
526 | buffer.append(lines+'\n') | |
522 | setattr(self, store, self._set_source(buffer)) |
|
527 | setattr(self, store, self._set_source(buffer)) | |
523 |
|
528 | |||
524 | def _set_source(self, buffer): |
|
529 | def _set_source(self, buffer): | |
525 | return u''.join(buffer) |
|
530 | return u''.join(buffer) | |
526 |
|
531 | |||
527 |
|
532 | |||
528 | class IPythonInputSplitter(InputSplitter): |
|
533 | class IPythonInputSplitter(InputSplitter): | |
529 | """An input splitter that recognizes all of IPython's special syntax.""" |
|
534 | """An input splitter that recognizes all of IPython's special syntax.""" | |
530 |
|
535 | |||
531 | # String with raw, untransformed input. |
|
536 | # String with raw, untransformed input. | |
532 | source_raw = '' |
|
537 | source_raw = '' | |
533 |
|
538 | |||
534 | # Flag to track when a transformer has stored input that it hasn't given |
|
539 | # Flag to track when a transformer has stored input that it hasn't given | |
535 | # back yet. |
|
540 | # back yet. | |
536 | transformer_accumulating = False |
|
541 | transformer_accumulating = False | |
537 |
|
542 | |||
538 | # Flag to track when assemble_python_lines has stored input that it hasn't |
|
543 | # Flag to track when assemble_python_lines has stored input that it hasn't | |
539 | # given back yet. |
|
544 | # given back yet. | |
540 | within_python_line = False |
|
545 | within_python_line = False | |
541 |
|
546 | |||
542 | # Private attributes |
|
547 | # Private attributes | |
543 |
|
548 | |||
544 | # List with lines of raw input accumulated so far. |
|
549 | # List with lines of raw input accumulated so far. | |
545 | _buffer_raw = None |
|
550 | _buffer_raw = None | |
546 |
|
551 | |||
547 | def __init__(self, line_input_checker=True, physical_line_transforms=None, |
|
552 | def __init__(self, line_input_checker=True, physical_line_transforms=None, | |
548 | logical_line_transforms=None, python_line_transforms=None): |
|
553 | logical_line_transforms=None, python_line_transforms=None): | |
549 | super(IPythonInputSplitter, self).__init__() |
|
554 | super(IPythonInputSplitter, self).__init__() | |
550 | self._buffer_raw = [] |
|
555 | self._buffer_raw = [] | |
551 | self._validate = True |
|
556 | self._validate = True | |
552 |
|
557 | |||
553 | if physical_line_transforms is not None: |
|
558 | if physical_line_transforms is not None: | |
554 | self.physical_line_transforms = physical_line_transforms |
|
559 | self.physical_line_transforms = physical_line_transforms | |
555 | else: |
|
560 | else: | |
556 | self.physical_line_transforms = [ |
|
561 | self.physical_line_transforms = [ | |
557 | leading_indent(), |
|
562 | leading_indent(), | |
558 | classic_prompt(), |
|
563 | classic_prompt(), | |
559 | ipy_prompt(), |
|
564 | ipy_prompt(), | |
560 | cellmagic(end_on_blank_line=line_input_checker), |
|
565 | cellmagic(end_on_blank_line=line_input_checker), | |
561 | ] |
|
566 | ] | |
562 |
|
567 | |||
563 | self.assemble_logical_lines = assemble_logical_lines() |
|
568 | self.assemble_logical_lines = assemble_logical_lines() | |
564 | if logical_line_transforms is not None: |
|
569 | if logical_line_transforms is not None: | |
565 | self.logical_line_transforms = logical_line_transforms |
|
570 | self.logical_line_transforms = logical_line_transforms | |
566 | else: |
|
571 | else: | |
567 | self.logical_line_transforms = [ |
|
572 | self.logical_line_transforms = [ | |
568 | help_end(), |
|
573 | help_end(), | |
569 | escaped_commands(), |
|
574 | escaped_commands(), | |
570 | assign_from_magic(), |
|
575 | assign_from_magic(), | |
571 | assign_from_system(), |
|
576 | assign_from_system(), | |
572 | ] |
|
577 | ] | |
573 |
|
578 | |||
574 | self.assemble_python_lines = assemble_python_lines() |
|
579 | self.assemble_python_lines = assemble_python_lines() | |
575 | if python_line_transforms is not None: |
|
580 | if python_line_transforms is not None: | |
576 | self.python_line_transforms = python_line_transforms |
|
581 | self.python_line_transforms = python_line_transforms | |
577 | else: |
|
582 | else: | |
578 | # We don't use any of these at present |
|
583 | # We don't use any of these at present | |
579 | self.python_line_transforms = [] |
|
584 | self.python_line_transforms = [] | |
580 |
|
585 | |||
581 | @property |
|
586 | @property | |
582 | def transforms(self): |
|
587 | def transforms(self): | |
583 | "Quick access to all transformers." |
|
588 | "Quick access to all transformers." | |
584 | return self.physical_line_transforms + \ |
|
589 | return self.physical_line_transforms + \ | |
585 | [self.assemble_logical_lines] + self.logical_line_transforms + \ |
|
590 | [self.assemble_logical_lines] + self.logical_line_transforms + \ | |
586 | [self.assemble_python_lines] + self.python_line_transforms |
|
591 | [self.assemble_python_lines] + self.python_line_transforms | |
587 |
|
592 | |||
588 | @property |
|
593 | @property | |
589 | def transforms_in_use(self): |
|
594 | def transforms_in_use(self): | |
590 | """Transformers, excluding logical line transformers if we're in a |
|
595 | """Transformers, excluding logical line transformers if we're in a | |
591 | Python line.""" |
|
596 | Python line.""" | |
592 | t = self.physical_line_transforms[:] |
|
597 | t = self.physical_line_transforms[:] | |
593 | if not self.within_python_line: |
|
598 | if not self.within_python_line: | |
594 | t += [self.assemble_logical_lines] + self.logical_line_transforms |
|
599 | t += [self.assemble_logical_lines] + self.logical_line_transforms | |
595 | return t + [self.assemble_python_lines] + self.python_line_transforms |
|
600 | return t + [self.assemble_python_lines] + self.python_line_transforms | |
596 |
|
601 | |||
597 | def reset(self): |
|
602 | def reset(self): | |
598 | """Reset the input buffer and associated state.""" |
|
603 | """Reset the input buffer and associated state.""" | |
599 | super(IPythonInputSplitter, self).reset() |
|
604 | super(IPythonInputSplitter, self).reset() | |
600 | self._buffer_raw[:] = [] |
|
605 | self._buffer_raw[:] = [] | |
601 | self.source_raw = '' |
|
606 | self.source_raw = '' | |
602 | self.transformer_accumulating = False |
|
607 | self.transformer_accumulating = False | |
603 | self.within_python_line = False |
|
608 | self.within_python_line = False | |
604 |
|
609 | |||
605 | for t in self.transforms: |
|
610 | for t in self.transforms: | |
606 | try: |
|
611 | try: | |
607 | t.reset() |
|
612 | t.reset() | |
608 | except SyntaxError: |
|
613 | except SyntaxError: | |
609 | # Nothing that calls reset() expects to handle transformer |
|
614 | # Nothing that calls reset() expects to handle transformer | |
610 | # errors |
|
615 | # errors | |
611 | pass |
|
616 | pass | |
612 |
|
617 | |||
613 | def flush_transformers(self): |
|
618 | def flush_transformers(self): | |
614 | def _flush(transform, outs): |
|
619 | def _flush(transform, outs): | |
615 | """yield transformed lines |
|
620 | """yield transformed lines | |
616 |
|
621 | |||
617 | always strings, never None |
|
622 | always strings, never None | |
618 |
|
623 | |||
619 | transform: the current transform |
|
624 | transform: the current transform | |
620 | outs: an iterable of previously transformed inputs. |
|
625 | outs: an iterable of previously transformed inputs. | |
621 | Each may be multiline, which will be passed |
|
626 | Each may be multiline, which will be passed | |
622 | one line at a time to transform. |
|
627 | one line at a time to transform. | |
623 | """ |
|
628 | """ | |
624 | for out in outs: |
|
629 | for out in outs: | |
625 | for line in out.splitlines(): |
|
630 | for line in out.splitlines(): | |
626 | # push one line at a time |
|
631 | # push one line at a time | |
627 | tmp = transform.push(line) |
|
632 | tmp = transform.push(line) | |
628 | if tmp is not None: |
|
633 | if tmp is not None: | |
629 | yield tmp |
|
634 | yield tmp | |
630 |
|
635 | |||
631 | # reset the transform |
|
636 | # reset the transform | |
632 | tmp = transform.reset() |
|
637 | tmp = transform.reset() | |
633 | if tmp is not None: |
|
638 | if tmp is not None: | |
634 | yield tmp |
|
639 | yield tmp | |
635 |
|
640 | |||
636 | out = [] |
|
641 | out = [] | |
637 | for t in self.transforms_in_use: |
|
642 | for t in self.transforms_in_use: | |
638 | out = _flush(t, out) |
|
643 | out = _flush(t, out) | |
639 |
|
644 | |||
640 | out = list(out) |
|
645 | out = list(out) | |
641 | if out: |
|
646 | if out: | |
642 | self._store('\n'.join(out)) |
|
647 | self._store('\n'.join(out)) | |
643 |
|
648 | |||
644 | def raw_reset(self): |
|
649 | def raw_reset(self): | |
645 | """Return raw input only and perform a full reset. |
|
650 | """Return raw input only and perform a full reset. | |
646 | """ |
|
651 | """ | |
647 | out = self.source_raw |
|
652 | out = self.source_raw | |
648 | self.reset() |
|
653 | self.reset() | |
649 | return out |
|
654 | return out | |
650 |
|
655 | |||
651 | def source_reset(self): |
|
656 | def source_reset(self): | |
652 | try: |
|
657 | try: | |
653 | self.flush_transformers() |
|
658 | self.flush_transformers() | |
654 | return self.source |
|
659 | return self.source | |
655 | finally: |
|
660 | finally: | |
656 | self.reset() |
|
661 | self.reset() | |
657 |
|
662 | |||
658 | def push_accepts_more(self): |
|
663 | def push_accepts_more(self): | |
659 | if self.transformer_accumulating: |
|
664 | if self.transformer_accumulating: | |
660 | return True |
|
665 | return True | |
661 | else: |
|
666 | else: | |
662 | return super(IPythonInputSplitter, self).push_accepts_more() |
|
667 | return super(IPythonInputSplitter, self).push_accepts_more() | |
663 |
|
668 | |||
664 | def transform_cell(self, cell): |
|
669 | def transform_cell(self, cell): | |
665 | """Process and translate a cell of input. |
|
670 | """Process and translate a cell of input. | |
666 | """ |
|
671 | """ | |
667 | self.reset() |
|
672 | self.reset() | |
668 | try: |
|
673 | try: | |
669 | self.push(cell) |
|
674 | self.push(cell) | |
670 | self.flush_transformers() |
|
675 | self.flush_transformers() | |
671 | return self.source |
|
676 | return self.source | |
672 | finally: |
|
677 | finally: | |
673 | self.reset() |
|
678 | self.reset() | |
674 |
|
679 | |||
675 | def push(self, lines): |
|
680 | def push(self, lines): | |
676 | """Push one or more lines of IPython input. |
|
681 | """Push one or more lines of IPython input. | |
677 |
|
682 | |||
678 | This stores the given lines and returns a status code indicating |
|
683 | This stores the given lines and returns a status code indicating | |
679 | whether the code forms a complete Python block or not, after processing |
|
684 | whether the code forms a complete Python block or not, after processing | |
680 | all input lines for special IPython syntax. |
|
685 | all input lines for special IPython syntax. | |
681 |
|
686 | |||
682 | Any exceptions generated in compilation are swallowed, but if an |
|
687 | Any exceptions generated in compilation are swallowed, but if an | |
683 | exception was produced, the method returns True. |
|
688 | exception was produced, the method returns True. | |
684 |
|
689 | |||
685 | Parameters |
|
690 | Parameters | |
686 | ---------- |
|
691 | ---------- | |
687 | lines : string |
|
692 | lines : string | |
688 | One or more lines of Python input. |
|
693 | One or more lines of Python input. | |
689 |
|
694 | |||
690 | Returns |
|
695 | Returns | |
691 | ------- |
|
696 | ------- | |
692 | is_complete : boolean |
|
697 | is_complete : boolean | |
693 | True if the current input source (the result of the current input |
|
698 | True if the current input source (the result of the current input | |
694 | plus prior inputs) forms a complete Python execution block. Note that |
|
699 | plus prior inputs) forms a complete Python execution block. Note that | |
695 | this value is also stored as a private attribute (_is_complete), so it |
|
700 | this value is also stored as a private attribute (_is_complete), so it | |
696 | can be queried at any time. |
|
701 | can be queried at any time. | |
697 | """ |
|
702 | """ | |
698 |
|
703 | |||
699 | # We must ensure all input is pure unicode |
|
704 | # We must ensure all input is pure unicode | |
700 | lines = cast_unicode(lines, self.encoding) |
|
705 | lines = cast_unicode(lines, self.encoding) | |
701 | # ''.splitlines() --> [], but we need to push the empty line to transformers |
|
706 | # ''.splitlines() --> [], but we need to push the empty line to transformers | |
702 | lines_list = lines.splitlines() |
|
707 | lines_list = lines.splitlines() | |
703 | if not lines_list: |
|
708 | if not lines_list: | |
704 | lines_list = [''] |
|
709 | lines_list = [''] | |
705 |
|
710 | |||
706 | # Store raw source before applying any transformations to it. Note |
|
711 | # Store raw source before applying any transformations to it. Note | |
707 | # that this must be done *after* the reset() call that would otherwise |
|
712 | # that this must be done *after* the reset() call that would otherwise | |
708 | # flush the buffer. |
|
713 | # flush the buffer. | |
709 | self._store(lines, self._buffer_raw, 'source_raw') |
|
714 | self._store(lines, self._buffer_raw, 'source_raw') | |
710 |
|
715 | |||
711 | transformed_lines_list = [] |
|
716 | transformed_lines_list = [] | |
712 | for line in lines_list: |
|
717 | for line in lines_list: | |
713 | transformed = self._transform_line(line) |
|
718 | transformed = self._transform_line(line) | |
714 | if transformed is not None: |
|
719 | if transformed is not None: | |
715 | transformed_lines_list.append(transformed) |
|
720 | transformed_lines_list.append(transformed) | |
716 |
|
721 | |||
717 | if transformed_lines_list: |
|
722 | if transformed_lines_list: | |
718 | transformed_lines = '\n'.join(transformed_lines_list) |
|
723 | transformed_lines = '\n'.join(transformed_lines_list) | |
719 | return super(IPythonInputSplitter, self).push(transformed_lines) |
|
724 | return super(IPythonInputSplitter, self).push(transformed_lines) | |
720 | else: |
|
725 | else: | |
721 | # Got nothing back from transformers - they must be waiting for |
|
726 | # Got nothing back from transformers - they must be waiting for | |
722 | # more input. |
|
727 | # more input. | |
723 | return False |
|
728 | return False | |
724 |
|
729 | |||
725 | def _transform_line(self, line): |
|
730 | def _transform_line(self, line): | |
726 | """Push a line of input code through the various transformers. |
|
731 | """Push a line of input code through the various transformers. | |
727 |
|
732 | |||
728 | Returns any output from the transformers, or None if a transformer |
|
733 | Returns any output from the transformers, or None if a transformer | |
729 | is accumulating lines. |
|
734 | is accumulating lines. | |
730 |
|
735 | |||
731 | Sets self.transformer_accumulating as a side effect. |
|
736 | Sets self.transformer_accumulating as a side effect. | |
732 | """ |
|
737 | """ | |
733 | def _accumulating(dbg): |
|
738 | def _accumulating(dbg): | |
734 | #print(dbg) |
|
739 | #print(dbg) | |
735 | self.transformer_accumulating = True |
|
740 | self.transformer_accumulating = True | |
736 | return None |
|
741 | return None | |
737 |
|
742 | |||
738 | for transformer in self.physical_line_transforms: |
|
743 | for transformer in self.physical_line_transforms: | |
739 | line = transformer.push(line) |
|
744 | line = transformer.push(line) | |
740 | if line is None: |
|
745 | if line is None: | |
741 | return _accumulating(transformer) |
|
746 | return _accumulating(transformer) | |
742 |
|
747 | |||
743 | if not self.within_python_line: |
|
748 | if not self.within_python_line: | |
744 | line = self.assemble_logical_lines.push(line) |
|
749 | line = self.assemble_logical_lines.push(line) | |
745 | if line is None: |
|
750 | if line is None: | |
746 | return _accumulating('acc logical line') |
|
751 | return _accumulating('acc logical line') | |
747 |
|
752 | |||
748 | for transformer in self.logical_line_transforms: |
|
753 | for transformer in self.logical_line_transforms: | |
749 | line = transformer.push(line) |
|
754 | line = transformer.push(line) | |
750 | if line is None: |
|
755 | if line is None: | |
751 | return _accumulating(transformer) |
|
756 | return _accumulating(transformer) | |
752 |
|
757 | |||
753 | line = self.assemble_python_lines.push(line) |
|
758 | line = self.assemble_python_lines.push(line) | |
754 | if line is None: |
|
759 | if line is None: | |
755 | self.within_python_line = True |
|
760 | self.within_python_line = True | |
756 | return _accumulating('acc python line') |
|
761 | return _accumulating('acc python line') | |
757 | else: |
|
762 | else: | |
758 | self.within_python_line = False |
|
763 | self.within_python_line = False | |
759 |
|
764 | |||
760 | for transformer in self.python_line_transforms: |
|
765 | for transformer in self.python_line_transforms: | |
761 | line = transformer.push(line) |
|
766 | line = transformer.push(line) | |
762 | if line is None: |
|
767 | if line is None: | |
763 | return _accumulating(transformer) |
|
768 | return _accumulating(transformer) | |
764 |
|
769 | |||
765 | #print("transformers clear") #debug |
|
770 | #print("transformers clear") #debug | |
766 | self.transformer_accumulating = False |
|
771 | self.transformer_accumulating = False | |
767 | return line |
|
772 | return line | |
768 |
|
773 |
@@ -1,3363 +1,3368 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Main IPython class.""" |
|
2 | """Main IPython class.""" | |
3 |
|
3 | |||
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> |
|
5 | # Copyright (C) 2001 Janko Hauser <jhauser@zscout.de> | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # Copyright (C) 2008-2011 The IPython Development Team |
|
7 | # Copyright (C) 2008-2011 The IPython Development Team | |
8 | # |
|
8 | # | |
9 | # Distributed under the terms of the BSD License. The full license is in |
|
9 | # Distributed under the terms of the BSD License. The full license is in | |
10 | # the file COPYING, distributed as part of this software. |
|
10 | # the file COPYING, distributed as part of this software. | |
11 | #----------------------------------------------------------------------------- |
|
11 | #----------------------------------------------------------------------------- | |
12 |
|
12 | |||
13 |
|
13 | |||
14 | import abc |
|
14 | import abc | |
15 | import ast |
|
15 | import ast | |
16 | import atexit |
|
16 | import atexit | |
17 | import builtins as builtin_mod |
|
17 | import builtins as builtin_mod | |
18 | import functools |
|
18 | import functools | |
19 | import os |
|
19 | import os | |
20 | import re |
|
20 | import re | |
21 | import runpy |
|
21 | import runpy | |
22 | import sys |
|
22 | import sys | |
23 | import tempfile |
|
23 | import tempfile | |
24 | import traceback |
|
24 | import traceback | |
25 | import types |
|
25 | import types | |
26 | import subprocess |
|
26 | import subprocess | |
27 | import warnings |
|
27 | import warnings | |
28 | from io import open as io_open |
|
28 | from io import open as io_open | |
29 |
|
29 | |||
30 | from pickleshare import PickleShareDB |
|
30 | from pickleshare import PickleShareDB | |
31 |
|
31 | |||
32 | from traitlets.config.configurable import SingletonConfigurable |
|
32 | from traitlets.config.configurable import SingletonConfigurable | |
33 | from IPython.core import oinspect |
|
33 | from IPython.core import oinspect | |
34 | from IPython.core import magic |
|
34 | from IPython.core import magic | |
35 | from IPython.core import page |
|
35 | from IPython.core import page | |
36 | from IPython.core import prefilter |
|
36 | from IPython.core import prefilter | |
37 | from IPython.core import ultratb |
|
37 | from IPython.core import ultratb | |
38 | from IPython.core.alias import Alias, AliasManager |
|
38 | from IPython.core.alias import Alias, AliasManager | |
39 | from IPython.core.autocall import ExitAutocall |
|
39 | from IPython.core.autocall import ExitAutocall | |
40 | from IPython.core.builtin_trap import BuiltinTrap |
|
40 | from IPython.core.builtin_trap import BuiltinTrap | |
41 | from IPython.core.events import EventManager, available_events |
|
41 | from IPython.core.events import EventManager, available_events | |
42 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython |
|
42 | from IPython.core.compilerop import CachingCompiler, check_linecache_ipython | |
43 | from IPython.core.debugger import Pdb |
|
43 | from IPython.core.debugger import Pdb | |
44 | from IPython.core.display_trap import DisplayTrap |
|
44 | from IPython.core.display_trap import DisplayTrap | |
45 | from IPython.core.displayhook import DisplayHook |
|
45 | from IPython.core.displayhook import DisplayHook | |
46 | from IPython.core.displaypub import DisplayPublisher |
|
46 | from IPython.core.displaypub import DisplayPublisher | |
47 | from IPython.core.error import InputRejected, UsageError |
|
47 | from IPython.core.error import InputRejected, UsageError | |
48 | from IPython.core.extensions import ExtensionManager |
|
48 | from IPython.core.extensions import ExtensionManager | |
49 | from IPython.core.formatters import DisplayFormatter |
|
49 | from IPython.core.formatters import DisplayFormatter | |
50 | from IPython.core.history import HistoryManager |
|
50 | from IPython.core.history import HistoryManager | |
51 | from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2 |
|
51 | from IPython.core.inputtransformer2 import ESC_MAGIC, ESC_MAGIC2 | |
52 | from IPython.core.logger import Logger |
|
52 | from IPython.core.logger import Logger | |
53 | from IPython.core.macro import Macro |
|
53 | from IPython.core.macro import Macro | |
54 | from IPython.core.payload import PayloadManager |
|
54 | from IPython.core.payload import PayloadManager | |
55 | from IPython.core.prefilter import PrefilterManager |
|
55 | from IPython.core.prefilter import PrefilterManager | |
56 | from IPython.core.profiledir import ProfileDir |
|
56 | from IPython.core.profiledir import ProfileDir | |
57 | from IPython.core.usage import default_banner |
|
57 | from IPython.core.usage import default_banner | |
58 | from IPython.display import display |
|
58 | from IPython.display import display | |
59 | from IPython.testing.skipdoctest import skip_doctest |
|
59 | from IPython.testing.skipdoctest import skip_doctest | |
60 | from IPython.utils import PyColorize |
|
60 | from IPython.utils import PyColorize | |
61 | from IPython.utils import io |
|
61 | from IPython.utils import io | |
62 | from IPython.utils import py3compat |
|
62 | from IPython.utils import py3compat | |
63 | from IPython.utils import openpy |
|
63 | from IPython.utils import openpy | |
64 | from IPython.utils.decorators import undoc |
|
64 | from IPython.utils.decorators import undoc | |
65 | from IPython.utils.io import ask_yes_no |
|
65 | from IPython.utils.io import ask_yes_no | |
66 | from IPython.utils.ipstruct import Struct |
|
66 | from IPython.utils.ipstruct import Struct | |
67 | from IPython.paths import get_ipython_dir |
|
67 | from IPython.paths import get_ipython_dir | |
68 | from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists |
|
68 | from IPython.utils.path import get_home_dir, get_py_filename, ensure_dir_exists | |
69 | from IPython.utils.process import system, getoutput |
|
69 | from IPython.utils.process import system, getoutput | |
70 | from IPython.utils.strdispatch import StrDispatch |
|
70 | from IPython.utils.strdispatch import StrDispatch | |
71 | from IPython.utils.syspathcontext import prepended_to_syspath |
|
71 | from IPython.utils.syspathcontext import prepended_to_syspath | |
72 | from IPython.utils.text import format_screen, LSString, SList, DollarFormatter |
|
72 | from IPython.utils.text import format_screen, LSString, SList, DollarFormatter | |
73 | from IPython.utils.tempdir import TemporaryDirectory |
|
73 | from IPython.utils.tempdir import TemporaryDirectory | |
74 | from traitlets import ( |
|
74 | from traitlets import ( | |
75 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, |
|
75 | Integer, Bool, CaselessStrEnum, Enum, List, Dict, Unicode, Instance, Type, | |
76 | observe, default, |
|
76 | observe, default, | |
77 | ) |
|
77 | ) | |
78 | from warnings import warn |
|
78 | from warnings import warn | |
79 | from logging import error |
|
79 | from logging import error | |
80 | import IPython.core.hooks |
|
80 | import IPython.core.hooks | |
81 |
|
81 | |||
82 | from typing import List as ListType |
|
82 | from typing import List as ListType | |
83 | from ast import AST |
|
83 | from ast import AST | |
84 |
|
84 | |||
85 | # NoOpContext is deprecated, but ipykernel imports it from here. |
|
85 | # NoOpContext is deprecated, but ipykernel imports it from here. | |
86 | # See https://github.com/ipython/ipykernel/issues/157 |
|
86 | # See https://github.com/ipython/ipykernel/issues/157 | |
87 | from IPython.utils.contexts import NoOpContext |
|
87 | from IPython.utils.contexts import NoOpContext | |
88 |
|
88 | |||
89 | try: |
|
89 | try: | |
90 | import docrepr.sphinxify as sphx |
|
90 | import docrepr.sphinxify as sphx | |
91 |
|
91 | |||
92 | def sphinxify(doc): |
|
92 | def sphinxify(doc): | |
93 | with TemporaryDirectory() as dirname: |
|
93 | with TemporaryDirectory() as dirname: | |
94 | return { |
|
94 | return { | |
95 | 'text/html': sphx.sphinxify(doc, dirname), |
|
95 | 'text/html': sphx.sphinxify(doc, dirname), | |
96 | 'text/plain': doc |
|
96 | 'text/plain': doc | |
97 | } |
|
97 | } | |
98 | except ImportError: |
|
98 | except ImportError: | |
99 | sphinxify = None |
|
99 | sphinxify = None | |
100 |
|
100 | |||
101 |
|
101 | |||
102 | class ProvisionalWarning(DeprecationWarning): |
|
102 | class ProvisionalWarning(DeprecationWarning): | |
103 | """ |
|
103 | """ | |
104 | Warning class for unstable features |
|
104 | Warning class for unstable features | |
105 | """ |
|
105 | """ | |
106 | pass |
|
106 | pass | |
107 |
|
107 | |||
108 | if sys.version_info > (3,6): |
|
108 | if sys.version_info > (3,6): | |
109 | _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign) |
|
109 | _assign_nodes = (ast.AugAssign, ast.AnnAssign, ast.Assign) | |
110 | _single_targets_nodes = (ast.AugAssign, ast.AnnAssign) |
|
110 | _single_targets_nodes = (ast.AugAssign, ast.AnnAssign) | |
111 | else: |
|
111 | else: | |
112 | _assign_nodes = (ast.AugAssign, ast.Assign ) |
|
112 | _assign_nodes = (ast.AugAssign, ast.Assign ) | |
113 | _single_targets_nodes = (ast.AugAssign, ) |
|
113 | _single_targets_nodes = (ast.AugAssign, ) | |
114 |
|
114 | |||
115 | #----------------------------------------------------------------------------- |
|
115 | #----------------------------------------------------------------------------- | |
116 | # Globals |
|
116 | # Globals | |
117 | #----------------------------------------------------------------------------- |
|
117 | #----------------------------------------------------------------------------- | |
118 |
|
118 | |||
119 | # compiled regexps for autoindent management |
|
119 | # compiled regexps for autoindent management | |
120 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') |
|
120 | dedent_re = re.compile(r'^\s+raise|^\s+return|^\s+pass') | |
121 |
|
121 | |||
122 | #----------------------------------------------------------------------------- |
|
122 | #----------------------------------------------------------------------------- | |
123 | # Utilities |
|
123 | # Utilities | |
124 | #----------------------------------------------------------------------------- |
|
124 | #----------------------------------------------------------------------------- | |
125 |
|
125 | |||
126 | @undoc |
|
126 | @undoc | |
127 | def softspace(file, newvalue): |
|
127 | def softspace(file, newvalue): | |
128 | """Copied from code.py, to remove the dependency""" |
|
128 | """Copied from code.py, to remove the dependency""" | |
129 |
|
129 | |||
130 | oldvalue = 0 |
|
130 | oldvalue = 0 | |
131 | try: |
|
131 | try: | |
132 | oldvalue = file.softspace |
|
132 | oldvalue = file.softspace | |
133 | except AttributeError: |
|
133 | except AttributeError: | |
134 | pass |
|
134 | pass | |
135 | try: |
|
135 | try: | |
136 | file.softspace = newvalue |
|
136 | file.softspace = newvalue | |
137 | except (AttributeError, TypeError): |
|
137 | except (AttributeError, TypeError): | |
138 | # "attribute-less object" or "read-only attributes" |
|
138 | # "attribute-less object" or "read-only attributes" | |
139 | pass |
|
139 | pass | |
140 | return oldvalue |
|
140 | return oldvalue | |
141 |
|
141 | |||
142 | @undoc |
|
142 | @undoc | |
143 | def no_op(*a, **kw): |
|
143 | def no_op(*a, **kw): | |
144 | pass |
|
144 | pass | |
145 |
|
145 | |||
146 |
|
146 | |||
147 | class SpaceInInput(Exception): pass |
|
147 | class SpaceInInput(Exception): pass | |
148 |
|
148 | |||
149 |
|
149 | |||
150 | def get_default_colors(): |
|
150 | def get_default_colors(): | |
151 | "DEPRECATED" |
|
151 | "DEPRECATED" | |
152 | warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.', |
|
152 | warn('get_default_color is deprecated since IPython 5.0, and returns `Neutral` on all platforms.', | |
153 | DeprecationWarning, stacklevel=2) |
|
153 | DeprecationWarning, stacklevel=2) | |
154 | return 'Neutral' |
|
154 | return 'Neutral' | |
155 |
|
155 | |||
156 |
|
156 | |||
157 | class SeparateUnicode(Unicode): |
|
157 | class SeparateUnicode(Unicode): | |
158 | r"""A Unicode subclass to validate separate_in, separate_out, etc. |
|
158 | r"""A Unicode subclass to validate separate_in, separate_out, etc. | |
159 |
|
159 | |||
160 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. |
|
160 | This is a Unicode based trait that converts '0'->'' and ``'\\n'->'\n'``. | |
161 | """ |
|
161 | """ | |
162 |
|
162 | |||
163 | def validate(self, obj, value): |
|
163 | def validate(self, obj, value): | |
164 | if value == '0': value = '' |
|
164 | if value == '0': value = '' | |
165 | value = value.replace('\\n','\n') |
|
165 | value = value.replace('\\n','\n') | |
166 | return super(SeparateUnicode, self).validate(obj, value) |
|
166 | return super(SeparateUnicode, self).validate(obj, value) | |
167 |
|
167 | |||
168 |
|
168 | |||
169 | @undoc |
|
169 | @undoc | |
170 | class DummyMod(object): |
|
170 | class DummyMod(object): | |
171 | """A dummy module used for IPython's interactive module when |
|
171 | """A dummy module used for IPython's interactive module when | |
172 | a namespace must be assigned to the module's __dict__.""" |
|
172 | a namespace must be assigned to the module's __dict__.""" | |
173 | __spec__ = None |
|
173 | __spec__ = None | |
174 |
|
174 | |||
175 |
|
175 | |||
176 | class ExecutionInfo(object): |
|
176 | class ExecutionInfo(object): | |
177 | """The arguments used for a call to :meth:`InteractiveShell.run_cell` |
|
177 | """The arguments used for a call to :meth:`InteractiveShell.run_cell` | |
178 |
|
178 | |||
179 | Stores information about what is going to happen. |
|
179 | Stores information about what is going to happen. | |
180 | """ |
|
180 | """ | |
181 | raw_cell = None |
|
181 | raw_cell = None | |
182 | store_history = False |
|
182 | store_history = False | |
183 | silent = False |
|
183 | silent = False | |
184 | shell_futures = True |
|
184 | shell_futures = True | |
185 |
|
185 | |||
186 | def __init__(self, raw_cell, store_history, silent, shell_futures): |
|
186 | def __init__(self, raw_cell, store_history, silent, shell_futures): | |
187 | self.raw_cell = raw_cell |
|
187 | self.raw_cell = raw_cell | |
188 | self.store_history = store_history |
|
188 | self.store_history = store_history | |
189 | self.silent = silent |
|
189 | self.silent = silent | |
190 | self.shell_futures = shell_futures |
|
190 | self.shell_futures = shell_futures | |
191 |
|
191 | |||
192 | def __repr__(self): |
|
192 | def __repr__(self): | |
193 | name = self.__class__.__qualname__ |
|
193 | name = self.__class__.__qualname__ | |
194 | raw_cell = ((self.raw_cell[:50] + '..') |
|
194 | raw_cell = ((self.raw_cell[:50] + '..') | |
195 | if len(self.raw_cell) > 50 else self.raw_cell) |
|
195 | if len(self.raw_cell) > 50 else self.raw_cell) | |
196 | return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\ |
|
196 | return '<%s object at %x, raw_cell="%s" store_history=%s silent=%s shell_futures=%s>' %\ | |
197 | (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures) |
|
197 | (name, id(self), raw_cell, self.store_history, self.silent, self.shell_futures) | |
198 |
|
198 | |||
199 |
|
199 | |||
200 | class ExecutionResult(object): |
|
200 | class ExecutionResult(object): | |
201 | """The result of a call to :meth:`InteractiveShell.run_cell` |
|
201 | """The result of a call to :meth:`InteractiveShell.run_cell` | |
202 |
|
202 | |||
203 | Stores information about what took place. |
|
203 | Stores information about what took place. | |
204 | """ |
|
204 | """ | |
205 | execution_count = None |
|
205 | execution_count = None | |
206 | error_before_exec = None |
|
206 | error_before_exec = None | |
207 | error_in_exec = None |
|
207 | error_in_exec = None | |
208 | info = None |
|
208 | info = None | |
209 | result = None |
|
209 | result = None | |
210 |
|
210 | |||
211 | def __init__(self, info): |
|
211 | def __init__(self, info): | |
212 | self.info = info |
|
212 | self.info = info | |
213 |
|
213 | |||
214 | @property |
|
214 | @property | |
215 | def success(self): |
|
215 | def success(self): | |
216 | return (self.error_before_exec is None) and (self.error_in_exec is None) |
|
216 | return (self.error_before_exec is None) and (self.error_in_exec is None) | |
217 |
|
217 | |||
218 | def raise_error(self): |
|
218 | def raise_error(self): | |
219 | """Reraises error if `success` is `False`, otherwise does nothing""" |
|
219 | """Reraises error if `success` is `False`, otherwise does nothing""" | |
220 | if self.error_before_exec is not None: |
|
220 | if self.error_before_exec is not None: | |
221 | raise self.error_before_exec |
|
221 | raise self.error_before_exec | |
222 | if self.error_in_exec is not None: |
|
222 | if self.error_in_exec is not None: | |
223 | raise self.error_in_exec |
|
223 | raise self.error_in_exec | |
224 |
|
224 | |||
225 | def __repr__(self): |
|
225 | def __repr__(self): | |
226 | name = self.__class__.__qualname__ |
|
226 | name = self.__class__.__qualname__ | |
227 | return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\ |
|
227 | return '<%s object at %x, execution_count=%s error_before_exec=%s error_in_exec=%s info=%s result=%s>' %\ | |
228 | (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result)) |
|
228 | (name, id(self), self.execution_count, self.error_before_exec, self.error_in_exec, repr(self.info), repr(self.result)) | |
229 |
|
229 | |||
230 |
|
230 | |||
231 | class InteractiveShell(SingletonConfigurable): |
|
231 | class InteractiveShell(SingletonConfigurable): | |
232 | """An enhanced, interactive shell for Python.""" |
|
232 | """An enhanced, interactive shell for Python.""" | |
233 |
|
233 | |||
234 | _instance = None |
|
234 | _instance = None | |
235 |
|
235 | |||
236 | ast_transformers = List([], help= |
|
236 | ast_transformers = List([], help= | |
237 | """ |
|
237 | """ | |
238 | A list of ast.NodeTransformer subclass instances, which will be applied |
|
238 | A list of ast.NodeTransformer subclass instances, which will be applied | |
239 | to user input before code is run. |
|
239 | to user input before code is run. | |
240 | """ |
|
240 | """ | |
241 | ).tag(config=True) |
|
241 | ).tag(config=True) | |
242 |
|
242 | |||
243 | autocall = Enum((0,1,2), default_value=0, help= |
|
243 | autocall = Enum((0,1,2), default_value=0, help= | |
244 | """ |
|
244 | """ | |
245 | Make IPython automatically call any callable object even if you didn't |
|
245 | Make IPython automatically call any callable object even if you didn't | |
246 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' |
|
246 | type explicit parentheses. For example, 'str 43' becomes 'str(43)' | |
247 | automatically. The value can be '0' to disable the feature, '1' for |
|
247 | automatically. The value can be '0' to disable the feature, '1' for | |
248 | 'smart' autocall, where it is not applied if there are no more |
|
248 | 'smart' autocall, where it is not applied if there are no more | |
249 | arguments on the line, and '2' for 'full' autocall, where all callable |
|
249 | arguments on the line, and '2' for 'full' autocall, where all callable | |
250 | objects are automatically called (even if no arguments are present). |
|
250 | objects are automatically called (even if no arguments are present). | |
251 | """ |
|
251 | """ | |
252 | ).tag(config=True) |
|
252 | ).tag(config=True) | |
253 | # TODO: remove all autoindent logic and put into frontends. |
|
253 | # TODO: remove all autoindent logic and put into frontends. | |
254 | # We can't do this yet because even runlines uses the autoindent. |
|
254 | # We can't do this yet because even runlines uses the autoindent. | |
255 | autoindent = Bool(True, help= |
|
255 | autoindent = Bool(True, help= | |
256 | """ |
|
256 | """ | |
257 | Autoindent IPython code entered interactively. |
|
257 | Autoindent IPython code entered interactively. | |
258 | """ |
|
258 | """ | |
259 | ).tag(config=True) |
|
259 | ).tag(config=True) | |
260 |
|
260 | |||
261 | automagic = Bool(True, help= |
|
261 | automagic = Bool(True, help= | |
262 | """ |
|
262 | """ | |
263 | Enable magic commands to be called without the leading %. |
|
263 | Enable magic commands to be called without the leading %. | |
264 | """ |
|
264 | """ | |
265 | ).tag(config=True) |
|
265 | ).tag(config=True) | |
266 |
|
266 | |||
267 | banner1 = Unicode(default_banner, |
|
267 | banner1 = Unicode(default_banner, | |
268 | help="""The part of the banner to be printed before the profile""" |
|
268 | help="""The part of the banner to be printed before the profile""" | |
269 | ).tag(config=True) |
|
269 | ).tag(config=True) | |
270 | banner2 = Unicode('', |
|
270 | banner2 = Unicode('', | |
271 | help="""The part of the banner to be printed after the profile""" |
|
271 | help="""The part of the banner to be printed after the profile""" | |
272 | ).tag(config=True) |
|
272 | ).tag(config=True) | |
273 |
|
273 | |||
274 | cache_size = Integer(1000, help= |
|
274 | cache_size = Integer(1000, help= | |
275 | """ |
|
275 | """ | |
276 | Set the size of the output cache. The default is 1000, you can |
|
276 | Set the size of the output cache. The default is 1000, you can | |
277 | change it permanently in your config file. Setting it to 0 completely |
|
277 | change it permanently in your config file. Setting it to 0 completely | |
278 | disables the caching system, and the minimum value accepted is 3 (if |
|
278 | disables the caching system, and the minimum value accepted is 3 (if | |
279 | you provide a value less than 3, it is reset to 0 and a warning is |
|
279 | you provide a value less than 3, it is reset to 0 and a warning is | |
280 | issued). This limit is defined because otherwise you'll spend more |
|
280 | issued). This limit is defined because otherwise you'll spend more | |
281 | time re-flushing a too small cache than working |
|
281 | time re-flushing a too small cache than working | |
282 | """ |
|
282 | """ | |
283 | ).tag(config=True) |
|
283 | ).tag(config=True) | |
284 | color_info = Bool(True, help= |
|
284 | color_info = Bool(True, help= | |
285 | """ |
|
285 | """ | |
286 | Use colors for displaying information about objects. Because this |
|
286 | Use colors for displaying information about objects. Because this | |
287 | information is passed through a pager (like 'less'), and some pagers |
|
287 | information is passed through a pager (like 'less'), and some pagers | |
288 | get confused with color codes, this capability can be turned off. |
|
288 | get confused with color codes, this capability can be turned off. | |
289 | """ |
|
289 | """ | |
290 | ).tag(config=True) |
|
290 | ).tag(config=True) | |
291 | colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), |
|
291 | colors = CaselessStrEnum(('Neutral', 'NoColor','LightBG','Linux'), | |
292 | default_value='Neutral', |
|
292 | default_value='Neutral', | |
293 | help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." |
|
293 | help="Set the color scheme (NoColor, Neutral, Linux, or LightBG)." | |
294 | ).tag(config=True) |
|
294 | ).tag(config=True) | |
295 | debug = Bool(False).tag(config=True) |
|
295 | debug = Bool(False).tag(config=True) | |
296 | disable_failing_post_execute = Bool(False, |
|
296 | disable_failing_post_execute = Bool(False, | |
297 | help="Don't call post-execute functions that have failed in the past." |
|
297 | help="Don't call post-execute functions that have failed in the past." | |
298 | ).tag(config=True) |
|
298 | ).tag(config=True) | |
299 | display_formatter = Instance(DisplayFormatter, allow_none=True) |
|
299 | display_formatter = Instance(DisplayFormatter, allow_none=True) | |
300 | displayhook_class = Type(DisplayHook) |
|
300 | displayhook_class = Type(DisplayHook) | |
301 | display_pub_class = Type(DisplayPublisher) |
|
301 | display_pub_class = Type(DisplayPublisher) | |
302 |
|
302 | |||
303 | sphinxify_docstring = Bool(False, help= |
|
303 | sphinxify_docstring = Bool(False, help= | |
304 | """ |
|
304 | """ | |
305 | Enables rich html representation of docstrings. (This requires the |
|
305 | Enables rich html representation of docstrings. (This requires the | |
306 | docrepr module). |
|
306 | docrepr module). | |
307 | """).tag(config=True) |
|
307 | """).tag(config=True) | |
308 |
|
308 | |||
309 | @observe("sphinxify_docstring") |
|
309 | @observe("sphinxify_docstring") | |
310 | def _sphinxify_docstring_changed(self, change): |
|
310 | def _sphinxify_docstring_changed(self, change): | |
311 | if change['new']: |
|
311 | if change['new']: | |
312 | warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) |
|
312 | warn("`sphinxify_docstring` is provisional since IPython 5.0 and might change in future versions." , ProvisionalWarning) | |
313 |
|
313 | |||
314 | enable_html_pager = Bool(False, help= |
|
314 | enable_html_pager = Bool(False, help= | |
315 | """ |
|
315 | """ | |
316 | (Provisional API) enables html representation in mime bundles sent |
|
316 | (Provisional API) enables html representation in mime bundles sent | |
317 | to pagers. |
|
317 | to pagers. | |
318 | """).tag(config=True) |
|
318 | """).tag(config=True) | |
319 |
|
319 | |||
320 | @observe("enable_html_pager") |
|
320 | @observe("enable_html_pager") | |
321 | def _enable_html_pager_changed(self, change): |
|
321 | def _enable_html_pager_changed(self, change): | |
322 | if change['new']: |
|
322 | if change['new']: | |
323 | warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) |
|
323 | warn("`enable_html_pager` is provisional since IPython 5.0 and might change in future versions.", ProvisionalWarning) | |
324 |
|
324 | |||
325 | data_pub_class = None |
|
325 | data_pub_class = None | |
326 |
|
326 | |||
327 | exit_now = Bool(False) |
|
327 | exit_now = Bool(False) | |
328 | exiter = Instance(ExitAutocall) |
|
328 | exiter = Instance(ExitAutocall) | |
329 | @default('exiter') |
|
329 | @default('exiter') | |
330 | def _exiter_default(self): |
|
330 | def _exiter_default(self): | |
331 | return ExitAutocall(self) |
|
331 | return ExitAutocall(self) | |
332 | # Monotonically increasing execution counter |
|
332 | # Monotonically increasing execution counter | |
333 | execution_count = Integer(1) |
|
333 | execution_count = Integer(1) | |
334 | filename = Unicode("<ipython console>") |
|
334 | filename = Unicode("<ipython console>") | |
335 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ |
|
335 | ipython_dir= Unicode('').tag(config=True) # Set to get_ipython_dir() in __init__ | |
336 |
|
336 | |||
337 | # Used to transform cells before running them, and check whether code is complete |
|
337 | # Used to transform cells before running them, and check whether code is complete | |
338 | input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager', |
|
338 | input_transformer_manager = Instance('IPython.core.inputtransformer2.TransformerManager', | |
339 | ()) |
|
339 | ()) | |
340 |
|
340 | |||
341 | @property |
|
341 | @property | |
342 | def input_transformers_cleanup(self): |
|
342 | def input_transformers_cleanup(self): | |
343 | return self.input_transformer_manager.cleanup_transforms |
|
343 | return self.input_transformer_manager.cleanup_transforms | |
344 |
|
344 | |||
345 | input_transformers_post = List([], |
|
345 | input_transformers_post = List([], | |
346 | help="A list of string input transformers, to be applied after IPython's " |
|
346 | help="A list of string input transformers, to be applied after IPython's " | |
347 | "own input transformations." |
|
347 | "own input transformations." | |
348 | ) |
|
348 | ) | |
349 |
|
349 | |||
350 | @property |
|
350 | @property | |
351 | def input_splitter(self): |
|
351 | def input_splitter(self): | |
352 | """Make this available for compatibility |
|
352 | """Make this available for backward compatibility (pre-7.0 release) with existing code. | |
353 |
|
353 | |||
354 | ipykernel currently uses shell.input_splitter.check_complete |
|
354 | For example, ipykernel ipykernel currently uses | |
|
355 | `shell.input_splitter.check_complete` | |||
355 | """ |
|
356 | """ | |
|
357 | from warnings import warn | |||
|
358 | warn("`input_splitter` is deprecated since IPython 7.0, prefer `input_transformer_manager`.", | |||
|
359 | DeprecationWarning, stacklevel=2 | |||
|
360 | ) | |||
356 | return self.input_transformer_manager |
|
361 | return self.input_transformer_manager | |
357 |
|
362 | |||
358 | logstart = Bool(False, help= |
|
363 | logstart = Bool(False, help= | |
359 | """ |
|
364 | """ | |
360 | Start logging to the default log file in overwrite mode. |
|
365 | Start logging to the default log file in overwrite mode. | |
361 | Use `logappend` to specify a log file to **append** logs to. |
|
366 | Use `logappend` to specify a log file to **append** logs to. | |
362 | """ |
|
367 | """ | |
363 | ).tag(config=True) |
|
368 | ).tag(config=True) | |
364 | logfile = Unicode('', help= |
|
369 | logfile = Unicode('', help= | |
365 | """ |
|
370 | """ | |
366 | The name of the logfile to use. |
|
371 | The name of the logfile to use. | |
367 | """ |
|
372 | """ | |
368 | ).tag(config=True) |
|
373 | ).tag(config=True) | |
369 | logappend = Unicode('', help= |
|
374 | logappend = Unicode('', help= | |
370 | """ |
|
375 | """ | |
371 | Start logging to the given file in append mode. |
|
376 | Start logging to the given file in append mode. | |
372 | Use `logfile` to specify a log file to **overwrite** logs to. |
|
377 | Use `logfile` to specify a log file to **overwrite** logs to. | |
373 | """ |
|
378 | """ | |
374 | ).tag(config=True) |
|
379 | ).tag(config=True) | |
375 | object_info_string_level = Enum((0,1,2), default_value=0, |
|
380 | object_info_string_level = Enum((0,1,2), default_value=0, | |
376 | ).tag(config=True) |
|
381 | ).tag(config=True) | |
377 | pdb = Bool(False, help= |
|
382 | pdb = Bool(False, help= | |
378 | """ |
|
383 | """ | |
379 | Automatically call the pdb debugger after every exception. |
|
384 | Automatically call the pdb debugger after every exception. | |
380 | """ |
|
385 | """ | |
381 | ).tag(config=True) |
|
386 | ).tag(config=True) | |
382 | display_page = Bool(False, |
|
387 | display_page = Bool(False, | |
383 | help="""If True, anything that would be passed to the pager |
|
388 | help="""If True, anything that would be passed to the pager | |
384 | will be displayed as regular output instead.""" |
|
389 | will be displayed as regular output instead.""" | |
385 | ).tag(config=True) |
|
390 | ).tag(config=True) | |
386 |
|
391 | |||
387 | # deprecated prompt traits: |
|
392 | # deprecated prompt traits: | |
388 |
|
393 | |||
389 | prompt_in1 = Unicode('In [\\#]: ', |
|
394 | prompt_in1 = Unicode('In [\\#]: ', | |
390 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
395 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." | |
391 | ).tag(config=True) |
|
396 | ).tag(config=True) | |
392 | prompt_in2 = Unicode(' .\\D.: ', |
|
397 | prompt_in2 = Unicode(' .\\D.: ', | |
393 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
398 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." | |
394 | ).tag(config=True) |
|
399 | ).tag(config=True) | |
395 | prompt_out = Unicode('Out[\\#]: ', |
|
400 | prompt_out = Unicode('Out[\\#]: ', | |
396 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
401 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." | |
397 | ).tag(config=True) |
|
402 | ).tag(config=True) | |
398 | prompts_pad_left = Bool(True, |
|
403 | prompts_pad_left = Bool(True, | |
399 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." |
|
404 | help="Deprecated since IPython 4.0 and ignored since 5.0, set TerminalInteractiveShell.prompts object directly." | |
400 | ).tag(config=True) |
|
405 | ).tag(config=True) | |
401 |
|
406 | |||
402 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') |
|
407 | @observe('prompt_in1', 'prompt_in2', 'prompt_out', 'prompt_pad_left') | |
403 | def _prompt_trait_changed(self, change): |
|
408 | def _prompt_trait_changed(self, change): | |
404 | name = change['name'] |
|
409 | name = change['name'] | |
405 | warn("InteractiveShell.{name} is deprecated since IPython 4.0" |
|
410 | warn("InteractiveShell.{name} is deprecated since IPython 4.0" | |
406 | " and ignored since 5.0, set TerminalInteractiveShell.prompts" |
|
411 | " and ignored since 5.0, set TerminalInteractiveShell.prompts" | |
407 | " object directly.".format(name=name)) |
|
412 | " object directly.".format(name=name)) | |
408 |
|
413 | |||
409 | # protect against weird cases where self.config may not exist: |
|
414 | # protect against weird cases where self.config may not exist: | |
410 |
|
415 | |||
411 | show_rewritten_input = Bool(True, |
|
416 | show_rewritten_input = Bool(True, | |
412 | help="Show rewritten input, e.g. for autocall." |
|
417 | help="Show rewritten input, e.g. for autocall." | |
413 | ).tag(config=True) |
|
418 | ).tag(config=True) | |
414 |
|
419 | |||
415 | quiet = Bool(False).tag(config=True) |
|
420 | quiet = Bool(False).tag(config=True) | |
416 |
|
421 | |||
417 | history_length = Integer(10000, |
|
422 | history_length = Integer(10000, | |
418 | help='Total length of command history' |
|
423 | help='Total length of command history' | |
419 | ).tag(config=True) |
|
424 | ).tag(config=True) | |
420 |
|
425 | |||
421 | history_load_length = Integer(1000, help= |
|
426 | history_load_length = Integer(1000, help= | |
422 | """ |
|
427 | """ | |
423 | The number of saved history entries to be loaded |
|
428 | The number of saved history entries to be loaded | |
424 | into the history buffer at startup. |
|
429 | into the history buffer at startup. | |
425 | """ |
|
430 | """ | |
426 | ).tag(config=True) |
|
431 | ).tag(config=True) | |
427 |
|
432 | |||
428 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'], |
|
433 | ast_node_interactivity = Enum(['all', 'last', 'last_expr', 'none', 'last_expr_or_assign'], | |
429 | default_value='last_expr', |
|
434 | default_value='last_expr', | |
430 | help=""" |
|
435 | help=""" | |
431 | 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying |
|
436 | 'all', 'last', 'last_expr' or 'none', 'last_expr_or_assign' specifying | |
432 | which nodes should be run interactively (displaying output from expressions). |
|
437 | which nodes should be run interactively (displaying output from expressions). | |
433 | """ |
|
438 | """ | |
434 | ).tag(config=True) |
|
439 | ).tag(config=True) | |
435 |
|
440 | |||
436 | # TODO: this part of prompt management should be moved to the frontends. |
|
441 | # TODO: this part of prompt management should be moved to the frontends. | |
437 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' |
|
442 | # Use custom TraitTypes that convert '0'->'' and '\\n'->'\n' | |
438 | separate_in = SeparateUnicode('\n').tag(config=True) |
|
443 | separate_in = SeparateUnicode('\n').tag(config=True) | |
439 | separate_out = SeparateUnicode('').tag(config=True) |
|
444 | separate_out = SeparateUnicode('').tag(config=True) | |
440 | separate_out2 = SeparateUnicode('').tag(config=True) |
|
445 | separate_out2 = SeparateUnicode('').tag(config=True) | |
441 | wildcards_case_sensitive = Bool(True).tag(config=True) |
|
446 | wildcards_case_sensitive = Bool(True).tag(config=True) | |
442 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), |
|
447 | xmode = CaselessStrEnum(('Context','Plain', 'Verbose'), | |
443 | default_value='Context', |
|
448 | default_value='Context', | |
444 | help="Switch modes for the IPython exception handlers." |
|
449 | help="Switch modes for the IPython exception handlers." | |
445 | ).tag(config=True) |
|
450 | ).tag(config=True) | |
446 |
|
451 | |||
447 | # Subcomponents of InteractiveShell |
|
452 | # Subcomponents of InteractiveShell | |
448 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) |
|
453 | alias_manager = Instance('IPython.core.alias.AliasManager', allow_none=True) | |
449 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) |
|
454 | prefilter_manager = Instance('IPython.core.prefilter.PrefilterManager', allow_none=True) | |
450 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) |
|
455 | builtin_trap = Instance('IPython.core.builtin_trap.BuiltinTrap', allow_none=True) | |
451 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) |
|
456 | display_trap = Instance('IPython.core.display_trap.DisplayTrap', allow_none=True) | |
452 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) |
|
457 | extension_manager = Instance('IPython.core.extensions.ExtensionManager', allow_none=True) | |
453 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) |
|
458 | payload_manager = Instance('IPython.core.payload.PayloadManager', allow_none=True) | |
454 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) |
|
459 | history_manager = Instance('IPython.core.history.HistoryAccessorBase', allow_none=True) | |
455 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) |
|
460 | magics_manager = Instance('IPython.core.magic.MagicsManager', allow_none=True) | |
456 |
|
461 | |||
457 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) |
|
462 | profile_dir = Instance('IPython.core.application.ProfileDir', allow_none=True) | |
458 | @property |
|
463 | @property | |
459 | def profile(self): |
|
464 | def profile(self): | |
460 | if self.profile_dir is not None: |
|
465 | if self.profile_dir is not None: | |
461 | name = os.path.basename(self.profile_dir.location) |
|
466 | name = os.path.basename(self.profile_dir.location) | |
462 | return name.replace('profile_','') |
|
467 | return name.replace('profile_','') | |
463 |
|
468 | |||
464 |
|
469 | |||
465 | # Private interface |
|
470 | # Private interface | |
466 | _post_execute = Dict() |
|
471 | _post_execute = Dict() | |
467 |
|
472 | |||
468 | # Tracks any GUI loop loaded for pylab |
|
473 | # Tracks any GUI loop loaded for pylab | |
469 | pylab_gui_select = None |
|
474 | pylab_gui_select = None | |
470 |
|
475 | |||
471 | last_execution_succeeded = Bool(True, help='Did last executed command succeeded') |
|
476 | last_execution_succeeded = Bool(True, help='Did last executed command succeeded') | |
472 |
|
477 | |||
473 | last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True) |
|
478 | last_execution_result = Instance('IPython.core.interactiveshell.ExecutionResult', help='Result of executing the last command', allow_none=True) | |
474 |
|
479 | |||
475 | def __init__(self, ipython_dir=None, profile_dir=None, |
|
480 | def __init__(self, ipython_dir=None, profile_dir=None, | |
476 | user_module=None, user_ns=None, |
|
481 | user_module=None, user_ns=None, | |
477 | custom_exceptions=((), None), **kwargs): |
|
482 | custom_exceptions=((), None), **kwargs): | |
478 |
|
483 | |||
479 | # This is where traits with a config_key argument are updated |
|
484 | # This is where traits with a config_key argument are updated | |
480 | # from the values on config. |
|
485 | # from the values on config. | |
481 | super(InteractiveShell, self).__init__(**kwargs) |
|
486 | super(InteractiveShell, self).__init__(**kwargs) | |
482 | if 'PromptManager' in self.config: |
|
487 | if 'PromptManager' in self.config: | |
483 | warn('As of IPython 5.0 `PromptManager` config will have no effect' |
|
488 | warn('As of IPython 5.0 `PromptManager` config will have no effect' | |
484 | ' and has been replaced by TerminalInteractiveShell.prompts_class') |
|
489 | ' and has been replaced by TerminalInteractiveShell.prompts_class') | |
485 | self.configurables = [self] |
|
490 | self.configurables = [self] | |
486 |
|
491 | |||
487 | # These are relatively independent and stateless |
|
492 | # These are relatively independent and stateless | |
488 | self.init_ipython_dir(ipython_dir) |
|
493 | self.init_ipython_dir(ipython_dir) | |
489 | self.init_profile_dir(profile_dir) |
|
494 | self.init_profile_dir(profile_dir) | |
490 | self.init_instance_attrs() |
|
495 | self.init_instance_attrs() | |
491 | self.init_environment() |
|
496 | self.init_environment() | |
492 |
|
497 | |||
493 | # Check if we're in a virtualenv, and set up sys.path. |
|
498 | # Check if we're in a virtualenv, and set up sys.path. | |
494 | self.init_virtualenv() |
|
499 | self.init_virtualenv() | |
495 |
|
500 | |||
496 | # Create namespaces (user_ns, user_global_ns, etc.) |
|
501 | # Create namespaces (user_ns, user_global_ns, etc.) | |
497 | self.init_create_namespaces(user_module, user_ns) |
|
502 | self.init_create_namespaces(user_module, user_ns) | |
498 | # This has to be done after init_create_namespaces because it uses |
|
503 | # This has to be done after init_create_namespaces because it uses | |
499 | # something in self.user_ns, but before init_sys_modules, which |
|
504 | # something in self.user_ns, but before init_sys_modules, which | |
500 | # is the first thing to modify sys. |
|
505 | # is the first thing to modify sys. | |
501 | # TODO: When we override sys.stdout and sys.stderr before this class |
|
506 | # TODO: When we override sys.stdout and sys.stderr before this class | |
502 | # is created, we are saving the overridden ones here. Not sure if this |
|
507 | # is created, we are saving the overridden ones here. Not sure if this | |
503 | # is what we want to do. |
|
508 | # is what we want to do. | |
504 | self.save_sys_module_state() |
|
509 | self.save_sys_module_state() | |
505 | self.init_sys_modules() |
|
510 | self.init_sys_modules() | |
506 |
|
511 | |||
507 | # While we're trying to have each part of the code directly access what |
|
512 | # While we're trying to have each part of the code directly access what | |
508 | # it needs without keeping redundant references to objects, we have too |
|
513 | # it needs without keeping redundant references to objects, we have too | |
509 | # much legacy code that expects ip.db to exist. |
|
514 | # much legacy code that expects ip.db to exist. | |
510 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) |
|
515 | self.db = PickleShareDB(os.path.join(self.profile_dir.location, 'db')) | |
511 |
|
516 | |||
512 | self.init_history() |
|
517 | self.init_history() | |
513 | self.init_encoding() |
|
518 | self.init_encoding() | |
514 | self.init_prefilter() |
|
519 | self.init_prefilter() | |
515 |
|
520 | |||
516 | self.init_syntax_highlighting() |
|
521 | self.init_syntax_highlighting() | |
517 | self.init_hooks() |
|
522 | self.init_hooks() | |
518 | self.init_events() |
|
523 | self.init_events() | |
519 | self.init_pushd_popd_magic() |
|
524 | self.init_pushd_popd_magic() | |
520 | self.init_user_ns() |
|
525 | self.init_user_ns() | |
521 | self.init_logger() |
|
526 | self.init_logger() | |
522 | self.init_builtins() |
|
527 | self.init_builtins() | |
523 |
|
528 | |||
524 | # The following was in post_config_initialization |
|
529 | # The following was in post_config_initialization | |
525 | self.init_inspector() |
|
530 | self.init_inspector() | |
526 | self.raw_input_original = input |
|
531 | self.raw_input_original = input | |
527 | self.init_completer() |
|
532 | self.init_completer() | |
528 | # TODO: init_io() needs to happen before init_traceback handlers |
|
533 | # TODO: init_io() needs to happen before init_traceback handlers | |
529 | # because the traceback handlers hardcode the stdout/stderr streams. |
|
534 | # because the traceback handlers hardcode the stdout/stderr streams. | |
530 | # This logic in in debugger.Pdb and should eventually be changed. |
|
535 | # This logic in in debugger.Pdb and should eventually be changed. | |
531 | self.init_io() |
|
536 | self.init_io() | |
532 | self.init_traceback_handlers(custom_exceptions) |
|
537 | self.init_traceback_handlers(custom_exceptions) | |
533 | self.init_prompts() |
|
538 | self.init_prompts() | |
534 | self.init_display_formatter() |
|
539 | self.init_display_formatter() | |
535 | self.init_display_pub() |
|
540 | self.init_display_pub() | |
536 | self.init_data_pub() |
|
541 | self.init_data_pub() | |
537 | self.init_displayhook() |
|
542 | self.init_displayhook() | |
538 | self.init_magics() |
|
543 | self.init_magics() | |
539 | self.init_alias() |
|
544 | self.init_alias() | |
540 | self.init_logstart() |
|
545 | self.init_logstart() | |
541 | self.init_pdb() |
|
546 | self.init_pdb() | |
542 | self.init_extension_manager() |
|
547 | self.init_extension_manager() | |
543 | self.init_payload() |
|
548 | self.init_payload() | |
544 | self.init_deprecation_warnings() |
|
549 | self.init_deprecation_warnings() | |
545 | self.hooks.late_startup_hook() |
|
550 | self.hooks.late_startup_hook() | |
546 | self.events.trigger('shell_initialized', self) |
|
551 | self.events.trigger('shell_initialized', self) | |
547 | atexit.register(self.atexit_operations) |
|
552 | atexit.register(self.atexit_operations) | |
548 |
|
553 | |||
549 | def get_ipython(self): |
|
554 | def get_ipython(self): | |
550 | """Return the currently running IPython instance.""" |
|
555 | """Return the currently running IPython instance.""" | |
551 | return self |
|
556 | return self | |
552 |
|
557 | |||
553 | #------------------------------------------------------------------------- |
|
558 | #------------------------------------------------------------------------- | |
554 | # Trait changed handlers |
|
559 | # Trait changed handlers | |
555 | #------------------------------------------------------------------------- |
|
560 | #------------------------------------------------------------------------- | |
556 | @observe('ipython_dir') |
|
561 | @observe('ipython_dir') | |
557 | def _ipython_dir_changed(self, change): |
|
562 | def _ipython_dir_changed(self, change): | |
558 | ensure_dir_exists(change['new']) |
|
563 | ensure_dir_exists(change['new']) | |
559 |
|
564 | |||
560 | def set_autoindent(self,value=None): |
|
565 | def set_autoindent(self,value=None): | |
561 | """Set the autoindent flag. |
|
566 | """Set the autoindent flag. | |
562 |
|
567 | |||
563 | If called with no arguments, it acts as a toggle.""" |
|
568 | If called with no arguments, it acts as a toggle.""" | |
564 | if value is None: |
|
569 | if value is None: | |
565 | self.autoindent = not self.autoindent |
|
570 | self.autoindent = not self.autoindent | |
566 | else: |
|
571 | else: | |
567 | self.autoindent = value |
|
572 | self.autoindent = value | |
568 |
|
573 | |||
569 | #------------------------------------------------------------------------- |
|
574 | #------------------------------------------------------------------------- | |
570 | # init_* methods called by __init__ |
|
575 | # init_* methods called by __init__ | |
571 | #------------------------------------------------------------------------- |
|
576 | #------------------------------------------------------------------------- | |
572 |
|
577 | |||
573 | def init_ipython_dir(self, ipython_dir): |
|
578 | def init_ipython_dir(self, ipython_dir): | |
574 | if ipython_dir is not None: |
|
579 | if ipython_dir is not None: | |
575 | self.ipython_dir = ipython_dir |
|
580 | self.ipython_dir = ipython_dir | |
576 | return |
|
581 | return | |
577 |
|
582 | |||
578 | self.ipython_dir = get_ipython_dir() |
|
583 | self.ipython_dir = get_ipython_dir() | |
579 |
|
584 | |||
580 | def init_profile_dir(self, profile_dir): |
|
585 | def init_profile_dir(self, profile_dir): | |
581 | if profile_dir is not None: |
|
586 | if profile_dir is not None: | |
582 | self.profile_dir = profile_dir |
|
587 | self.profile_dir = profile_dir | |
583 | return |
|
588 | return | |
584 | self.profile_dir =\ |
|
589 | self.profile_dir =\ | |
585 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') |
|
590 | ProfileDir.create_profile_dir_by_name(self.ipython_dir, 'default') | |
586 |
|
591 | |||
587 | def init_instance_attrs(self): |
|
592 | def init_instance_attrs(self): | |
588 | self.more = False |
|
593 | self.more = False | |
589 |
|
594 | |||
590 | # command compiler |
|
595 | # command compiler | |
591 | self.compile = CachingCompiler() |
|
596 | self.compile = CachingCompiler() | |
592 |
|
597 | |||
593 | # Make an empty namespace, which extension writers can rely on both |
|
598 | # Make an empty namespace, which extension writers can rely on both | |
594 | # existing and NEVER being used by ipython itself. This gives them a |
|
599 | # existing and NEVER being used by ipython itself. This gives them a | |
595 | # convenient location for storing additional information and state |
|
600 | # convenient location for storing additional information and state | |
596 | # their extensions may require, without fear of collisions with other |
|
601 | # their extensions may require, without fear of collisions with other | |
597 | # ipython names that may develop later. |
|
602 | # ipython names that may develop later. | |
598 | self.meta = Struct() |
|
603 | self.meta = Struct() | |
599 |
|
604 | |||
600 | # Temporary files used for various purposes. Deleted at exit. |
|
605 | # Temporary files used for various purposes. Deleted at exit. | |
601 | self.tempfiles = [] |
|
606 | self.tempfiles = [] | |
602 | self.tempdirs = [] |
|
607 | self.tempdirs = [] | |
603 |
|
608 | |||
604 | # keep track of where we started running (mainly for crash post-mortem) |
|
609 | # keep track of where we started running (mainly for crash post-mortem) | |
605 | # This is not being used anywhere currently. |
|
610 | # This is not being used anywhere currently. | |
606 | self.starting_dir = os.getcwd() |
|
611 | self.starting_dir = os.getcwd() | |
607 |
|
612 | |||
608 | # Indentation management |
|
613 | # Indentation management | |
609 | self.indent_current_nsp = 0 |
|
614 | self.indent_current_nsp = 0 | |
610 |
|
615 | |||
611 | # Dict to track post-execution functions that have been registered |
|
616 | # Dict to track post-execution functions that have been registered | |
612 | self._post_execute = {} |
|
617 | self._post_execute = {} | |
613 |
|
618 | |||
614 | def init_environment(self): |
|
619 | def init_environment(self): | |
615 | """Any changes we need to make to the user's environment.""" |
|
620 | """Any changes we need to make to the user's environment.""" | |
616 | pass |
|
621 | pass | |
617 |
|
622 | |||
618 | def init_encoding(self): |
|
623 | def init_encoding(self): | |
619 | # Get system encoding at startup time. Certain terminals (like Emacs |
|
624 | # Get system encoding at startup time. Certain terminals (like Emacs | |
620 | # under Win32 have it set to None, and we need to have a known valid |
|
625 | # under Win32 have it set to None, and we need to have a known valid | |
621 | # encoding to use in the raw_input() method |
|
626 | # encoding to use in the raw_input() method | |
622 | try: |
|
627 | try: | |
623 | self.stdin_encoding = sys.stdin.encoding or 'ascii' |
|
628 | self.stdin_encoding = sys.stdin.encoding or 'ascii' | |
624 | except AttributeError: |
|
629 | except AttributeError: | |
625 | self.stdin_encoding = 'ascii' |
|
630 | self.stdin_encoding = 'ascii' | |
626 |
|
631 | |||
627 |
|
632 | |||
628 | @observe('colors') |
|
633 | @observe('colors') | |
629 | def init_syntax_highlighting(self, changes=None): |
|
634 | def init_syntax_highlighting(self, changes=None): | |
630 | # Python source parser/formatter for syntax highlighting |
|
635 | # Python source parser/formatter for syntax highlighting | |
631 | pyformat = PyColorize.Parser(style=self.colors, parent=self).format |
|
636 | pyformat = PyColorize.Parser(style=self.colors, parent=self).format | |
632 | self.pycolorize = lambda src: pyformat(src,'str') |
|
637 | self.pycolorize = lambda src: pyformat(src,'str') | |
633 |
|
638 | |||
634 | def refresh_style(self): |
|
639 | def refresh_style(self): | |
635 | # No-op here, used in subclass |
|
640 | # No-op here, used in subclass | |
636 | pass |
|
641 | pass | |
637 |
|
642 | |||
638 | def init_pushd_popd_magic(self): |
|
643 | def init_pushd_popd_magic(self): | |
639 | # for pushd/popd management |
|
644 | # for pushd/popd management | |
640 | self.home_dir = get_home_dir() |
|
645 | self.home_dir = get_home_dir() | |
641 |
|
646 | |||
642 | self.dir_stack = [] |
|
647 | self.dir_stack = [] | |
643 |
|
648 | |||
644 | def init_logger(self): |
|
649 | def init_logger(self): | |
645 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', |
|
650 | self.logger = Logger(self.home_dir, logfname='ipython_log.py', | |
646 | logmode='rotate') |
|
651 | logmode='rotate') | |
647 |
|
652 | |||
648 | def init_logstart(self): |
|
653 | def init_logstart(self): | |
649 | """Initialize logging in case it was requested at the command line. |
|
654 | """Initialize logging in case it was requested at the command line. | |
650 | """ |
|
655 | """ | |
651 | if self.logappend: |
|
656 | if self.logappend: | |
652 | self.magic('logstart %s append' % self.logappend) |
|
657 | self.magic('logstart %s append' % self.logappend) | |
653 | elif self.logfile: |
|
658 | elif self.logfile: | |
654 | self.magic('logstart %s' % self.logfile) |
|
659 | self.magic('logstart %s' % self.logfile) | |
655 | elif self.logstart: |
|
660 | elif self.logstart: | |
656 | self.magic('logstart') |
|
661 | self.magic('logstart') | |
657 |
|
662 | |||
658 | def init_deprecation_warnings(self): |
|
663 | def init_deprecation_warnings(self): | |
659 | """ |
|
664 | """ | |
660 | register default filter for deprecation warning. |
|
665 | register default filter for deprecation warning. | |
661 |
|
666 | |||
662 | This will allow deprecation warning of function used interactively to show |
|
667 | This will allow deprecation warning of function used interactively to show | |
663 | warning to users, and still hide deprecation warning from libraries import. |
|
668 | warning to users, and still hide deprecation warning from libraries import. | |
664 | """ |
|
669 | """ | |
665 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) |
|
670 | warnings.filterwarnings("default", category=DeprecationWarning, module=self.user_ns.get("__name__")) | |
666 |
|
671 | |||
667 | def init_builtins(self): |
|
672 | def init_builtins(self): | |
668 | # A single, static flag that we set to True. Its presence indicates |
|
673 | # A single, static flag that we set to True. Its presence indicates | |
669 | # that an IPython shell has been created, and we make no attempts at |
|
674 | # that an IPython shell has been created, and we make no attempts at | |
670 | # removing on exit or representing the existence of more than one |
|
675 | # removing on exit or representing the existence of more than one | |
671 | # IPython at a time. |
|
676 | # IPython at a time. | |
672 | builtin_mod.__dict__['__IPYTHON__'] = True |
|
677 | builtin_mod.__dict__['__IPYTHON__'] = True | |
673 | builtin_mod.__dict__['display'] = display |
|
678 | builtin_mod.__dict__['display'] = display | |
674 |
|
679 | |||
675 | self.builtin_trap = BuiltinTrap(shell=self) |
|
680 | self.builtin_trap = BuiltinTrap(shell=self) | |
676 |
|
681 | |||
677 | @observe('colors') |
|
682 | @observe('colors') | |
678 | def init_inspector(self, changes=None): |
|
683 | def init_inspector(self, changes=None): | |
679 | # Object inspector |
|
684 | # Object inspector | |
680 | self.inspector = oinspect.Inspector(oinspect.InspectColors, |
|
685 | self.inspector = oinspect.Inspector(oinspect.InspectColors, | |
681 | PyColorize.ANSICodeColors, |
|
686 | PyColorize.ANSICodeColors, | |
682 | self.colors, |
|
687 | self.colors, | |
683 | self.object_info_string_level) |
|
688 | self.object_info_string_level) | |
684 |
|
689 | |||
685 | def init_io(self): |
|
690 | def init_io(self): | |
686 | # This will just use sys.stdout and sys.stderr. If you want to |
|
691 | # This will just use sys.stdout and sys.stderr. If you want to | |
687 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
692 | # override sys.stdout and sys.stderr themselves, you need to do that | |
688 | # *before* instantiating this class, because io holds onto |
|
693 | # *before* instantiating this class, because io holds onto | |
689 | # references to the underlying streams. |
|
694 | # references to the underlying streams. | |
690 | # io.std* are deprecated, but don't show our own deprecation warnings |
|
695 | # io.std* are deprecated, but don't show our own deprecation warnings | |
691 | # during initialization of the deprecated API. |
|
696 | # during initialization of the deprecated API. | |
692 | with warnings.catch_warnings(): |
|
697 | with warnings.catch_warnings(): | |
693 | warnings.simplefilter('ignore', DeprecationWarning) |
|
698 | warnings.simplefilter('ignore', DeprecationWarning) | |
694 | io.stdout = io.IOStream(sys.stdout) |
|
699 | io.stdout = io.IOStream(sys.stdout) | |
695 | io.stderr = io.IOStream(sys.stderr) |
|
700 | io.stderr = io.IOStream(sys.stderr) | |
696 |
|
701 | |||
697 | def init_prompts(self): |
|
702 | def init_prompts(self): | |
698 | # Set system prompts, so that scripts can decide if they are running |
|
703 | # Set system prompts, so that scripts can decide if they are running | |
699 | # interactively. |
|
704 | # interactively. | |
700 | sys.ps1 = 'In : ' |
|
705 | sys.ps1 = 'In : ' | |
701 | sys.ps2 = '...: ' |
|
706 | sys.ps2 = '...: ' | |
702 | sys.ps3 = 'Out: ' |
|
707 | sys.ps3 = 'Out: ' | |
703 |
|
708 | |||
704 | def init_display_formatter(self): |
|
709 | def init_display_formatter(self): | |
705 | self.display_formatter = DisplayFormatter(parent=self) |
|
710 | self.display_formatter = DisplayFormatter(parent=self) | |
706 | self.configurables.append(self.display_formatter) |
|
711 | self.configurables.append(self.display_formatter) | |
707 |
|
712 | |||
708 | def init_display_pub(self): |
|
713 | def init_display_pub(self): | |
709 | self.display_pub = self.display_pub_class(parent=self) |
|
714 | self.display_pub = self.display_pub_class(parent=self) | |
710 | self.configurables.append(self.display_pub) |
|
715 | self.configurables.append(self.display_pub) | |
711 |
|
716 | |||
712 | def init_data_pub(self): |
|
717 | def init_data_pub(self): | |
713 | if not self.data_pub_class: |
|
718 | if not self.data_pub_class: | |
714 | self.data_pub = None |
|
719 | self.data_pub = None | |
715 | return |
|
720 | return | |
716 | self.data_pub = self.data_pub_class(parent=self) |
|
721 | self.data_pub = self.data_pub_class(parent=self) | |
717 | self.configurables.append(self.data_pub) |
|
722 | self.configurables.append(self.data_pub) | |
718 |
|
723 | |||
719 | def init_displayhook(self): |
|
724 | def init_displayhook(self): | |
720 | # Initialize displayhook, set in/out prompts and printing system |
|
725 | # Initialize displayhook, set in/out prompts and printing system | |
721 | self.displayhook = self.displayhook_class( |
|
726 | self.displayhook = self.displayhook_class( | |
722 | parent=self, |
|
727 | parent=self, | |
723 | shell=self, |
|
728 | shell=self, | |
724 | cache_size=self.cache_size, |
|
729 | cache_size=self.cache_size, | |
725 | ) |
|
730 | ) | |
726 | self.configurables.append(self.displayhook) |
|
731 | self.configurables.append(self.displayhook) | |
727 | # This is a context manager that installs/revmoes the displayhook at |
|
732 | # This is a context manager that installs/revmoes the displayhook at | |
728 | # the appropriate time. |
|
733 | # the appropriate time. | |
729 | self.display_trap = DisplayTrap(hook=self.displayhook) |
|
734 | self.display_trap = DisplayTrap(hook=self.displayhook) | |
730 |
|
735 | |||
731 | def init_virtualenv(self): |
|
736 | def init_virtualenv(self): | |
732 | """Add a virtualenv to sys.path so the user can import modules from it. |
|
737 | """Add a virtualenv to sys.path so the user can import modules from it. | |
733 | This isn't perfect: it doesn't use the Python interpreter with which the |
|
738 | This isn't perfect: it doesn't use the Python interpreter with which the | |
734 | virtualenv was built, and it ignores the --no-site-packages option. A |
|
739 | virtualenv was built, and it ignores the --no-site-packages option. A | |
735 | warning will appear suggesting the user installs IPython in the |
|
740 | warning will appear suggesting the user installs IPython in the | |
736 | virtualenv, but for many cases, it probably works well enough. |
|
741 | virtualenv, but for many cases, it probably works well enough. | |
737 |
|
742 | |||
738 | Adapted from code snippets online. |
|
743 | Adapted from code snippets online. | |
739 |
|
744 | |||
740 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv |
|
745 | http://blog.ufsoft.org/2009/1/29/ipython-and-virtualenv | |
741 | """ |
|
746 | """ | |
742 | if 'VIRTUAL_ENV' not in os.environ: |
|
747 | if 'VIRTUAL_ENV' not in os.environ: | |
743 | # Not in a virtualenv |
|
748 | # Not in a virtualenv | |
744 | return |
|
749 | return | |
745 |
|
750 | |||
746 | p = os.path.normcase(sys.executable) |
|
751 | p = os.path.normcase(sys.executable) | |
747 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) |
|
752 | p_venv = os.path.normcase(os.environ['VIRTUAL_ENV']) | |
748 |
|
753 | |||
749 | # executable path should end like /bin/python or \\scripts\\python.exe |
|
754 | # executable path should end like /bin/python or \\scripts\\python.exe | |
750 | p_exe_up2 = os.path.dirname(os.path.dirname(p)) |
|
755 | p_exe_up2 = os.path.dirname(os.path.dirname(p)) | |
751 | if p_exe_up2 and os.path.exists(p_venv) and os.path.samefile(p_exe_up2, p_venv): |
|
756 | if p_exe_up2 and os.path.exists(p_venv) and os.path.samefile(p_exe_up2, p_venv): | |
752 | # Our exe is inside the virtualenv, don't need to do anything. |
|
757 | # Our exe is inside the virtualenv, don't need to do anything. | |
753 | return |
|
758 | return | |
754 |
|
759 | |||
755 | # fallback venv detection: |
|
760 | # fallback venv detection: | |
756 | # stdlib venv may symlink sys.executable, so we can't use realpath. |
|
761 | # stdlib venv may symlink sys.executable, so we can't use realpath. | |
757 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. |
|
762 | # but others can symlink *to* the venv Python, so we can't just use sys.executable. | |
758 | # So we just check every item in the symlink tree (generally <= 3) |
|
763 | # So we just check every item in the symlink tree (generally <= 3) | |
759 | paths = [p] |
|
764 | paths = [p] | |
760 | while os.path.islink(p): |
|
765 | while os.path.islink(p): | |
761 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) |
|
766 | p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p))) | |
762 | paths.append(p) |
|
767 | paths.append(p) | |
763 |
|
768 | |||
764 | # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible |
|
769 | # In Cygwin paths like "c:\..." and '\cygdrive\c\...' are possible | |
765 | if p_venv.startswith('\\cygdrive'): |
|
770 | if p_venv.startswith('\\cygdrive'): | |
766 | p_venv = p_venv[11:] |
|
771 | p_venv = p_venv[11:] | |
767 | elif len(p_venv) >= 2 and p_venv[1] == ':': |
|
772 | elif len(p_venv) >= 2 and p_venv[1] == ':': | |
768 | p_venv = p_venv[2:] |
|
773 | p_venv = p_venv[2:] | |
769 |
|
774 | |||
770 | if any(p_venv in p for p in paths): |
|
775 | if any(p_venv in p for p in paths): | |
771 | # Running properly in the virtualenv, don't need to do anything |
|
776 | # Running properly in the virtualenv, don't need to do anything | |
772 | return |
|
777 | return | |
773 |
|
778 | |||
774 | warn("Attempting to work in a virtualenv. If you encounter problems, please " |
|
779 | warn("Attempting to work in a virtualenv. If you encounter problems, please " | |
775 | "install IPython inside the virtualenv.") |
|
780 | "install IPython inside the virtualenv.") | |
776 | if sys.platform == "win32": |
|
781 | if sys.platform == "win32": | |
777 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') |
|
782 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'Lib', 'site-packages') | |
778 | else: |
|
783 | else: | |
779 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', |
|
784 | virtual_env = os.path.join(os.environ['VIRTUAL_ENV'], 'lib', | |
780 | 'python%d.%d' % sys.version_info[:2], 'site-packages') |
|
785 | 'python%d.%d' % sys.version_info[:2], 'site-packages') | |
781 |
|
786 | |||
782 | import site |
|
787 | import site | |
783 | sys.path.insert(0, virtual_env) |
|
788 | sys.path.insert(0, virtual_env) | |
784 | site.addsitedir(virtual_env) |
|
789 | site.addsitedir(virtual_env) | |
785 |
|
790 | |||
786 | #------------------------------------------------------------------------- |
|
791 | #------------------------------------------------------------------------- | |
787 | # Things related to injections into the sys module |
|
792 | # Things related to injections into the sys module | |
788 | #------------------------------------------------------------------------- |
|
793 | #------------------------------------------------------------------------- | |
789 |
|
794 | |||
790 | def save_sys_module_state(self): |
|
795 | def save_sys_module_state(self): | |
791 | """Save the state of hooks in the sys module. |
|
796 | """Save the state of hooks in the sys module. | |
792 |
|
797 | |||
793 | This has to be called after self.user_module is created. |
|
798 | This has to be called after self.user_module is created. | |
794 | """ |
|
799 | """ | |
795 | self._orig_sys_module_state = {'stdin': sys.stdin, |
|
800 | self._orig_sys_module_state = {'stdin': sys.stdin, | |
796 | 'stdout': sys.stdout, |
|
801 | 'stdout': sys.stdout, | |
797 | 'stderr': sys.stderr, |
|
802 | 'stderr': sys.stderr, | |
798 | 'excepthook': sys.excepthook} |
|
803 | 'excepthook': sys.excepthook} | |
799 | self._orig_sys_modules_main_name = self.user_module.__name__ |
|
804 | self._orig_sys_modules_main_name = self.user_module.__name__ | |
800 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) |
|
805 | self._orig_sys_modules_main_mod = sys.modules.get(self.user_module.__name__) | |
801 |
|
806 | |||
802 | def restore_sys_module_state(self): |
|
807 | def restore_sys_module_state(self): | |
803 | """Restore the state of the sys module.""" |
|
808 | """Restore the state of the sys module.""" | |
804 | try: |
|
809 | try: | |
805 | for k, v in self._orig_sys_module_state.items(): |
|
810 | for k, v in self._orig_sys_module_state.items(): | |
806 | setattr(sys, k, v) |
|
811 | setattr(sys, k, v) | |
807 | except AttributeError: |
|
812 | except AttributeError: | |
808 | pass |
|
813 | pass | |
809 | # Reset what what done in self.init_sys_modules |
|
814 | # Reset what what done in self.init_sys_modules | |
810 | if self._orig_sys_modules_main_mod is not None: |
|
815 | if self._orig_sys_modules_main_mod is not None: | |
811 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod |
|
816 | sys.modules[self._orig_sys_modules_main_name] = self._orig_sys_modules_main_mod | |
812 |
|
817 | |||
813 | #------------------------------------------------------------------------- |
|
818 | #------------------------------------------------------------------------- | |
814 | # Things related to the banner |
|
819 | # Things related to the banner | |
815 | #------------------------------------------------------------------------- |
|
820 | #------------------------------------------------------------------------- | |
816 |
|
821 | |||
817 | @property |
|
822 | @property | |
818 | def banner(self): |
|
823 | def banner(self): | |
819 | banner = self.banner1 |
|
824 | banner = self.banner1 | |
820 | if self.profile and self.profile != 'default': |
|
825 | if self.profile and self.profile != 'default': | |
821 | banner += '\nIPython profile: %s\n' % self.profile |
|
826 | banner += '\nIPython profile: %s\n' % self.profile | |
822 | if self.banner2: |
|
827 | if self.banner2: | |
823 | banner += '\n' + self.banner2 |
|
828 | banner += '\n' + self.banner2 | |
824 | return banner |
|
829 | return banner | |
825 |
|
830 | |||
826 | def show_banner(self, banner=None): |
|
831 | def show_banner(self, banner=None): | |
827 | if banner is None: |
|
832 | if banner is None: | |
828 | banner = self.banner |
|
833 | banner = self.banner | |
829 | sys.stdout.write(banner) |
|
834 | sys.stdout.write(banner) | |
830 |
|
835 | |||
831 | #------------------------------------------------------------------------- |
|
836 | #------------------------------------------------------------------------- | |
832 | # Things related to hooks |
|
837 | # Things related to hooks | |
833 | #------------------------------------------------------------------------- |
|
838 | #------------------------------------------------------------------------- | |
834 |
|
839 | |||
835 | def init_hooks(self): |
|
840 | def init_hooks(self): | |
836 | # hooks holds pointers used for user-side customizations |
|
841 | # hooks holds pointers used for user-side customizations | |
837 | self.hooks = Struct() |
|
842 | self.hooks = Struct() | |
838 |
|
843 | |||
839 | self.strdispatchers = {} |
|
844 | self.strdispatchers = {} | |
840 |
|
845 | |||
841 | # Set all default hooks, defined in the IPython.hooks module. |
|
846 | # Set all default hooks, defined in the IPython.hooks module. | |
842 | hooks = IPython.core.hooks |
|
847 | hooks = IPython.core.hooks | |
843 | for hook_name in hooks.__all__: |
|
848 | for hook_name in hooks.__all__: | |
844 | # default hooks have priority 100, i.e. low; user hooks should have |
|
849 | # default hooks have priority 100, i.e. low; user hooks should have | |
845 | # 0-100 priority |
|
850 | # 0-100 priority | |
846 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) |
|
851 | self.set_hook(hook_name,getattr(hooks,hook_name), 100, _warn_deprecated=False) | |
847 |
|
852 | |||
848 | if self.display_page: |
|
853 | if self.display_page: | |
849 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) |
|
854 | self.set_hook('show_in_pager', page.as_hook(page.display_page), 90) | |
850 |
|
855 | |||
851 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, |
|
856 | def set_hook(self,name,hook, priority=50, str_key=None, re_key=None, | |
852 | _warn_deprecated=True): |
|
857 | _warn_deprecated=True): | |
853 | """set_hook(name,hook) -> sets an internal IPython hook. |
|
858 | """set_hook(name,hook) -> sets an internal IPython hook. | |
854 |
|
859 | |||
855 | IPython exposes some of its internal API as user-modifiable hooks. By |
|
860 | IPython exposes some of its internal API as user-modifiable hooks. By | |
856 | adding your function to one of these hooks, you can modify IPython's |
|
861 | adding your function to one of these hooks, you can modify IPython's | |
857 | behavior to call at runtime your own routines.""" |
|
862 | behavior to call at runtime your own routines.""" | |
858 |
|
863 | |||
859 | # At some point in the future, this should validate the hook before it |
|
864 | # At some point in the future, this should validate the hook before it | |
860 | # accepts it. Probably at least check that the hook takes the number |
|
865 | # accepts it. Probably at least check that the hook takes the number | |
861 | # of args it's supposed to. |
|
866 | # of args it's supposed to. | |
862 |
|
867 | |||
863 | f = types.MethodType(hook,self) |
|
868 | f = types.MethodType(hook,self) | |
864 |
|
869 | |||
865 | # check if the hook is for strdispatcher first |
|
870 | # check if the hook is for strdispatcher first | |
866 | if str_key is not None: |
|
871 | if str_key is not None: | |
867 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
872 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
868 | sdp.add_s(str_key, f, priority ) |
|
873 | sdp.add_s(str_key, f, priority ) | |
869 | self.strdispatchers[name] = sdp |
|
874 | self.strdispatchers[name] = sdp | |
870 | return |
|
875 | return | |
871 | if re_key is not None: |
|
876 | if re_key is not None: | |
872 | sdp = self.strdispatchers.get(name, StrDispatch()) |
|
877 | sdp = self.strdispatchers.get(name, StrDispatch()) | |
873 | sdp.add_re(re.compile(re_key), f, priority ) |
|
878 | sdp.add_re(re.compile(re_key), f, priority ) | |
874 | self.strdispatchers[name] = sdp |
|
879 | self.strdispatchers[name] = sdp | |
875 | return |
|
880 | return | |
876 |
|
881 | |||
877 | dp = getattr(self.hooks, name, None) |
|
882 | dp = getattr(self.hooks, name, None) | |
878 | if name not in IPython.core.hooks.__all__: |
|
883 | if name not in IPython.core.hooks.__all__: | |
879 | print("Warning! Hook '%s' is not one of %s" % \ |
|
884 | print("Warning! Hook '%s' is not one of %s" % \ | |
880 | (name, IPython.core.hooks.__all__ )) |
|
885 | (name, IPython.core.hooks.__all__ )) | |
881 |
|
886 | |||
882 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): |
|
887 | if _warn_deprecated and (name in IPython.core.hooks.deprecated): | |
883 | alternative = IPython.core.hooks.deprecated[name] |
|
888 | alternative = IPython.core.hooks.deprecated[name] | |
884 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2) |
|
889 | warn("Hook {} is deprecated. Use {} instead.".format(name, alternative), stacklevel=2) | |
885 |
|
890 | |||
886 | if not dp: |
|
891 | if not dp: | |
887 | dp = IPython.core.hooks.CommandChainDispatcher() |
|
892 | dp = IPython.core.hooks.CommandChainDispatcher() | |
888 |
|
893 | |||
889 | try: |
|
894 | try: | |
890 | dp.add(f,priority) |
|
895 | dp.add(f,priority) | |
891 | except AttributeError: |
|
896 | except AttributeError: | |
892 | # it was not commandchain, plain old func - replace |
|
897 | # it was not commandchain, plain old func - replace | |
893 | dp = f |
|
898 | dp = f | |
894 |
|
899 | |||
895 | setattr(self.hooks,name, dp) |
|
900 | setattr(self.hooks,name, dp) | |
896 |
|
901 | |||
897 | #------------------------------------------------------------------------- |
|
902 | #------------------------------------------------------------------------- | |
898 | # Things related to events |
|
903 | # Things related to events | |
899 | #------------------------------------------------------------------------- |
|
904 | #------------------------------------------------------------------------- | |
900 |
|
905 | |||
901 | def init_events(self): |
|
906 | def init_events(self): | |
902 | self.events = EventManager(self, available_events) |
|
907 | self.events = EventManager(self, available_events) | |
903 |
|
908 | |||
904 | self.events.register("pre_execute", self._clear_warning_registry) |
|
909 | self.events.register("pre_execute", self._clear_warning_registry) | |
905 |
|
910 | |||
906 | def register_post_execute(self, func): |
|
911 | def register_post_execute(self, func): | |
907 | """DEPRECATED: Use ip.events.register('post_run_cell', func) |
|
912 | """DEPRECATED: Use ip.events.register('post_run_cell', func) | |
908 |
|
913 | |||
909 | Register a function for calling after code execution. |
|
914 | Register a function for calling after code execution. | |
910 | """ |
|
915 | """ | |
911 | warn("ip.register_post_execute is deprecated, use " |
|
916 | warn("ip.register_post_execute is deprecated, use " | |
912 | "ip.events.register('post_run_cell', func) instead.", stacklevel=2) |
|
917 | "ip.events.register('post_run_cell', func) instead.", stacklevel=2) | |
913 | self.events.register('post_run_cell', func) |
|
918 | self.events.register('post_run_cell', func) | |
914 |
|
919 | |||
915 | def _clear_warning_registry(self): |
|
920 | def _clear_warning_registry(self): | |
916 | # clear the warning registry, so that different code blocks with |
|
921 | # clear the warning registry, so that different code blocks with | |
917 | # overlapping line number ranges don't cause spurious suppression of |
|
922 | # overlapping line number ranges don't cause spurious suppression of | |
918 | # warnings (see gh-6611 for details) |
|
923 | # warnings (see gh-6611 for details) | |
919 | if "__warningregistry__" in self.user_global_ns: |
|
924 | if "__warningregistry__" in self.user_global_ns: | |
920 | del self.user_global_ns["__warningregistry__"] |
|
925 | del self.user_global_ns["__warningregistry__"] | |
921 |
|
926 | |||
922 | #------------------------------------------------------------------------- |
|
927 | #------------------------------------------------------------------------- | |
923 | # Things related to the "main" module |
|
928 | # Things related to the "main" module | |
924 | #------------------------------------------------------------------------- |
|
929 | #------------------------------------------------------------------------- | |
925 |
|
930 | |||
926 | def new_main_mod(self, filename, modname): |
|
931 | def new_main_mod(self, filename, modname): | |
927 | """Return a new 'main' module object for user code execution. |
|
932 | """Return a new 'main' module object for user code execution. | |
928 |
|
933 | |||
929 | ``filename`` should be the path of the script which will be run in the |
|
934 | ``filename`` should be the path of the script which will be run in the | |
930 | module. Requests with the same filename will get the same module, with |
|
935 | module. Requests with the same filename will get the same module, with | |
931 | its namespace cleared. |
|
936 | its namespace cleared. | |
932 |
|
937 | |||
933 | ``modname`` should be the module name - normally either '__main__' or |
|
938 | ``modname`` should be the module name - normally either '__main__' or | |
934 | the basename of the file without the extension. |
|
939 | the basename of the file without the extension. | |
935 |
|
940 | |||
936 | When scripts are executed via %run, we must keep a reference to their |
|
941 | When scripts are executed via %run, we must keep a reference to their | |
937 | __main__ module around so that Python doesn't |
|
942 | __main__ module around so that Python doesn't | |
938 | clear it, rendering references to module globals useless. |
|
943 | clear it, rendering references to module globals useless. | |
939 |
|
944 | |||
940 | This method keeps said reference in a private dict, keyed by the |
|
945 | This method keeps said reference in a private dict, keyed by the | |
941 | absolute path of the script. This way, for multiple executions of the |
|
946 | absolute path of the script. This way, for multiple executions of the | |
942 | same script we only keep one copy of the namespace (the last one), |
|
947 | same script we only keep one copy of the namespace (the last one), | |
943 | thus preventing memory leaks from old references while allowing the |
|
948 | thus preventing memory leaks from old references while allowing the | |
944 | objects from the last execution to be accessible. |
|
949 | objects from the last execution to be accessible. | |
945 | """ |
|
950 | """ | |
946 | filename = os.path.abspath(filename) |
|
951 | filename = os.path.abspath(filename) | |
947 | try: |
|
952 | try: | |
948 | main_mod = self._main_mod_cache[filename] |
|
953 | main_mod = self._main_mod_cache[filename] | |
949 | except KeyError: |
|
954 | except KeyError: | |
950 | main_mod = self._main_mod_cache[filename] = types.ModuleType( |
|
955 | main_mod = self._main_mod_cache[filename] = types.ModuleType( | |
951 | modname, |
|
956 | modname, | |
952 | doc="Module created for script run in IPython") |
|
957 | doc="Module created for script run in IPython") | |
953 | else: |
|
958 | else: | |
954 | main_mod.__dict__.clear() |
|
959 | main_mod.__dict__.clear() | |
955 | main_mod.__name__ = modname |
|
960 | main_mod.__name__ = modname | |
956 |
|
961 | |||
957 | main_mod.__file__ = filename |
|
962 | main_mod.__file__ = filename | |
958 | # It seems pydoc (and perhaps others) needs any module instance to |
|
963 | # It seems pydoc (and perhaps others) needs any module instance to | |
959 | # implement a __nonzero__ method |
|
964 | # implement a __nonzero__ method | |
960 | main_mod.__nonzero__ = lambda : True |
|
965 | main_mod.__nonzero__ = lambda : True | |
961 |
|
966 | |||
962 | return main_mod |
|
967 | return main_mod | |
963 |
|
968 | |||
964 | def clear_main_mod_cache(self): |
|
969 | def clear_main_mod_cache(self): | |
965 | """Clear the cache of main modules. |
|
970 | """Clear the cache of main modules. | |
966 |
|
971 | |||
967 | Mainly for use by utilities like %reset. |
|
972 | Mainly for use by utilities like %reset. | |
968 |
|
973 | |||
969 | Examples |
|
974 | Examples | |
970 | -------- |
|
975 | -------- | |
971 |
|
976 | |||
972 | In [15]: import IPython |
|
977 | In [15]: import IPython | |
973 |
|
978 | |||
974 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') |
|
979 | In [16]: m = _ip.new_main_mod(IPython.__file__, 'IPython') | |
975 |
|
980 | |||
976 | In [17]: len(_ip._main_mod_cache) > 0 |
|
981 | In [17]: len(_ip._main_mod_cache) > 0 | |
977 | Out[17]: True |
|
982 | Out[17]: True | |
978 |
|
983 | |||
979 | In [18]: _ip.clear_main_mod_cache() |
|
984 | In [18]: _ip.clear_main_mod_cache() | |
980 |
|
985 | |||
981 | In [19]: len(_ip._main_mod_cache) == 0 |
|
986 | In [19]: len(_ip._main_mod_cache) == 0 | |
982 | Out[19]: True |
|
987 | Out[19]: True | |
983 | """ |
|
988 | """ | |
984 | self._main_mod_cache.clear() |
|
989 | self._main_mod_cache.clear() | |
985 |
|
990 | |||
986 | #------------------------------------------------------------------------- |
|
991 | #------------------------------------------------------------------------- | |
987 | # Things related to debugging |
|
992 | # Things related to debugging | |
988 | #------------------------------------------------------------------------- |
|
993 | #------------------------------------------------------------------------- | |
989 |
|
994 | |||
990 | def init_pdb(self): |
|
995 | def init_pdb(self): | |
991 | # Set calling of pdb on exceptions |
|
996 | # Set calling of pdb on exceptions | |
992 | # self.call_pdb is a property |
|
997 | # self.call_pdb is a property | |
993 | self.call_pdb = self.pdb |
|
998 | self.call_pdb = self.pdb | |
994 |
|
999 | |||
995 | def _get_call_pdb(self): |
|
1000 | def _get_call_pdb(self): | |
996 | return self._call_pdb |
|
1001 | return self._call_pdb | |
997 |
|
1002 | |||
998 | def _set_call_pdb(self,val): |
|
1003 | def _set_call_pdb(self,val): | |
999 |
|
1004 | |||
1000 | if val not in (0,1,False,True): |
|
1005 | if val not in (0,1,False,True): | |
1001 | raise ValueError('new call_pdb value must be boolean') |
|
1006 | raise ValueError('new call_pdb value must be boolean') | |
1002 |
|
1007 | |||
1003 | # store value in instance |
|
1008 | # store value in instance | |
1004 | self._call_pdb = val |
|
1009 | self._call_pdb = val | |
1005 |
|
1010 | |||
1006 | # notify the actual exception handlers |
|
1011 | # notify the actual exception handlers | |
1007 | self.InteractiveTB.call_pdb = val |
|
1012 | self.InteractiveTB.call_pdb = val | |
1008 |
|
1013 | |||
1009 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, |
|
1014 | call_pdb = property(_get_call_pdb,_set_call_pdb,None, | |
1010 | 'Control auto-activation of pdb at exceptions') |
|
1015 | 'Control auto-activation of pdb at exceptions') | |
1011 |
|
1016 | |||
1012 | def debugger(self,force=False): |
|
1017 | def debugger(self,force=False): | |
1013 | """Call the pdb debugger. |
|
1018 | """Call the pdb debugger. | |
1014 |
|
1019 | |||
1015 | Keywords: |
|
1020 | Keywords: | |
1016 |
|
1021 | |||
1017 | - force(False): by default, this routine checks the instance call_pdb |
|
1022 | - force(False): by default, this routine checks the instance call_pdb | |
1018 | flag and does not actually invoke the debugger if the flag is false. |
|
1023 | flag and does not actually invoke the debugger if the flag is false. | |
1019 | The 'force' option forces the debugger to activate even if the flag |
|
1024 | The 'force' option forces the debugger to activate even if the flag | |
1020 | is false. |
|
1025 | is false. | |
1021 | """ |
|
1026 | """ | |
1022 |
|
1027 | |||
1023 | if not (force or self.call_pdb): |
|
1028 | if not (force or self.call_pdb): | |
1024 | return |
|
1029 | return | |
1025 |
|
1030 | |||
1026 | if not hasattr(sys,'last_traceback'): |
|
1031 | if not hasattr(sys,'last_traceback'): | |
1027 | error('No traceback has been produced, nothing to debug.') |
|
1032 | error('No traceback has been produced, nothing to debug.') | |
1028 | return |
|
1033 | return | |
1029 |
|
1034 | |||
1030 | self.InteractiveTB.debugger(force=True) |
|
1035 | self.InteractiveTB.debugger(force=True) | |
1031 |
|
1036 | |||
1032 | #------------------------------------------------------------------------- |
|
1037 | #------------------------------------------------------------------------- | |
1033 | # Things related to IPython's various namespaces |
|
1038 | # Things related to IPython's various namespaces | |
1034 | #------------------------------------------------------------------------- |
|
1039 | #------------------------------------------------------------------------- | |
1035 | default_user_namespaces = True |
|
1040 | default_user_namespaces = True | |
1036 |
|
1041 | |||
1037 | def init_create_namespaces(self, user_module=None, user_ns=None): |
|
1042 | def init_create_namespaces(self, user_module=None, user_ns=None): | |
1038 | # Create the namespace where the user will operate. user_ns is |
|
1043 | # Create the namespace where the user will operate. user_ns is | |
1039 | # normally the only one used, and it is passed to the exec calls as |
|
1044 | # normally the only one used, and it is passed to the exec calls as | |
1040 | # the locals argument. But we do carry a user_global_ns namespace |
|
1045 | # the locals argument. But we do carry a user_global_ns namespace | |
1041 | # given as the exec 'globals' argument, This is useful in embedding |
|
1046 | # given as the exec 'globals' argument, This is useful in embedding | |
1042 | # situations where the ipython shell opens in a context where the |
|
1047 | # situations where the ipython shell opens in a context where the | |
1043 | # distinction between locals and globals is meaningful. For |
|
1048 | # distinction between locals and globals is meaningful. For | |
1044 | # non-embedded contexts, it is just the same object as the user_ns dict. |
|
1049 | # non-embedded contexts, it is just the same object as the user_ns dict. | |
1045 |
|
1050 | |||
1046 | # FIXME. For some strange reason, __builtins__ is showing up at user |
|
1051 | # FIXME. For some strange reason, __builtins__ is showing up at user | |
1047 | # level as a dict instead of a module. This is a manual fix, but I |
|
1052 | # level as a dict instead of a module. This is a manual fix, but I | |
1048 | # should really track down where the problem is coming from. Alex |
|
1053 | # should really track down where the problem is coming from. Alex | |
1049 | # Schmolck reported this problem first. |
|
1054 | # Schmolck reported this problem first. | |
1050 |
|
1055 | |||
1051 | # A useful post by Alex Martelli on this topic: |
|
1056 | # A useful post by Alex Martelli on this topic: | |
1052 | # Re: inconsistent value from __builtins__ |
|
1057 | # Re: inconsistent value from __builtins__ | |
1053 | # Von: Alex Martelli <aleaxit@yahoo.com> |
|
1058 | # Von: Alex Martelli <aleaxit@yahoo.com> | |
1054 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends |
|
1059 | # Datum: Freitag 01 Oktober 2004 04:45:34 nachmittags/abends | |
1055 | # Gruppen: comp.lang.python |
|
1060 | # Gruppen: comp.lang.python | |
1056 |
|
1061 | |||
1057 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: |
|
1062 | # Michael Hohn <hohn@hooknose.lbl.gov> wrote: | |
1058 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) |
|
1063 | # > >>> print type(builtin_check.get_global_binding('__builtins__')) | |
1059 | # > <type 'dict'> |
|
1064 | # > <type 'dict'> | |
1060 | # > >>> print type(__builtins__) |
|
1065 | # > >>> print type(__builtins__) | |
1061 | # > <type 'module'> |
|
1066 | # > <type 'module'> | |
1062 | # > Is this difference in return value intentional? |
|
1067 | # > Is this difference in return value intentional? | |
1063 |
|
1068 | |||
1064 | # Well, it's documented that '__builtins__' can be either a dictionary |
|
1069 | # Well, it's documented that '__builtins__' can be either a dictionary | |
1065 | # or a module, and it's been that way for a long time. Whether it's |
|
1070 | # or a module, and it's been that way for a long time. Whether it's | |
1066 | # intentional (or sensible), I don't know. In any case, the idea is |
|
1071 | # intentional (or sensible), I don't know. In any case, the idea is | |
1067 | # that if you need to access the built-in namespace directly, you |
|
1072 | # that if you need to access the built-in namespace directly, you | |
1068 | # should start with "import __builtin__" (note, no 's') which will |
|
1073 | # should start with "import __builtin__" (note, no 's') which will | |
1069 | # definitely give you a module. Yeah, it's somewhat confusing:-(. |
|
1074 | # definitely give you a module. Yeah, it's somewhat confusing:-(. | |
1070 |
|
1075 | |||
1071 | # These routines return a properly built module and dict as needed by |
|
1076 | # These routines return a properly built module and dict as needed by | |
1072 | # the rest of the code, and can also be used by extension writers to |
|
1077 | # the rest of the code, and can also be used by extension writers to | |
1073 | # generate properly initialized namespaces. |
|
1078 | # generate properly initialized namespaces. | |
1074 | if (user_ns is not None) or (user_module is not None): |
|
1079 | if (user_ns is not None) or (user_module is not None): | |
1075 | self.default_user_namespaces = False |
|
1080 | self.default_user_namespaces = False | |
1076 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) |
|
1081 | self.user_module, self.user_ns = self.prepare_user_module(user_module, user_ns) | |
1077 |
|
1082 | |||
1078 | # A record of hidden variables we have added to the user namespace, so |
|
1083 | # A record of hidden variables we have added to the user namespace, so | |
1079 | # we can list later only variables defined in actual interactive use. |
|
1084 | # we can list later only variables defined in actual interactive use. | |
1080 | self.user_ns_hidden = {} |
|
1085 | self.user_ns_hidden = {} | |
1081 |
|
1086 | |||
1082 | # Now that FakeModule produces a real module, we've run into a nasty |
|
1087 | # Now that FakeModule produces a real module, we've run into a nasty | |
1083 | # problem: after script execution (via %run), the module where the user |
|
1088 | # problem: after script execution (via %run), the module where the user | |
1084 | # code ran is deleted. Now that this object is a true module (needed |
|
1089 | # code ran is deleted. Now that this object is a true module (needed | |
1085 | # so doctest and other tools work correctly), the Python module |
|
1090 | # so doctest and other tools work correctly), the Python module | |
1086 | # teardown mechanism runs over it, and sets to None every variable |
|
1091 | # teardown mechanism runs over it, and sets to None every variable | |
1087 | # present in that module. Top-level references to objects from the |
|
1092 | # present in that module. Top-level references to objects from the | |
1088 | # script survive, because the user_ns is updated with them. However, |
|
1093 | # script survive, because the user_ns is updated with them. However, | |
1089 | # calling functions defined in the script that use other things from |
|
1094 | # calling functions defined in the script that use other things from | |
1090 | # the script will fail, because the function's closure had references |
|
1095 | # the script will fail, because the function's closure had references | |
1091 | # to the original objects, which are now all None. So we must protect |
|
1096 | # to the original objects, which are now all None. So we must protect | |
1092 | # these modules from deletion by keeping a cache. |
|
1097 | # these modules from deletion by keeping a cache. | |
1093 | # |
|
1098 | # | |
1094 | # To avoid keeping stale modules around (we only need the one from the |
|
1099 | # To avoid keeping stale modules around (we only need the one from the | |
1095 | # last run), we use a dict keyed with the full path to the script, so |
|
1100 | # last run), we use a dict keyed with the full path to the script, so | |
1096 | # only the last version of the module is held in the cache. Note, |
|
1101 | # only the last version of the module is held in the cache. Note, | |
1097 | # however, that we must cache the module *namespace contents* (their |
|
1102 | # however, that we must cache the module *namespace contents* (their | |
1098 | # __dict__). Because if we try to cache the actual modules, old ones |
|
1103 | # __dict__). Because if we try to cache the actual modules, old ones | |
1099 | # (uncached) could be destroyed while still holding references (such as |
|
1104 | # (uncached) could be destroyed while still holding references (such as | |
1100 | # those held by GUI objects that tend to be long-lived)> |
|
1105 | # those held by GUI objects that tend to be long-lived)> | |
1101 | # |
|
1106 | # | |
1102 | # The %reset command will flush this cache. See the cache_main_mod() |
|
1107 | # The %reset command will flush this cache. See the cache_main_mod() | |
1103 | # and clear_main_mod_cache() methods for details on use. |
|
1108 | # and clear_main_mod_cache() methods for details on use. | |
1104 |
|
1109 | |||
1105 | # This is the cache used for 'main' namespaces |
|
1110 | # This is the cache used for 'main' namespaces | |
1106 | self._main_mod_cache = {} |
|
1111 | self._main_mod_cache = {} | |
1107 |
|
1112 | |||
1108 | # A table holding all the namespaces IPython deals with, so that |
|
1113 | # A table holding all the namespaces IPython deals with, so that | |
1109 | # introspection facilities can search easily. |
|
1114 | # introspection facilities can search easily. | |
1110 | self.ns_table = {'user_global':self.user_module.__dict__, |
|
1115 | self.ns_table = {'user_global':self.user_module.__dict__, | |
1111 | 'user_local':self.user_ns, |
|
1116 | 'user_local':self.user_ns, | |
1112 | 'builtin':builtin_mod.__dict__ |
|
1117 | 'builtin':builtin_mod.__dict__ | |
1113 | } |
|
1118 | } | |
1114 |
|
1119 | |||
1115 | @property |
|
1120 | @property | |
1116 | def user_global_ns(self): |
|
1121 | def user_global_ns(self): | |
1117 | return self.user_module.__dict__ |
|
1122 | return self.user_module.__dict__ | |
1118 |
|
1123 | |||
1119 | def prepare_user_module(self, user_module=None, user_ns=None): |
|
1124 | def prepare_user_module(self, user_module=None, user_ns=None): | |
1120 | """Prepare the module and namespace in which user code will be run. |
|
1125 | """Prepare the module and namespace in which user code will be run. | |
1121 |
|
1126 | |||
1122 | When IPython is started normally, both parameters are None: a new module |
|
1127 | When IPython is started normally, both parameters are None: a new module | |
1123 | is created automatically, and its __dict__ used as the namespace. |
|
1128 | is created automatically, and its __dict__ used as the namespace. | |
1124 |
|
1129 | |||
1125 | If only user_module is provided, its __dict__ is used as the namespace. |
|
1130 | If only user_module is provided, its __dict__ is used as the namespace. | |
1126 | If only user_ns is provided, a dummy module is created, and user_ns |
|
1131 | If only user_ns is provided, a dummy module is created, and user_ns | |
1127 | becomes the global namespace. If both are provided (as they may be |
|
1132 | becomes the global namespace. If both are provided (as they may be | |
1128 | when embedding), user_ns is the local namespace, and user_module |
|
1133 | when embedding), user_ns is the local namespace, and user_module | |
1129 | provides the global namespace. |
|
1134 | provides the global namespace. | |
1130 |
|
1135 | |||
1131 | Parameters |
|
1136 | Parameters | |
1132 | ---------- |
|
1137 | ---------- | |
1133 | user_module : module, optional |
|
1138 | user_module : module, optional | |
1134 | The current user module in which IPython is being run. If None, |
|
1139 | The current user module in which IPython is being run. If None, | |
1135 | a clean module will be created. |
|
1140 | a clean module will be created. | |
1136 | user_ns : dict, optional |
|
1141 | user_ns : dict, optional | |
1137 | A namespace in which to run interactive commands. |
|
1142 | A namespace in which to run interactive commands. | |
1138 |
|
1143 | |||
1139 | Returns |
|
1144 | Returns | |
1140 | ------- |
|
1145 | ------- | |
1141 | A tuple of user_module and user_ns, each properly initialised. |
|
1146 | A tuple of user_module and user_ns, each properly initialised. | |
1142 | """ |
|
1147 | """ | |
1143 | if user_module is None and user_ns is not None: |
|
1148 | if user_module is None and user_ns is not None: | |
1144 | user_ns.setdefault("__name__", "__main__") |
|
1149 | user_ns.setdefault("__name__", "__main__") | |
1145 | user_module = DummyMod() |
|
1150 | user_module = DummyMod() | |
1146 | user_module.__dict__ = user_ns |
|
1151 | user_module.__dict__ = user_ns | |
1147 |
|
1152 | |||
1148 | if user_module is None: |
|
1153 | if user_module is None: | |
1149 | user_module = types.ModuleType("__main__", |
|
1154 | user_module = types.ModuleType("__main__", | |
1150 | doc="Automatically created module for IPython interactive environment") |
|
1155 | doc="Automatically created module for IPython interactive environment") | |
1151 |
|
1156 | |||
1152 | # We must ensure that __builtin__ (without the final 's') is always |
|
1157 | # We must ensure that __builtin__ (without the final 's') is always | |
1153 | # available and pointing to the __builtin__ *module*. For more details: |
|
1158 | # available and pointing to the __builtin__ *module*. For more details: | |
1154 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1159 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1155 | user_module.__dict__.setdefault('__builtin__', builtin_mod) |
|
1160 | user_module.__dict__.setdefault('__builtin__', builtin_mod) | |
1156 | user_module.__dict__.setdefault('__builtins__', builtin_mod) |
|
1161 | user_module.__dict__.setdefault('__builtins__', builtin_mod) | |
1157 |
|
1162 | |||
1158 | if user_ns is None: |
|
1163 | if user_ns is None: | |
1159 | user_ns = user_module.__dict__ |
|
1164 | user_ns = user_module.__dict__ | |
1160 |
|
1165 | |||
1161 | return user_module, user_ns |
|
1166 | return user_module, user_ns | |
1162 |
|
1167 | |||
1163 | def init_sys_modules(self): |
|
1168 | def init_sys_modules(self): | |
1164 | # We need to insert into sys.modules something that looks like a |
|
1169 | # We need to insert into sys.modules something that looks like a | |
1165 | # module but which accesses the IPython namespace, for shelve and |
|
1170 | # module but which accesses the IPython namespace, for shelve and | |
1166 | # pickle to work interactively. Normally they rely on getting |
|
1171 | # pickle to work interactively. Normally they rely on getting | |
1167 | # everything out of __main__, but for embedding purposes each IPython |
|
1172 | # everything out of __main__, but for embedding purposes each IPython | |
1168 | # instance has its own private namespace, so we can't go shoving |
|
1173 | # instance has its own private namespace, so we can't go shoving | |
1169 | # everything into __main__. |
|
1174 | # everything into __main__. | |
1170 |
|
1175 | |||
1171 | # note, however, that we should only do this for non-embedded |
|
1176 | # note, however, that we should only do this for non-embedded | |
1172 | # ipythons, which really mimic the __main__.__dict__ with their own |
|
1177 | # ipythons, which really mimic the __main__.__dict__ with their own | |
1173 | # namespace. Embedded instances, on the other hand, should not do |
|
1178 | # namespace. Embedded instances, on the other hand, should not do | |
1174 | # this because they need to manage the user local/global namespaces |
|
1179 | # this because they need to manage the user local/global namespaces | |
1175 | # only, but they live within a 'normal' __main__ (meaning, they |
|
1180 | # only, but they live within a 'normal' __main__ (meaning, they | |
1176 | # shouldn't overtake the execution environment of the script they're |
|
1181 | # shouldn't overtake the execution environment of the script they're | |
1177 | # embedded in). |
|
1182 | # embedded in). | |
1178 |
|
1183 | |||
1179 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. |
|
1184 | # This is overridden in the InteractiveShellEmbed subclass to a no-op. | |
1180 | main_name = self.user_module.__name__ |
|
1185 | main_name = self.user_module.__name__ | |
1181 | sys.modules[main_name] = self.user_module |
|
1186 | sys.modules[main_name] = self.user_module | |
1182 |
|
1187 | |||
1183 | def init_user_ns(self): |
|
1188 | def init_user_ns(self): | |
1184 | """Initialize all user-visible namespaces to their minimum defaults. |
|
1189 | """Initialize all user-visible namespaces to their minimum defaults. | |
1185 |
|
1190 | |||
1186 | Certain history lists are also initialized here, as they effectively |
|
1191 | Certain history lists are also initialized here, as they effectively | |
1187 | act as user namespaces. |
|
1192 | act as user namespaces. | |
1188 |
|
1193 | |||
1189 | Notes |
|
1194 | Notes | |
1190 | ----- |
|
1195 | ----- | |
1191 | All data structures here are only filled in, they are NOT reset by this |
|
1196 | All data structures here are only filled in, they are NOT reset by this | |
1192 | method. If they were not empty before, data will simply be added to |
|
1197 | method. If they were not empty before, data will simply be added to | |
1193 | them. |
|
1198 | them. | |
1194 | """ |
|
1199 | """ | |
1195 | # This function works in two parts: first we put a few things in |
|
1200 | # This function works in two parts: first we put a few things in | |
1196 | # user_ns, and we sync that contents into user_ns_hidden so that these |
|
1201 | # user_ns, and we sync that contents into user_ns_hidden so that these | |
1197 | # initial variables aren't shown by %who. After the sync, we add the |
|
1202 | # initial variables aren't shown by %who. After the sync, we add the | |
1198 | # rest of what we *do* want the user to see with %who even on a new |
|
1203 | # rest of what we *do* want the user to see with %who even on a new | |
1199 | # session (probably nothing, so they really only see their own stuff) |
|
1204 | # session (probably nothing, so they really only see their own stuff) | |
1200 |
|
1205 | |||
1201 | # The user dict must *always* have a __builtin__ reference to the |
|
1206 | # The user dict must *always* have a __builtin__ reference to the | |
1202 | # Python standard __builtin__ namespace, which must be imported. |
|
1207 | # Python standard __builtin__ namespace, which must be imported. | |
1203 | # This is so that certain operations in prompt evaluation can be |
|
1208 | # This is so that certain operations in prompt evaluation can be | |
1204 | # reliably executed with builtins. Note that we can NOT use |
|
1209 | # reliably executed with builtins. Note that we can NOT use | |
1205 | # __builtins__ (note the 's'), because that can either be a dict or a |
|
1210 | # __builtins__ (note the 's'), because that can either be a dict or a | |
1206 | # module, and can even mutate at runtime, depending on the context |
|
1211 | # module, and can even mutate at runtime, depending on the context | |
1207 | # (Python makes no guarantees on it). In contrast, __builtin__ is |
|
1212 | # (Python makes no guarantees on it). In contrast, __builtin__ is | |
1208 | # always a module object, though it must be explicitly imported. |
|
1213 | # always a module object, though it must be explicitly imported. | |
1209 |
|
1214 | |||
1210 | # For more details: |
|
1215 | # For more details: | |
1211 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html |
|
1216 | # http://mail.python.org/pipermail/python-dev/2001-April/014068.html | |
1212 | ns = {} |
|
1217 | ns = {} | |
1213 |
|
1218 | |||
1214 | # make global variables for user access to the histories |
|
1219 | # make global variables for user access to the histories | |
1215 | ns['_ih'] = self.history_manager.input_hist_parsed |
|
1220 | ns['_ih'] = self.history_manager.input_hist_parsed | |
1216 | ns['_oh'] = self.history_manager.output_hist |
|
1221 | ns['_oh'] = self.history_manager.output_hist | |
1217 | ns['_dh'] = self.history_manager.dir_hist |
|
1222 | ns['_dh'] = self.history_manager.dir_hist | |
1218 |
|
1223 | |||
1219 | # user aliases to input and output histories. These shouldn't show up |
|
1224 | # user aliases to input and output histories. These shouldn't show up | |
1220 | # in %who, as they can have very large reprs. |
|
1225 | # in %who, as they can have very large reprs. | |
1221 | ns['In'] = self.history_manager.input_hist_parsed |
|
1226 | ns['In'] = self.history_manager.input_hist_parsed | |
1222 | ns['Out'] = self.history_manager.output_hist |
|
1227 | ns['Out'] = self.history_manager.output_hist | |
1223 |
|
1228 | |||
1224 | # Store myself as the public api!!! |
|
1229 | # Store myself as the public api!!! | |
1225 | ns['get_ipython'] = self.get_ipython |
|
1230 | ns['get_ipython'] = self.get_ipython | |
1226 |
|
1231 | |||
1227 | ns['exit'] = self.exiter |
|
1232 | ns['exit'] = self.exiter | |
1228 | ns['quit'] = self.exiter |
|
1233 | ns['quit'] = self.exiter | |
1229 |
|
1234 | |||
1230 | # Sync what we've added so far to user_ns_hidden so these aren't seen |
|
1235 | # Sync what we've added so far to user_ns_hidden so these aren't seen | |
1231 | # by %who |
|
1236 | # by %who | |
1232 | self.user_ns_hidden.update(ns) |
|
1237 | self.user_ns_hidden.update(ns) | |
1233 |
|
1238 | |||
1234 | # Anything put into ns now would show up in %who. Think twice before |
|
1239 | # Anything put into ns now would show up in %who. Think twice before | |
1235 | # putting anything here, as we really want %who to show the user their |
|
1240 | # putting anything here, as we really want %who to show the user their | |
1236 | # stuff, not our variables. |
|
1241 | # stuff, not our variables. | |
1237 |
|
1242 | |||
1238 | # Finally, update the real user's namespace |
|
1243 | # Finally, update the real user's namespace | |
1239 | self.user_ns.update(ns) |
|
1244 | self.user_ns.update(ns) | |
1240 |
|
1245 | |||
1241 | @property |
|
1246 | @property | |
1242 | def all_ns_refs(self): |
|
1247 | def all_ns_refs(self): | |
1243 | """Get a list of references to all the namespace dictionaries in which |
|
1248 | """Get a list of references to all the namespace dictionaries in which | |
1244 | IPython might store a user-created object. |
|
1249 | IPython might store a user-created object. | |
1245 |
|
1250 | |||
1246 | Note that this does not include the displayhook, which also caches |
|
1251 | Note that this does not include the displayhook, which also caches | |
1247 | objects from the output.""" |
|
1252 | objects from the output.""" | |
1248 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ |
|
1253 | return [self.user_ns, self.user_global_ns, self.user_ns_hidden] + \ | |
1249 | [m.__dict__ for m in self._main_mod_cache.values()] |
|
1254 | [m.__dict__ for m in self._main_mod_cache.values()] | |
1250 |
|
1255 | |||
1251 | def reset(self, new_session=True): |
|
1256 | def reset(self, new_session=True): | |
1252 | """Clear all internal namespaces, and attempt to release references to |
|
1257 | """Clear all internal namespaces, and attempt to release references to | |
1253 | user objects. |
|
1258 | user objects. | |
1254 |
|
1259 | |||
1255 | If new_session is True, a new history session will be opened. |
|
1260 | If new_session is True, a new history session will be opened. | |
1256 | """ |
|
1261 | """ | |
1257 | # Clear histories |
|
1262 | # Clear histories | |
1258 | self.history_manager.reset(new_session) |
|
1263 | self.history_manager.reset(new_session) | |
1259 | # Reset counter used to index all histories |
|
1264 | # Reset counter used to index all histories | |
1260 | if new_session: |
|
1265 | if new_session: | |
1261 | self.execution_count = 1 |
|
1266 | self.execution_count = 1 | |
1262 |
|
1267 | |||
1263 | # Reset last execution result |
|
1268 | # Reset last execution result | |
1264 | self.last_execution_succeeded = True |
|
1269 | self.last_execution_succeeded = True | |
1265 | self.last_execution_result = None |
|
1270 | self.last_execution_result = None | |
1266 |
|
1271 | |||
1267 | # Flush cached output items |
|
1272 | # Flush cached output items | |
1268 | if self.displayhook.do_full_cache: |
|
1273 | if self.displayhook.do_full_cache: | |
1269 | self.displayhook.flush() |
|
1274 | self.displayhook.flush() | |
1270 |
|
1275 | |||
1271 | # The main execution namespaces must be cleared very carefully, |
|
1276 | # The main execution namespaces must be cleared very carefully, | |
1272 | # skipping the deletion of the builtin-related keys, because doing so |
|
1277 | # skipping the deletion of the builtin-related keys, because doing so | |
1273 | # would cause errors in many object's __del__ methods. |
|
1278 | # would cause errors in many object's __del__ methods. | |
1274 | if self.user_ns is not self.user_global_ns: |
|
1279 | if self.user_ns is not self.user_global_ns: | |
1275 | self.user_ns.clear() |
|
1280 | self.user_ns.clear() | |
1276 | ns = self.user_global_ns |
|
1281 | ns = self.user_global_ns | |
1277 | drop_keys = set(ns.keys()) |
|
1282 | drop_keys = set(ns.keys()) | |
1278 | drop_keys.discard('__builtin__') |
|
1283 | drop_keys.discard('__builtin__') | |
1279 | drop_keys.discard('__builtins__') |
|
1284 | drop_keys.discard('__builtins__') | |
1280 | drop_keys.discard('__name__') |
|
1285 | drop_keys.discard('__name__') | |
1281 | for k in drop_keys: |
|
1286 | for k in drop_keys: | |
1282 | del ns[k] |
|
1287 | del ns[k] | |
1283 |
|
1288 | |||
1284 | self.user_ns_hidden.clear() |
|
1289 | self.user_ns_hidden.clear() | |
1285 |
|
1290 | |||
1286 | # Restore the user namespaces to minimal usability |
|
1291 | # Restore the user namespaces to minimal usability | |
1287 | self.init_user_ns() |
|
1292 | self.init_user_ns() | |
1288 |
|
1293 | |||
1289 | # Restore the default and user aliases |
|
1294 | # Restore the default and user aliases | |
1290 | self.alias_manager.clear_aliases() |
|
1295 | self.alias_manager.clear_aliases() | |
1291 | self.alias_manager.init_aliases() |
|
1296 | self.alias_manager.init_aliases() | |
1292 |
|
1297 | |||
1293 | # Flush the private list of module references kept for script |
|
1298 | # Flush the private list of module references kept for script | |
1294 | # execution protection |
|
1299 | # execution protection | |
1295 | self.clear_main_mod_cache() |
|
1300 | self.clear_main_mod_cache() | |
1296 |
|
1301 | |||
1297 | def del_var(self, varname, by_name=False): |
|
1302 | def del_var(self, varname, by_name=False): | |
1298 | """Delete a variable from the various namespaces, so that, as |
|
1303 | """Delete a variable from the various namespaces, so that, as | |
1299 | far as possible, we're not keeping any hidden references to it. |
|
1304 | far as possible, we're not keeping any hidden references to it. | |
1300 |
|
1305 | |||
1301 | Parameters |
|
1306 | Parameters | |
1302 | ---------- |
|
1307 | ---------- | |
1303 | varname : str |
|
1308 | varname : str | |
1304 | The name of the variable to delete. |
|
1309 | The name of the variable to delete. | |
1305 | by_name : bool |
|
1310 | by_name : bool | |
1306 | If True, delete variables with the given name in each |
|
1311 | If True, delete variables with the given name in each | |
1307 | namespace. If False (default), find the variable in the user |
|
1312 | namespace. If False (default), find the variable in the user | |
1308 | namespace, and delete references to it. |
|
1313 | namespace, and delete references to it. | |
1309 | """ |
|
1314 | """ | |
1310 | if varname in ('__builtin__', '__builtins__'): |
|
1315 | if varname in ('__builtin__', '__builtins__'): | |
1311 | raise ValueError("Refusing to delete %s" % varname) |
|
1316 | raise ValueError("Refusing to delete %s" % varname) | |
1312 |
|
1317 | |||
1313 | ns_refs = self.all_ns_refs |
|
1318 | ns_refs = self.all_ns_refs | |
1314 |
|
1319 | |||
1315 | if by_name: # Delete by name |
|
1320 | if by_name: # Delete by name | |
1316 | for ns in ns_refs: |
|
1321 | for ns in ns_refs: | |
1317 | try: |
|
1322 | try: | |
1318 | del ns[varname] |
|
1323 | del ns[varname] | |
1319 | except KeyError: |
|
1324 | except KeyError: | |
1320 | pass |
|
1325 | pass | |
1321 | else: # Delete by object |
|
1326 | else: # Delete by object | |
1322 | try: |
|
1327 | try: | |
1323 | obj = self.user_ns[varname] |
|
1328 | obj = self.user_ns[varname] | |
1324 | except KeyError: |
|
1329 | except KeyError: | |
1325 | raise NameError("name '%s' is not defined" % varname) |
|
1330 | raise NameError("name '%s' is not defined" % varname) | |
1326 | # Also check in output history |
|
1331 | # Also check in output history | |
1327 | ns_refs.append(self.history_manager.output_hist) |
|
1332 | ns_refs.append(self.history_manager.output_hist) | |
1328 | for ns in ns_refs: |
|
1333 | for ns in ns_refs: | |
1329 | to_delete = [n for n, o in ns.items() if o is obj] |
|
1334 | to_delete = [n for n, o in ns.items() if o is obj] | |
1330 | for name in to_delete: |
|
1335 | for name in to_delete: | |
1331 | del ns[name] |
|
1336 | del ns[name] | |
1332 |
|
1337 | |||
1333 | # Ensure it is removed from the last execution result |
|
1338 | # Ensure it is removed from the last execution result | |
1334 | if self.last_execution_result.result is obj: |
|
1339 | if self.last_execution_result.result is obj: | |
1335 | self.last_execution_result = None |
|
1340 | self.last_execution_result = None | |
1336 |
|
1341 | |||
1337 | # displayhook keeps extra references, but not in a dictionary |
|
1342 | # displayhook keeps extra references, but not in a dictionary | |
1338 | for name in ('_', '__', '___'): |
|
1343 | for name in ('_', '__', '___'): | |
1339 | if getattr(self.displayhook, name) is obj: |
|
1344 | if getattr(self.displayhook, name) is obj: | |
1340 | setattr(self.displayhook, name, None) |
|
1345 | setattr(self.displayhook, name, None) | |
1341 |
|
1346 | |||
1342 | def reset_selective(self, regex=None): |
|
1347 | def reset_selective(self, regex=None): | |
1343 | """Clear selective variables from internal namespaces based on a |
|
1348 | """Clear selective variables from internal namespaces based on a | |
1344 | specified regular expression. |
|
1349 | specified regular expression. | |
1345 |
|
1350 | |||
1346 | Parameters |
|
1351 | Parameters | |
1347 | ---------- |
|
1352 | ---------- | |
1348 | regex : string or compiled pattern, optional |
|
1353 | regex : string or compiled pattern, optional | |
1349 | A regular expression pattern that will be used in searching |
|
1354 | A regular expression pattern that will be used in searching | |
1350 | variable names in the users namespaces. |
|
1355 | variable names in the users namespaces. | |
1351 | """ |
|
1356 | """ | |
1352 | if regex is not None: |
|
1357 | if regex is not None: | |
1353 | try: |
|
1358 | try: | |
1354 | m = re.compile(regex) |
|
1359 | m = re.compile(regex) | |
1355 | except TypeError: |
|
1360 | except TypeError: | |
1356 | raise TypeError('regex must be a string or compiled pattern') |
|
1361 | raise TypeError('regex must be a string or compiled pattern') | |
1357 | # Search for keys in each namespace that match the given regex |
|
1362 | # Search for keys in each namespace that match the given regex | |
1358 | # If a match is found, delete the key/value pair. |
|
1363 | # If a match is found, delete the key/value pair. | |
1359 | for ns in self.all_ns_refs: |
|
1364 | for ns in self.all_ns_refs: | |
1360 | for var in ns: |
|
1365 | for var in ns: | |
1361 | if m.search(var): |
|
1366 | if m.search(var): | |
1362 | del ns[var] |
|
1367 | del ns[var] | |
1363 |
|
1368 | |||
1364 | def push(self, variables, interactive=True): |
|
1369 | def push(self, variables, interactive=True): | |
1365 | """Inject a group of variables into the IPython user namespace. |
|
1370 | """Inject a group of variables into the IPython user namespace. | |
1366 |
|
1371 | |||
1367 | Parameters |
|
1372 | Parameters | |
1368 | ---------- |
|
1373 | ---------- | |
1369 | variables : dict, str or list/tuple of str |
|
1374 | variables : dict, str or list/tuple of str | |
1370 | The variables to inject into the user's namespace. If a dict, a |
|
1375 | The variables to inject into the user's namespace. If a dict, a | |
1371 | simple update is done. If a str, the string is assumed to have |
|
1376 | simple update is done. If a str, the string is assumed to have | |
1372 | variable names separated by spaces. A list/tuple of str can also |
|
1377 | variable names separated by spaces. A list/tuple of str can also | |
1373 | be used to give the variable names. If just the variable names are |
|
1378 | be used to give the variable names. If just the variable names are | |
1374 | give (list/tuple/str) then the variable values looked up in the |
|
1379 | give (list/tuple/str) then the variable values looked up in the | |
1375 | callers frame. |
|
1380 | callers frame. | |
1376 | interactive : bool |
|
1381 | interactive : bool | |
1377 | If True (default), the variables will be listed with the ``who`` |
|
1382 | If True (default), the variables will be listed with the ``who`` | |
1378 | magic. |
|
1383 | magic. | |
1379 | """ |
|
1384 | """ | |
1380 | vdict = None |
|
1385 | vdict = None | |
1381 |
|
1386 | |||
1382 | # We need a dict of name/value pairs to do namespace updates. |
|
1387 | # We need a dict of name/value pairs to do namespace updates. | |
1383 | if isinstance(variables, dict): |
|
1388 | if isinstance(variables, dict): | |
1384 | vdict = variables |
|
1389 | vdict = variables | |
1385 | elif isinstance(variables, (str, list, tuple)): |
|
1390 | elif isinstance(variables, (str, list, tuple)): | |
1386 | if isinstance(variables, str): |
|
1391 | if isinstance(variables, str): | |
1387 | vlist = variables.split() |
|
1392 | vlist = variables.split() | |
1388 | else: |
|
1393 | else: | |
1389 | vlist = variables |
|
1394 | vlist = variables | |
1390 | vdict = {} |
|
1395 | vdict = {} | |
1391 | cf = sys._getframe(1) |
|
1396 | cf = sys._getframe(1) | |
1392 | for name in vlist: |
|
1397 | for name in vlist: | |
1393 | try: |
|
1398 | try: | |
1394 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) |
|
1399 | vdict[name] = eval(name, cf.f_globals, cf.f_locals) | |
1395 | except: |
|
1400 | except: | |
1396 | print('Could not get variable %s from %s' % |
|
1401 | print('Could not get variable %s from %s' % | |
1397 | (name,cf.f_code.co_name)) |
|
1402 | (name,cf.f_code.co_name)) | |
1398 | else: |
|
1403 | else: | |
1399 | raise ValueError('variables must be a dict/str/list/tuple') |
|
1404 | raise ValueError('variables must be a dict/str/list/tuple') | |
1400 |
|
1405 | |||
1401 | # Propagate variables to user namespace |
|
1406 | # Propagate variables to user namespace | |
1402 | self.user_ns.update(vdict) |
|
1407 | self.user_ns.update(vdict) | |
1403 |
|
1408 | |||
1404 | # And configure interactive visibility |
|
1409 | # And configure interactive visibility | |
1405 | user_ns_hidden = self.user_ns_hidden |
|
1410 | user_ns_hidden = self.user_ns_hidden | |
1406 | if interactive: |
|
1411 | if interactive: | |
1407 | for name in vdict: |
|
1412 | for name in vdict: | |
1408 | user_ns_hidden.pop(name, None) |
|
1413 | user_ns_hidden.pop(name, None) | |
1409 | else: |
|
1414 | else: | |
1410 | user_ns_hidden.update(vdict) |
|
1415 | user_ns_hidden.update(vdict) | |
1411 |
|
1416 | |||
1412 | def drop_by_id(self, variables): |
|
1417 | def drop_by_id(self, variables): | |
1413 | """Remove a dict of variables from the user namespace, if they are the |
|
1418 | """Remove a dict of variables from the user namespace, if they are the | |
1414 | same as the values in the dictionary. |
|
1419 | same as the values in the dictionary. | |
1415 |
|
1420 | |||
1416 | This is intended for use by extensions: variables that they've added can |
|
1421 | This is intended for use by extensions: variables that they've added can | |
1417 | be taken back out if they are unloaded, without removing any that the |
|
1422 | be taken back out if they are unloaded, without removing any that the | |
1418 | user has overwritten. |
|
1423 | user has overwritten. | |
1419 |
|
1424 | |||
1420 | Parameters |
|
1425 | Parameters | |
1421 | ---------- |
|
1426 | ---------- | |
1422 | variables : dict |
|
1427 | variables : dict | |
1423 | A dictionary mapping object names (as strings) to the objects. |
|
1428 | A dictionary mapping object names (as strings) to the objects. | |
1424 | """ |
|
1429 | """ | |
1425 | for name, obj in variables.items(): |
|
1430 | for name, obj in variables.items(): | |
1426 | if name in self.user_ns and self.user_ns[name] is obj: |
|
1431 | if name in self.user_ns and self.user_ns[name] is obj: | |
1427 | del self.user_ns[name] |
|
1432 | del self.user_ns[name] | |
1428 | self.user_ns_hidden.pop(name, None) |
|
1433 | self.user_ns_hidden.pop(name, None) | |
1429 |
|
1434 | |||
1430 | #------------------------------------------------------------------------- |
|
1435 | #------------------------------------------------------------------------- | |
1431 | # Things related to object introspection |
|
1436 | # Things related to object introspection | |
1432 | #------------------------------------------------------------------------- |
|
1437 | #------------------------------------------------------------------------- | |
1433 |
|
1438 | |||
1434 | def _ofind(self, oname, namespaces=None): |
|
1439 | def _ofind(self, oname, namespaces=None): | |
1435 | """Find an object in the available namespaces. |
|
1440 | """Find an object in the available namespaces. | |
1436 |
|
1441 | |||
1437 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic |
|
1442 | self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic | |
1438 |
|
1443 | |||
1439 | Has special code to detect magic functions. |
|
1444 | Has special code to detect magic functions. | |
1440 | """ |
|
1445 | """ | |
1441 | oname = oname.strip() |
|
1446 | oname = oname.strip() | |
1442 | if not oname.startswith(ESC_MAGIC) and \ |
|
1447 | if not oname.startswith(ESC_MAGIC) and \ | |
1443 | not oname.startswith(ESC_MAGIC2) and \ |
|
1448 | not oname.startswith(ESC_MAGIC2) and \ | |
1444 | not all(a.isidentifier() for a in oname.split(".")): |
|
1449 | not all(a.isidentifier() for a in oname.split(".")): | |
1445 | return {'found': False} |
|
1450 | return {'found': False} | |
1446 |
|
1451 | |||
1447 | if namespaces is None: |
|
1452 | if namespaces is None: | |
1448 | # Namespaces to search in: |
|
1453 | # Namespaces to search in: | |
1449 | # Put them in a list. The order is important so that we |
|
1454 | # Put them in a list. The order is important so that we | |
1450 | # find things in the same order that Python finds them. |
|
1455 | # find things in the same order that Python finds them. | |
1451 | namespaces = [ ('Interactive', self.user_ns), |
|
1456 | namespaces = [ ('Interactive', self.user_ns), | |
1452 | ('Interactive (global)', self.user_global_ns), |
|
1457 | ('Interactive (global)', self.user_global_ns), | |
1453 | ('Python builtin', builtin_mod.__dict__), |
|
1458 | ('Python builtin', builtin_mod.__dict__), | |
1454 | ] |
|
1459 | ] | |
1455 |
|
1460 | |||
1456 | ismagic = False |
|
1461 | ismagic = False | |
1457 | isalias = False |
|
1462 | isalias = False | |
1458 | found = False |
|
1463 | found = False | |
1459 | ospace = None |
|
1464 | ospace = None | |
1460 | parent = None |
|
1465 | parent = None | |
1461 | obj = None |
|
1466 | obj = None | |
1462 |
|
1467 | |||
1463 | # Look for the given name by splitting it in parts. If the head is |
|
1468 | # Look for the given name by splitting it in parts. If the head is | |
1464 | # found, then we look for all the remaining parts as members, and only |
|
1469 | # found, then we look for all the remaining parts as members, and only | |
1465 | # declare success if we can find them all. |
|
1470 | # declare success if we can find them all. | |
1466 | oname_parts = oname.split('.') |
|
1471 | oname_parts = oname.split('.') | |
1467 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] |
|
1472 | oname_head, oname_rest = oname_parts[0],oname_parts[1:] | |
1468 | for nsname,ns in namespaces: |
|
1473 | for nsname,ns in namespaces: | |
1469 | try: |
|
1474 | try: | |
1470 | obj = ns[oname_head] |
|
1475 | obj = ns[oname_head] | |
1471 | except KeyError: |
|
1476 | except KeyError: | |
1472 | continue |
|
1477 | continue | |
1473 | else: |
|
1478 | else: | |
1474 | for idx, part in enumerate(oname_rest): |
|
1479 | for idx, part in enumerate(oname_rest): | |
1475 | try: |
|
1480 | try: | |
1476 | parent = obj |
|
1481 | parent = obj | |
1477 | # The last part is looked up in a special way to avoid |
|
1482 | # The last part is looked up in a special way to avoid | |
1478 | # descriptor invocation as it may raise or have side |
|
1483 | # descriptor invocation as it may raise or have side | |
1479 | # effects. |
|
1484 | # effects. | |
1480 | if idx == len(oname_rest) - 1: |
|
1485 | if idx == len(oname_rest) - 1: | |
1481 | obj = self._getattr_property(obj, part) |
|
1486 | obj = self._getattr_property(obj, part) | |
1482 | else: |
|
1487 | else: | |
1483 | obj = getattr(obj, part) |
|
1488 | obj = getattr(obj, part) | |
1484 | except: |
|
1489 | except: | |
1485 | # Blanket except b/c some badly implemented objects |
|
1490 | # Blanket except b/c some badly implemented objects | |
1486 | # allow __getattr__ to raise exceptions other than |
|
1491 | # allow __getattr__ to raise exceptions other than | |
1487 | # AttributeError, which then crashes IPython. |
|
1492 | # AttributeError, which then crashes IPython. | |
1488 | break |
|
1493 | break | |
1489 | else: |
|
1494 | else: | |
1490 | # If we finish the for loop (no break), we got all members |
|
1495 | # If we finish the for loop (no break), we got all members | |
1491 | found = True |
|
1496 | found = True | |
1492 | ospace = nsname |
|
1497 | ospace = nsname | |
1493 | break # namespace loop |
|
1498 | break # namespace loop | |
1494 |
|
1499 | |||
1495 | # Try to see if it's magic |
|
1500 | # Try to see if it's magic | |
1496 | if not found: |
|
1501 | if not found: | |
1497 | obj = None |
|
1502 | obj = None | |
1498 | if oname.startswith(ESC_MAGIC2): |
|
1503 | if oname.startswith(ESC_MAGIC2): | |
1499 | oname = oname.lstrip(ESC_MAGIC2) |
|
1504 | oname = oname.lstrip(ESC_MAGIC2) | |
1500 | obj = self.find_cell_magic(oname) |
|
1505 | obj = self.find_cell_magic(oname) | |
1501 | elif oname.startswith(ESC_MAGIC): |
|
1506 | elif oname.startswith(ESC_MAGIC): | |
1502 | oname = oname.lstrip(ESC_MAGIC) |
|
1507 | oname = oname.lstrip(ESC_MAGIC) | |
1503 | obj = self.find_line_magic(oname) |
|
1508 | obj = self.find_line_magic(oname) | |
1504 | else: |
|
1509 | else: | |
1505 | # search without prefix, so run? will find %run? |
|
1510 | # search without prefix, so run? will find %run? | |
1506 | obj = self.find_line_magic(oname) |
|
1511 | obj = self.find_line_magic(oname) | |
1507 | if obj is None: |
|
1512 | if obj is None: | |
1508 | obj = self.find_cell_magic(oname) |
|
1513 | obj = self.find_cell_magic(oname) | |
1509 | if obj is not None: |
|
1514 | if obj is not None: | |
1510 | found = True |
|
1515 | found = True | |
1511 | ospace = 'IPython internal' |
|
1516 | ospace = 'IPython internal' | |
1512 | ismagic = True |
|
1517 | ismagic = True | |
1513 | isalias = isinstance(obj, Alias) |
|
1518 | isalias = isinstance(obj, Alias) | |
1514 |
|
1519 | |||
1515 | # Last try: special-case some literals like '', [], {}, etc: |
|
1520 | # Last try: special-case some literals like '', [], {}, etc: | |
1516 | if not found and oname_head in ["''",'""','[]','{}','()']: |
|
1521 | if not found and oname_head in ["''",'""','[]','{}','()']: | |
1517 | obj = eval(oname_head) |
|
1522 | obj = eval(oname_head) | |
1518 | found = True |
|
1523 | found = True | |
1519 | ospace = 'Interactive' |
|
1524 | ospace = 'Interactive' | |
1520 |
|
1525 | |||
1521 | return { |
|
1526 | return { | |
1522 | 'obj':obj, |
|
1527 | 'obj':obj, | |
1523 | 'found':found, |
|
1528 | 'found':found, | |
1524 | 'parent':parent, |
|
1529 | 'parent':parent, | |
1525 | 'ismagic':ismagic, |
|
1530 | 'ismagic':ismagic, | |
1526 | 'isalias':isalias, |
|
1531 | 'isalias':isalias, | |
1527 | 'namespace':ospace |
|
1532 | 'namespace':ospace | |
1528 | } |
|
1533 | } | |
1529 |
|
1534 | |||
1530 | @staticmethod |
|
1535 | @staticmethod | |
1531 | def _getattr_property(obj, attrname): |
|
1536 | def _getattr_property(obj, attrname): | |
1532 | """Property-aware getattr to use in object finding. |
|
1537 | """Property-aware getattr to use in object finding. | |
1533 |
|
1538 | |||
1534 | If attrname represents a property, return it unevaluated (in case it has |
|
1539 | If attrname represents a property, return it unevaluated (in case it has | |
1535 | side effects or raises an error. |
|
1540 | side effects or raises an error. | |
1536 |
|
1541 | |||
1537 | """ |
|
1542 | """ | |
1538 | if not isinstance(obj, type): |
|
1543 | if not isinstance(obj, type): | |
1539 | try: |
|
1544 | try: | |
1540 | # `getattr(type(obj), attrname)` is not guaranteed to return |
|
1545 | # `getattr(type(obj), attrname)` is not guaranteed to return | |
1541 | # `obj`, but does so for property: |
|
1546 | # `obj`, but does so for property: | |
1542 | # |
|
1547 | # | |
1543 | # property.__get__(self, None, cls) -> self |
|
1548 | # property.__get__(self, None, cls) -> self | |
1544 | # |
|
1549 | # | |
1545 | # The universal alternative is to traverse the mro manually |
|
1550 | # The universal alternative is to traverse the mro manually | |
1546 | # searching for attrname in class dicts. |
|
1551 | # searching for attrname in class dicts. | |
1547 | attr = getattr(type(obj), attrname) |
|
1552 | attr = getattr(type(obj), attrname) | |
1548 | except AttributeError: |
|
1553 | except AttributeError: | |
1549 | pass |
|
1554 | pass | |
1550 | else: |
|
1555 | else: | |
1551 | # This relies on the fact that data descriptors (with both |
|
1556 | # This relies on the fact that data descriptors (with both | |
1552 | # __get__ & __set__ magic methods) take precedence over |
|
1557 | # __get__ & __set__ magic methods) take precedence over | |
1553 | # instance-level attributes: |
|
1558 | # instance-level attributes: | |
1554 | # |
|
1559 | # | |
1555 | # class A(object): |
|
1560 | # class A(object): | |
1556 | # @property |
|
1561 | # @property | |
1557 | # def foobar(self): return 123 |
|
1562 | # def foobar(self): return 123 | |
1558 | # a = A() |
|
1563 | # a = A() | |
1559 | # a.__dict__['foobar'] = 345 |
|
1564 | # a.__dict__['foobar'] = 345 | |
1560 | # a.foobar # == 123 |
|
1565 | # a.foobar # == 123 | |
1561 | # |
|
1566 | # | |
1562 | # So, a property may be returned right away. |
|
1567 | # So, a property may be returned right away. | |
1563 | if isinstance(attr, property): |
|
1568 | if isinstance(attr, property): | |
1564 | return attr |
|
1569 | return attr | |
1565 |
|
1570 | |||
1566 | # Nothing helped, fall back. |
|
1571 | # Nothing helped, fall back. | |
1567 | return getattr(obj, attrname) |
|
1572 | return getattr(obj, attrname) | |
1568 |
|
1573 | |||
1569 | def _object_find(self, oname, namespaces=None): |
|
1574 | def _object_find(self, oname, namespaces=None): | |
1570 | """Find an object and return a struct with info about it.""" |
|
1575 | """Find an object and return a struct with info about it.""" | |
1571 | return Struct(self._ofind(oname, namespaces)) |
|
1576 | return Struct(self._ofind(oname, namespaces)) | |
1572 |
|
1577 | |||
1573 | def _inspect(self, meth, oname, namespaces=None, **kw): |
|
1578 | def _inspect(self, meth, oname, namespaces=None, **kw): | |
1574 | """Generic interface to the inspector system. |
|
1579 | """Generic interface to the inspector system. | |
1575 |
|
1580 | |||
1576 | This function is meant to be called by pdef, pdoc & friends. |
|
1581 | This function is meant to be called by pdef, pdoc & friends. | |
1577 | """ |
|
1582 | """ | |
1578 | info = self._object_find(oname, namespaces) |
|
1583 | info = self._object_find(oname, namespaces) | |
1579 | docformat = sphinxify if self.sphinxify_docstring else None |
|
1584 | docformat = sphinxify if self.sphinxify_docstring else None | |
1580 | if info.found: |
|
1585 | if info.found: | |
1581 | pmethod = getattr(self.inspector, meth) |
|
1586 | pmethod = getattr(self.inspector, meth) | |
1582 | # TODO: only apply format_screen to the plain/text repr of the mime |
|
1587 | # TODO: only apply format_screen to the plain/text repr of the mime | |
1583 | # bundle. |
|
1588 | # bundle. | |
1584 | formatter = format_screen if info.ismagic else docformat |
|
1589 | formatter = format_screen if info.ismagic else docformat | |
1585 | if meth == 'pdoc': |
|
1590 | if meth == 'pdoc': | |
1586 | pmethod(info.obj, oname, formatter) |
|
1591 | pmethod(info.obj, oname, formatter) | |
1587 | elif meth == 'pinfo': |
|
1592 | elif meth == 'pinfo': | |
1588 | pmethod(info.obj, oname, formatter, info, |
|
1593 | pmethod(info.obj, oname, formatter, info, | |
1589 | enable_html_pager=self.enable_html_pager, **kw) |
|
1594 | enable_html_pager=self.enable_html_pager, **kw) | |
1590 | else: |
|
1595 | else: | |
1591 | pmethod(info.obj, oname) |
|
1596 | pmethod(info.obj, oname) | |
1592 | else: |
|
1597 | else: | |
1593 | print('Object `%s` not found.' % oname) |
|
1598 | print('Object `%s` not found.' % oname) | |
1594 | return 'not found' # so callers can take other action |
|
1599 | return 'not found' # so callers can take other action | |
1595 |
|
1600 | |||
1596 | def object_inspect(self, oname, detail_level=0): |
|
1601 | def object_inspect(self, oname, detail_level=0): | |
1597 | """Get object info about oname""" |
|
1602 | """Get object info about oname""" | |
1598 | with self.builtin_trap: |
|
1603 | with self.builtin_trap: | |
1599 | info = self._object_find(oname) |
|
1604 | info = self._object_find(oname) | |
1600 | if info.found: |
|
1605 | if info.found: | |
1601 | return self.inspector.info(info.obj, oname, info=info, |
|
1606 | return self.inspector.info(info.obj, oname, info=info, | |
1602 | detail_level=detail_level |
|
1607 | detail_level=detail_level | |
1603 | ) |
|
1608 | ) | |
1604 | else: |
|
1609 | else: | |
1605 | return oinspect.object_info(name=oname, found=False) |
|
1610 | return oinspect.object_info(name=oname, found=False) | |
1606 |
|
1611 | |||
1607 | def object_inspect_text(self, oname, detail_level=0): |
|
1612 | def object_inspect_text(self, oname, detail_level=0): | |
1608 | """Get object info as formatted text""" |
|
1613 | """Get object info as formatted text""" | |
1609 | return self.object_inspect_mime(oname, detail_level)['text/plain'] |
|
1614 | return self.object_inspect_mime(oname, detail_level)['text/plain'] | |
1610 |
|
1615 | |||
1611 | def object_inspect_mime(self, oname, detail_level=0): |
|
1616 | def object_inspect_mime(self, oname, detail_level=0): | |
1612 | """Get object info as a mimebundle of formatted representations. |
|
1617 | """Get object info as a mimebundle of formatted representations. | |
1613 |
|
1618 | |||
1614 | A mimebundle is a dictionary, keyed by mime-type. |
|
1619 | A mimebundle is a dictionary, keyed by mime-type. | |
1615 | It must always have the key `'text/plain'`. |
|
1620 | It must always have the key `'text/plain'`. | |
1616 | """ |
|
1621 | """ | |
1617 | with self.builtin_trap: |
|
1622 | with self.builtin_trap: | |
1618 | info = self._object_find(oname) |
|
1623 | info = self._object_find(oname) | |
1619 | if info.found: |
|
1624 | if info.found: | |
1620 | return self.inspector._get_info(info.obj, oname, info=info, |
|
1625 | return self.inspector._get_info(info.obj, oname, info=info, | |
1621 | detail_level=detail_level |
|
1626 | detail_level=detail_level | |
1622 | ) |
|
1627 | ) | |
1623 | else: |
|
1628 | else: | |
1624 | raise KeyError(oname) |
|
1629 | raise KeyError(oname) | |
1625 |
|
1630 | |||
1626 | #------------------------------------------------------------------------- |
|
1631 | #------------------------------------------------------------------------- | |
1627 | # Things related to history management |
|
1632 | # Things related to history management | |
1628 | #------------------------------------------------------------------------- |
|
1633 | #------------------------------------------------------------------------- | |
1629 |
|
1634 | |||
1630 | def init_history(self): |
|
1635 | def init_history(self): | |
1631 | """Sets up the command history, and starts regular autosaves.""" |
|
1636 | """Sets up the command history, and starts regular autosaves.""" | |
1632 | self.history_manager = HistoryManager(shell=self, parent=self) |
|
1637 | self.history_manager = HistoryManager(shell=self, parent=self) | |
1633 | self.configurables.append(self.history_manager) |
|
1638 | self.configurables.append(self.history_manager) | |
1634 |
|
1639 | |||
1635 | #------------------------------------------------------------------------- |
|
1640 | #------------------------------------------------------------------------- | |
1636 | # Things related to exception handling and tracebacks (not debugging) |
|
1641 | # Things related to exception handling and tracebacks (not debugging) | |
1637 | #------------------------------------------------------------------------- |
|
1642 | #------------------------------------------------------------------------- | |
1638 |
|
1643 | |||
1639 | debugger_cls = Pdb |
|
1644 | debugger_cls = Pdb | |
1640 |
|
1645 | |||
1641 | def init_traceback_handlers(self, custom_exceptions): |
|
1646 | def init_traceback_handlers(self, custom_exceptions): | |
1642 | # Syntax error handler. |
|
1647 | # Syntax error handler. | |
1643 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) |
|
1648 | self.SyntaxTB = ultratb.SyntaxTB(color_scheme='NoColor', parent=self) | |
1644 |
|
1649 | |||
1645 | # The interactive one is initialized with an offset, meaning we always |
|
1650 | # The interactive one is initialized with an offset, meaning we always | |
1646 | # want to remove the topmost item in the traceback, which is our own |
|
1651 | # want to remove the topmost item in the traceback, which is our own | |
1647 | # internal code. Valid modes: ['Plain','Context','Verbose'] |
|
1652 | # internal code. Valid modes: ['Plain','Context','Verbose'] | |
1648 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', |
|
1653 | self.InteractiveTB = ultratb.AutoFormattedTB(mode = 'Plain', | |
1649 | color_scheme='NoColor', |
|
1654 | color_scheme='NoColor', | |
1650 | tb_offset = 1, |
|
1655 | tb_offset = 1, | |
1651 | check_cache=check_linecache_ipython, |
|
1656 | check_cache=check_linecache_ipython, | |
1652 | debugger_cls=self.debugger_cls, parent=self) |
|
1657 | debugger_cls=self.debugger_cls, parent=self) | |
1653 |
|
1658 | |||
1654 | # The instance will store a pointer to the system-wide exception hook, |
|
1659 | # The instance will store a pointer to the system-wide exception hook, | |
1655 | # so that runtime code (such as magics) can access it. This is because |
|
1660 | # so that runtime code (such as magics) can access it. This is because | |
1656 | # during the read-eval loop, it may get temporarily overwritten. |
|
1661 | # during the read-eval loop, it may get temporarily overwritten. | |
1657 | self.sys_excepthook = sys.excepthook |
|
1662 | self.sys_excepthook = sys.excepthook | |
1658 |
|
1663 | |||
1659 | # and add any custom exception handlers the user may have specified |
|
1664 | # and add any custom exception handlers the user may have specified | |
1660 | self.set_custom_exc(*custom_exceptions) |
|
1665 | self.set_custom_exc(*custom_exceptions) | |
1661 |
|
1666 | |||
1662 | # Set the exception mode |
|
1667 | # Set the exception mode | |
1663 | self.InteractiveTB.set_mode(mode=self.xmode) |
|
1668 | self.InteractiveTB.set_mode(mode=self.xmode) | |
1664 |
|
1669 | |||
1665 | def set_custom_exc(self, exc_tuple, handler): |
|
1670 | def set_custom_exc(self, exc_tuple, handler): | |
1666 | """set_custom_exc(exc_tuple, handler) |
|
1671 | """set_custom_exc(exc_tuple, handler) | |
1667 |
|
1672 | |||
1668 | Set a custom exception handler, which will be called if any of the |
|
1673 | Set a custom exception handler, which will be called if any of the | |
1669 | exceptions in exc_tuple occur in the mainloop (specifically, in the |
|
1674 | exceptions in exc_tuple occur in the mainloop (specifically, in the | |
1670 | run_code() method). |
|
1675 | run_code() method). | |
1671 |
|
1676 | |||
1672 | Parameters |
|
1677 | Parameters | |
1673 | ---------- |
|
1678 | ---------- | |
1674 |
|
1679 | |||
1675 | exc_tuple : tuple of exception classes |
|
1680 | exc_tuple : tuple of exception classes | |
1676 | A *tuple* of exception classes, for which to call the defined |
|
1681 | A *tuple* of exception classes, for which to call the defined | |
1677 | handler. It is very important that you use a tuple, and NOT A |
|
1682 | handler. It is very important that you use a tuple, and NOT A | |
1678 | LIST here, because of the way Python's except statement works. If |
|
1683 | LIST here, because of the way Python's except statement works. If | |
1679 | you only want to trap a single exception, use a singleton tuple:: |
|
1684 | you only want to trap a single exception, use a singleton tuple:: | |
1680 |
|
1685 | |||
1681 | exc_tuple == (MyCustomException,) |
|
1686 | exc_tuple == (MyCustomException,) | |
1682 |
|
1687 | |||
1683 | handler : callable |
|
1688 | handler : callable | |
1684 | handler must have the following signature:: |
|
1689 | handler must have the following signature:: | |
1685 |
|
1690 | |||
1686 | def my_handler(self, etype, value, tb, tb_offset=None): |
|
1691 | def my_handler(self, etype, value, tb, tb_offset=None): | |
1687 | ... |
|
1692 | ... | |
1688 | return structured_traceback |
|
1693 | return structured_traceback | |
1689 |
|
1694 | |||
1690 | Your handler must return a structured traceback (a list of strings), |
|
1695 | Your handler must return a structured traceback (a list of strings), | |
1691 | or None. |
|
1696 | or None. | |
1692 |
|
1697 | |||
1693 | This will be made into an instance method (via types.MethodType) |
|
1698 | This will be made into an instance method (via types.MethodType) | |
1694 | of IPython itself, and it will be called if any of the exceptions |
|
1699 | of IPython itself, and it will be called if any of the exceptions | |
1695 | listed in the exc_tuple are caught. If the handler is None, an |
|
1700 | listed in the exc_tuple are caught. If the handler is None, an | |
1696 | internal basic one is used, which just prints basic info. |
|
1701 | internal basic one is used, which just prints basic info. | |
1697 |
|
1702 | |||
1698 | To protect IPython from crashes, if your handler ever raises an |
|
1703 | To protect IPython from crashes, if your handler ever raises an | |
1699 | exception or returns an invalid result, it will be immediately |
|
1704 | exception or returns an invalid result, it will be immediately | |
1700 | disabled. |
|
1705 | disabled. | |
1701 |
|
1706 | |||
1702 | WARNING: by putting in your own exception handler into IPython's main |
|
1707 | WARNING: by putting in your own exception handler into IPython's main | |
1703 | execution loop, you run a very good chance of nasty crashes. This |
|
1708 | execution loop, you run a very good chance of nasty crashes. This | |
1704 | facility should only be used if you really know what you are doing.""" |
|
1709 | facility should only be used if you really know what you are doing.""" | |
1705 | if not isinstance(exc_tuple, tuple): |
|
1710 | if not isinstance(exc_tuple, tuple): | |
1706 | raise TypeError("The custom exceptions must be given as a tuple.") |
|
1711 | raise TypeError("The custom exceptions must be given as a tuple.") | |
1707 |
|
1712 | |||
1708 | def dummy_handler(self, etype, value, tb, tb_offset=None): |
|
1713 | def dummy_handler(self, etype, value, tb, tb_offset=None): | |
1709 | print('*** Simple custom exception handler ***') |
|
1714 | print('*** Simple custom exception handler ***') | |
1710 | print('Exception type :', etype) |
|
1715 | print('Exception type :', etype) | |
1711 | print('Exception value:', value) |
|
1716 | print('Exception value:', value) | |
1712 | print('Traceback :', tb) |
|
1717 | print('Traceback :', tb) | |
1713 |
|
1718 | |||
1714 | def validate_stb(stb): |
|
1719 | def validate_stb(stb): | |
1715 | """validate structured traceback return type |
|
1720 | """validate structured traceback return type | |
1716 |
|
1721 | |||
1717 | return type of CustomTB *should* be a list of strings, but allow |
|
1722 | return type of CustomTB *should* be a list of strings, but allow | |
1718 | single strings or None, which are harmless. |
|
1723 | single strings or None, which are harmless. | |
1719 |
|
1724 | |||
1720 | This function will *always* return a list of strings, |
|
1725 | This function will *always* return a list of strings, | |
1721 | and will raise a TypeError if stb is inappropriate. |
|
1726 | and will raise a TypeError if stb is inappropriate. | |
1722 | """ |
|
1727 | """ | |
1723 | msg = "CustomTB must return list of strings, not %r" % stb |
|
1728 | msg = "CustomTB must return list of strings, not %r" % stb | |
1724 | if stb is None: |
|
1729 | if stb is None: | |
1725 | return [] |
|
1730 | return [] | |
1726 | elif isinstance(stb, str): |
|
1731 | elif isinstance(stb, str): | |
1727 | return [stb] |
|
1732 | return [stb] | |
1728 | elif not isinstance(stb, list): |
|
1733 | elif not isinstance(stb, list): | |
1729 | raise TypeError(msg) |
|
1734 | raise TypeError(msg) | |
1730 | # it's a list |
|
1735 | # it's a list | |
1731 | for line in stb: |
|
1736 | for line in stb: | |
1732 | # check every element |
|
1737 | # check every element | |
1733 | if not isinstance(line, str): |
|
1738 | if not isinstance(line, str): | |
1734 | raise TypeError(msg) |
|
1739 | raise TypeError(msg) | |
1735 | return stb |
|
1740 | return stb | |
1736 |
|
1741 | |||
1737 | if handler is None: |
|
1742 | if handler is None: | |
1738 | wrapped = dummy_handler |
|
1743 | wrapped = dummy_handler | |
1739 | else: |
|
1744 | else: | |
1740 | def wrapped(self,etype,value,tb,tb_offset=None): |
|
1745 | def wrapped(self,etype,value,tb,tb_offset=None): | |
1741 | """wrap CustomTB handler, to protect IPython from user code |
|
1746 | """wrap CustomTB handler, to protect IPython from user code | |
1742 |
|
1747 | |||
1743 | This makes it harder (but not impossible) for custom exception |
|
1748 | This makes it harder (but not impossible) for custom exception | |
1744 | handlers to crash IPython. |
|
1749 | handlers to crash IPython. | |
1745 | """ |
|
1750 | """ | |
1746 | try: |
|
1751 | try: | |
1747 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) |
|
1752 | stb = handler(self,etype,value,tb,tb_offset=tb_offset) | |
1748 | return validate_stb(stb) |
|
1753 | return validate_stb(stb) | |
1749 | except: |
|
1754 | except: | |
1750 | # clear custom handler immediately |
|
1755 | # clear custom handler immediately | |
1751 | self.set_custom_exc((), None) |
|
1756 | self.set_custom_exc((), None) | |
1752 | print("Custom TB Handler failed, unregistering", file=sys.stderr) |
|
1757 | print("Custom TB Handler failed, unregistering", file=sys.stderr) | |
1753 | # show the exception in handler first |
|
1758 | # show the exception in handler first | |
1754 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) |
|
1759 | stb = self.InteractiveTB.structured_traceback(*sys.exc_info()) | |
1755 | print(self.InteractiveTB.stb2text(stb)) |
|
1760 | print(self.InteractiveTB.stb2text(stb)) | |
1756 | print("The original exception:") |
|
1761 | print("The original exception:") | |
1757 | stb = self.InteractiveTB.structured_traceback( |
|
1762 | stb = self.InteractiveTB.structured_traceback( | |
1758 | (etype,value,tb), tb_offset=tb_offset |
|
1763 | (etype,value,tb), tb_offset=tb_offset | |
1759 | ) |
|
1764 | ) | |
1760 | return stb |
|
1765 | return stb | |
1761 |
|
1766 | |||
1762 | self.CustomTB = types.MethodType(wrapped,self) |
|
1767 | self.CustomTB = types.MethodType(wrapped,self) | |
1763 | self.custom_exceptions = exc_tuple |
|
1768 | self.custom_exceptions = exc_tuple | |
1764 |
|
1769 | |||
1765 | def excepthook(self, etype, value, tb): |
|
1770 | def excepthook(self, etype, value, tb): | |
1766 | """One more defense for GUI apps that call sys.excepthook. |
|
1771 | """One more defense for GUI apps that call sys.excepthook. | |
1767 |
|
1772 | |||
1768 | GUI frameworks like wxPython trap exceptions and call |
|
1773 | GUI frameworks like wxPython trap exceptions and call | |
1769 | sys.excepthook themselves. I guess this is a feature that |
|
1774 | sys.excepthook themselves. I guess this is a feature that | |
1770 | enables them to keep running after exceptions that would |
|
1775 | enables them to keep running after exceptions that would | |
1771 | otherwise kill their mainloop. This is a bother for IPython |
|
1776 | otherwise kill their mainloop. This is a bother for IPython | |
1772 | which excepts to catch all of the program exceptions with a try: |
|
1777 | which excepts to catch all of the program exceptions with a try: | |
1773 | except: statement. |
|
1778 | except: statement. | |
1774 |
|
1779 | |||
1775 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if |
|
1780 | Normally, IPython sets sys.excepthook to a CrashHandler instance, so if | |
1776 | any app directly invokes sys.excepthook, it will look to the user like |
|
1781 | any app directly invokes sys.excepthook, it will look to the user like | |
1777 | IPython crashed. In order to work around this, we can disable the |
|
1782 | IPython crashed. In order to work around this, we can disable the | |
1778 | CrashHandler and replace it with this excepthook instead, which prints a |
|
1783 | CrashHandler and replace it with this excepthook instead, which prints a | |
1779 | regular traceback using our InteractiveTB. In this fashion, apps which |
|
1784 | regular traceback using our InteractiveTB. In this fashion, apps which | |
1780 | call sys.excepthook will generate a regular-looking exception from |
|
1785 | call sys.excepthook will generate a regular-looking exception from | |
1781 | IPython, and the CrashHandler will only be triggered by real IPython |
|
1786 | IPython, and the CrashHandler will only be triggered by real IPython | |
1782 | crashes. |
|
1787 | crashes. | |
1783 |
|
1788 | |||
1784 | This hook should be used sparingly, only in places which are not likely |
|
1789 | This hook should be used sparingly, only in places which are not likely | |
1785 | to be true IPython errors. |
|
1790 | to be true IPython errors. | |
1786 | """ |
|
1791 | """ | |
1787 | self.showtraceback((etype, value, tb), tb_offset=0) |
|
1792 | self.showtraceback((etype, value, tb), tb_offset=0) | |
1788 |
|
1793 | |||
1789 | def _get_exc_info(self, exc_tuple=None): |
|
1794 | def _get_exc_info(self, exc_tuple=None): | |
1790 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. |
|
1795 | """get exc_info from a given tuple, sys.exc_info() or sys.last_type etc. | |
1791 |
|
1796 | |||
1792 | Ensures sys.last_type,value,traceback hold the exc_info we found, |
|
1797 | Ensures sys.last_type,value,traceback hold the exc_info we found, | |
1793 | from whichever source. |
|
1798 | from whichever source. | |
1794 |
|
1799 | |||
1795 | raises ValueError if none of these contain any information |
|
1800 | raises ValueError if none of these contain any information | |
1796 | """ |
|
1801 | """ | |
1797 | if exc_tuple is None: |
|
1802 | if exc_tuple is None: | |
1798 | etype, value, tb = sys.exc_info() |
|
1803 | etype, value, tb = sys.exc_info() | |
1799 | else: |
|
1804 | else: | |
1800 | etype, value, tb = exc_tuple |
|
1805 | etype, value, tb = exc_tuple | |
1801 |
|
1806 | |||
1802 | if etype is None: |
|
1807 | if etype is None: | |
1803 | if hasattr(sys, 'last_type'): |
|
1808 | if hasattr(sys, 'last_type'): | |
1804 | etype, value, tb = sys.last_type, sys.last_value, \ |
|
1809 | etype, value, tb = sys.last_type, sys.last_value, \ | |
1805 | sys.last_traceback |
|
1810 | sys.last_traceback | |
1806 |
|
1811 | |||
1807 | if etype is None: |
|
1812 | if etype is None: | |
1808 | raise ValueError("No exception to find") |
|
1813 | raise ValueError("No exception to find") | |
1809 |
|
1814 | |||
1810 | # Now store the exception info in sys.last_type etc. |
|
1815 | # Now store the exception info in sys.last_type etc. | |
1811 | # WARNING: these variables are somewhat deprecated and not |
|
1816 | # WARNING: these variables are somewhat deprecated and not | |
1812 | # necessarily safe to use in a threaded environment, but tools |
|
1817 | # necessarily safe to use in a threaded environment, but tools | |
1813 | # like pdb depend on their existence, so let's set them. If we |
|
1818 | # like pdb depend on their existence, so let's set them. If we | |
1814 | # find problems in the field, we'll need to revisit their use. |
|
1819 | # find problems in the field, we'll need to revisit their use. | |
1815 | sys.last_type = etype |
|
1820 | sys.last_type = etype | |
1816 | sys.last_value = value |
|
1821 | sys.last_value = value | |
1817 | sys.last_traceback = tb |
|
1822 | sys.last_traceback = tb | |
1818 |
|
1823 | |||
1819 | return etype, value, tb |
|
1824 | return etype, value, tb | |
1820 |
|
1825 | |||
1821 | def show_usage_error(self, exc): |
|
1826 | def show_usage_error(self, exc): | |
1822 | """Show a short message for UsageErrors |
|
1827 | """Show a short message for UsageErrors | |
1823 |
|
1828 | |||
1824 | These are special exceptions that shouldn't show a traceback. |
|
1829 | These are special exceptions that shouldn't show a traceback. | |
1825 | """ |
|
1830 | """ | |
1826 | print("UsageError: %s" % exc, file=sys.stderr) |
|
1831 | print("UsageError: %s" % exc, file=sys.stderr) | |
1827 |
|
1832 | |||
1828 | def get_exception_only(self, exc_tuple=None): |
|
1833 | def get_exception_only(self, exc_tuple=None): | |
1829 | """ |
|
1834 | """ | |
1830 | Return as a string (ending with a newline) the exception that |
|
1835 | Return as a string (ending with a newline) the exception that | |
1831 | just occurred, without any traceback. |
|
1836 | just occurred, without any traceback. | |
1832 | """ |
|
1837 | """ | |
1833 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1838 | etype, value, tb = self._get_exc_info(exc_tuple) | |
1834 | msg = traceback.format_exception_only(etype, value) |
|
1839 | msg = traceback.format_exception_only(etype, value) | |
1835 | return ''.join(msg) |
|
1840 | return ''.join(msg) | |
1836 |
|
1841 | |||
1837 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, |
|
1842 | def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, | |
1838 | exception_only=False, running_compiled_code=False): |
|
1843 | exception_only=False, running_compiled_code=False): | |
1839 | """Display the exception that just occurred. |
|
1844 | """Display the exception that just occurred. | |
1840 |
|
1845 | |||
1841 | If nothing is known about the exception, this is the method which |
|
1846 | If nothing is known about the exception, this is the method which | |
1842 | should be used throughout the code for presenting user tracebacks, |
|
1847 | should be used throughout the code for presenting user tracebacks, | |
1843 | rather than directly invoking the InteractiveTB object. |
|
1848 | rather than directly invoking the InteractiveTB object. | |
1844 |
|
1849 | |||
1845 | A specific showsyntaxerror() also exists, but this method can take |
|
1850 | A specific showsyntaxerror() also exists, but this method can take | |
1846 | care of calling it if needed, so unless you are explicitly catching a |
|
1851 | care of calling it if needed, so unless you are explicitly catching a | |
1847 | SyntaxError exception, don't try to analyze the stack manually and |
|
1852 | SyntaxError exception, don't try to analyze the stack manually and | |
1848 | simply call this method.""" |
|
1853 | simply call this method.""" | |
1849 |
|
1854 | |||
1850 | try: |
|
1855 | try: | |
1851 | try: |
|
1856 | try: | |
1852 | etype, value, tb = self._get_exc_info(exc_tuple) |
|
1857 | etype, value, tb = self._get_exc_info(exc_tuple) | |
1853 | except ValueError: |
|
1858 | except ValueError: | |
1854 | print('No traceback available to show.', file=sys.stderr) |
|
1859 | print('No traceback available to show.', file=sys.stderr) | |
1855 | return |
|
1860 | return | |
1856 |
|
1861 | |||
1857 | if issubclass(etype, SyntaxError): |
|
1862 | if issubclass(etype, SyntaxError): | |
1858 | # Though this won't be called by syntax errors in the input |
|
1863 | # Though this won't be called by syntax errors in the input | |
1859 | # line, there may be SyntaxError cases with imported code. |
|
1864 | # line, there may be SyntaxError cases with imported code. | |
1860 | self.showsyntaxerror(filename, running_compiled_code) |
|
1865 | self.showsyntaxerror(filename, running_compiled_code) | |
1861 | elif etype is UsageError: |
|
1866 | elif etype is UsageError: | |
1862 | self.show_usage_error(value) |
|
1867 | self.show_usage_error(value) | |
1863 | else: |
|
1868 | else: | |
1864 | if exception_only: |
|
1869 | if exception_only: | |
1865 | stb = ['An exception has occurred, use %tb to see ' |
|
1870 | stb = ['An exception has occurred, use %tb to see ' | |
1866 | 'the full traceback.\n'] |
|
1871 | 'the full traceback.\n'] | |
1867 | stb.extend(self.InteractiveTB.get_exception_only(etype, |
|
1872 | stb.extend(self.InteractiveTB.get_exception_only(etype, | |
1868 | value)) |
|
1873 | value)) | |
1869 | else: |
|
1874 | else: | |
1870 | try: |
|
1875 | try: | |
1871 | # Exception classes can customise their traceback - we |
|
1876 | # Exception classes can customise their traceback - we | |
1872 | # use this in IPython.parallel for exceptions occurring |
|
1877 | # use this in IPython.parallel for exceptions occurring | |
1873 | # in the engines. This should return a list of strings. |
|
1878 | # in the engines. This should return a list of strings. | |
1874 | stb = value._render_traceback_() |
|
1879 | stb = value._render_traceback_() | |
1875 | except Exception: |
|
1880 | except Exception: | |
1876 | stb = self.InteractiveTB.structured_traceback(etype, |
|
1881 | stb = self.InteractiveTB.structured_traceback(etype, | |
1877 | value, tb, tb_offset=tb_offset) |
|
1882 | value, tb, tb_offset=tb_offset) | |
1878 |
|
1883 | |||
1879 | self._showtraceback(etype, value, stb) |
|
1884 | self._showtraceback(etype, value, stb) | |
1880 | if self.call_pdb: |
|
1885 | if self.call_pdb: | |
1881 | # drop into debugger |
|
1886 | # drop into debugger | |
1882 | self.debugger(force=True) |
|
1887 | self.debugger(force=True) | |
1883 | return |
|
1888 | return | |
1884 |
|
1889 | |||
1885 | # Actually show the traceback |
|
1890 | # Actually show the traceback | |
1886 | self._showtraceback(etype, value, stb) |
|
1891 | self._showtraceback(etype, value, stb) | |
1887 |
|
1892 | |||
1888 | except KeyboardInterrupt: |
|
1893 | except KeyboardInterrupt: | |
1889 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
1894 | print('\n' + self.get_exception_only(), file=sys.stderr) | |
1890 |
|
1895 | |||
1891 | def _showtraceback(self, etype, evalue, stb): |
|
1896 | def _showtraceback(self, etype, evalue, stb): | |
1892 | """Actually show a traceback. |
|
1897 | """Actually show a traceback. | |
1893 |
|
1898 | |||
1894 | Subclasses may override this method to put the traceback on a different |
|
1899 | Subclasses may override this method to put the traceback on a different | |
1895 | place, like a side channel. |
|
1900 | place, like a side channel. | |
1896 | """ |
|
1901 | """ | |
1897 | print(self.InteractiveTB.stb2text(stb)) |
|
1902 | print(self.InteractiveTB.stb2text(stb)) | |
1898 |
|
1903 | |||
1899 | def showsyntaxerror(self, filename=None, running_compiled_code=False): |
|
1904 | def showsyntaxerror(self, filename=None, running_compiled_code=False): | |
1900 | """Display the syntax error that just occurred. |
|
1905 | """Display the syntax error that just occurred. | |
1901 |
|
1906 | |||
1902 | This doesn't display a stack trace because there isn't one. |
|
1907 | This doesn't display a stack trace because there isn't one. | |
1903 |
|
1908 | |||
1904 | If a filename is given, it is stuffed in the exception instead |
|
1909 | If a filename is given, it is stuffed in the exception instead | |
1905 | of what was there before (because Python's parser always uses |
|
1910 | of what was there before (because Python's parser always uses | |
1906 | "<string>" when reading from a string). |
|
1911 | "<string>" when reading from a string). | |
1907 |
|
1912 | |||
1908 | If the syntax error occurred when running a compiled code (i.e. running_compile_code=True), |
|
1913 | If the syntax error occurred when running a compiled code (i.e. running_compile_code=True), | |
1909 | longer stack trace will be displayed. |
|
1914 | longer stack trace will be displayed. | |
1910 | """ |
|
1915 | """ | |
1911 | etype, value, last_traceback = self._get_exc_info() |
|
1916 | etype, value, last_traceback = self._get_exc_info() | |
1912 |
|
1917 | |||
1913 | if filename and issubclass(etype, SyntaxError): |
|
1918 | if filename and issubclass(etype, SyntaxError): | |
1914 | try: |
|
1919 | try: | |
1915 | value.filename = filename |
|
1920 | value.filename = filename | |
1916 | except: |
|
1921 | except: | |
1917 | # Not the format we expect; leave it alone |
|
1922 | # Not the format we expect; leave it alone | |
1918 | pass |
|
1923 | pass | |
1919 |
|
1924 | |||
1920 | # If the error occurred when executing compiled code, we should provide full stacktrace. |
|
1925 | # If the error occurred when executing compiled code, we should provide full stacktrace. | |
1921 | elist = traceback.extract_tb(last_traceback) if running_compiled_code else [] |
|
1926 | elist = traceback.extract_tb(last_traceback) if running_compiled_code else [] | |
1922 | stb = self.SyntaxTB.structured_traceback(etype, value, elist) |
|
1927 | stb = self.SyntaxTB.structured_traceback(etype, value, elist) | |
1923 | self._showtraceback(etype, value, stb) |
|
1928 | self._showtraceback(etype, value, stb) | |
1924 |
|
1929 | |||
1925 | # This is overridden in TerminalInteractiveShell to show a message about |
|
1930 | # This is overridden in TerminalInteractiveShell to show a message about | |
1926 | # the %paste magic. |
|
1931 | # the %paste magic. | |
1927 | def showindentationerror(self): |
|
1932 | def showindentationerror(self): | |
1928 | """Called by _run_cell when there's an IndentationError in code entered |
|
1933 | """Called by _run_cell when there's an IndentationError in code entered | |
1929 | at the prompt. |
|
1934 | at the prompt. | |
1930 |
|
1935 | |||
1931 | This is overridden in TerminalInteractiveShell to show a message about |
|
1936 | This is overridden in TerminalInteractiveShell to show a message about | |
1932 | the %paste magic.""" |
|
1937 | the %paste magic.""" | |
1933 | self.showsyntaxerror() |
|
1938 | self.showsyntaxerror() | |
1934 |
|
1939 | |||
1935 | #------------------------------------------------------------------------- |
|
1940 | #------------------------------------------------------------------------- | |
1936 | # Things related to readline |
|
1941 | # Things related to readline | |
1937 | #------------------------------------------------------------------------- |
|
1942 | #------------------------------------------------------------------------- | |
1938 |
|
1943 | |||
1939 | def init_readline(self): |
|
1944 | def init_readline(self): | |
1940 | """DEPRECATED |
|
1945 | """DEPRECATED | |
1941 |
|
1946 | |||
1942 | Moved to terminal subclass, here only to simplify the init logic.""" |
|
1947 | Moved to terminal subclass, here only to simplify the init logic.""" | |
1943 | # Set a number of methods that depend on readline to be no-op |
|
1948 | # Set a number of methods that depend on readline to be no-op | |
1944 | warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', |
|
1949 | warnings.warn('`init_readline` is no-op since IPython 5.0 and is Deprecated', | |
1945 | DeprecationWarning, stacklevel=2) |
|
1950 | DeprecationWarning, stacklevel=2) | |
1946 | self.set_custom_completer = no_op |
|
1951 | self.set_custom_completer = no_op | |
1947 |
|
1952 | |||
1948 | @skip_doctest |
|
1953 | @skip_doctest | |
1949 | def set_next_input(self, s, replace=False): |
|
1954 | def set_next_input(self, s, replace=False): | |
1950 | """ Sets the 'default' input string for the next command line. |
|
1955 | """ Sets the 'default' input string for the next command line. | |
1951 |
|
1956 | |||
1952 | Example:: |
|
1957 | Example:: | |
1953 |
|
1958 | |||
1954 | In [1]: _ip.set_next_input("Hello Word") |
|
1959 | In [1]: _ip.set_next_input("Hello Word") | |
1955 | In [2]: Hello Word_ # cursor is here |
|
1960 | In [2]: Hello Word_ # cursor is here | |
1956 | """ |
|
1961 | """ | |
1957 | self.rl_next_input = s |
|
1962 | self.rl_next_input = s | |
1958 |
|
1963 | |||
1959 | def _indent_current_str(self): |
|
1964 | def _indent_current_str(self): | |
1960 | """return the current level of indentation as a string""" |
|
1965 | """return the current level of indentation as a string""" | |
1961 | return self.input_splitter.get_indent_spaces() * ' ' |
|
1966 | return self.input_splitter.get_indent_spaces() * ' ' | |
1962 |
|
1967 | |||
1963 | #------------------------------------------------------------------------- |
|
1968 | #------------------------------------------------------------------------- | |
1964 | # Things related to text completion |
|
1969 | # Things related to text completion | |
1965 | #------------------------------------------------------------------------- |
|
1970 | #------------------------------------------------------------------------- | |
1966 |
|
1971 | |||
1967 | def init_completer(self): |
|
1972 | def init_completer(self): | |
1968 | """Initialize the completion machinery. |
|
1973 | """Initialize the completion machinery. | |
1969 |
|
1974 | |||
1970 | This creates completion machinery that can be used by client code, |
|
1975 | This creates completion machinery that can be used by client code, | |
1971 | either interactively in-process (typically triggered by the readline |
|
1976 | either interactively in-process (typically triggered by the readline | |
1972 | library), programmatically (such as in test suites) or out-of-process |
|
1977 | library), programmatically (such as in test suites) or out-of-process | |
1973 | (typically over the network by remote frontends). |
|
1978 | (typically over the network by remote frontends). | |
1974 | """ |
|
1979 | """ | |
1975 | from IPython.core.completer import IPCompleter |
|
1980 | from IPython.core.completer import IPCompleter | |
1976 | from IPython.core.completerlib import (module_completer, |
|
1981 | from IPython.core.completerlib import (module_completer, | |
1977 | magic_run_completer, cd_completer, reset_completer) |
|
1982 | magic_run_completer, cd_completer, reset_completer) | |
1978 |
|
1983 | |||
1979 | self.Completer = IPCompleter(shell=self, |
|
1984 | self.Completer = IPCompleter(shell=self, | |
1980 | namespace=self.user_ns, |
|
1985 | namespace=self.user_ns, | |
1981 | global_namespace=self.user_global_ns, |
|
1986 | global_namespace=self.user_global_ns, | |
1982 | parent=self, |
|
1987 | parent=self, | |
1983 | ) |
|
1988 | ) | |
1984 | self.configurables.append(self.Completer) |
|
1989 | self.configurables.append(self.Completer) | |
1985 |
|
1990 | |||
1986 | # Add custom completers to the basic ones built into IPCompleter |
|
1991 | # Add custom completers to the basic ones built into IPCompleter | |
1987 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) |
|
1992 | sdisp = self.strdispatchers.get('complete_command', StrDispatch()) | |
1988 | self.strdispatchers['complete_command'] = sdisp |
|
1993 | self.strdispatchers['complete_command'] = sdisp | |
1989 | self.Completer.custom_completers = sdisp |
|
1994 | self.Completer.custom_completers = sdisp | |
1990 |
|
1995 | |||
1991 | self.set_hook('complete_command', module_completer, str_key = 'import') |
|
1996 | self.set_hook('complete_command', module_completer, str_key = 'import') | |
1992 | self.set_hook('complete_command', module_completer, str_key = 'from') |
|
1997 | self.set_hook('complete_command', module_completer, str_key = 'from') | |
1993 | self.set_hook('complete_command', module_completer, str_key = '%aimport') |
|
1998 | self.set_hook('complete_command', module_completer, str_key = '%aimport') | |
1994 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') |
|
1999 | self.set_hook('complete_command', magic_run_completer, str_key = '%run') | |
1995 | self.set_hook('complete_command', cd_completer, str_key = '%cd') |
|
2000 | self.set_hook('complete_command', cd_completer, str_key = '%cd') | |
1996 | self.set_hook('complete_command', reset_completer, str_key = '%reset') |
|
2001 | self.set_hook('complete_command', reset_completer, str_key = '%reset') | |
1997 |
|
2002 | |||
1998 |
|
2003 | |||
1999 | @skip_doctest |
|
2004 | @skip_doctest | |
2000 | def complete(self, text, line=None, cursor_pos=None): |
|
2005 | def complete(self, text, line=None, cursor_pos=None): | |
2001 | """Return the completed text and a list of completions. |
|
2006 | """Return the completed text and a list of completions. | |
2002 |
|
2007 | |||
2003 | Parameters |
|
2008 | Parameters | |
2004 | ---------- |
|
2009 | ---------- | |
2005 |
|
2010 | |||
2006 | text : string |
|
2011 | text : string | |
2007 | A string of text to be completed on. It can be given as empty and |
|
2012 | A string of text to be completed on. It can be given as empty and | |
2008 | instead a line/position pair are given. In this case, the |
|
2013 | instead a line/position pair are given. In this case, the | |
2009 | completer itself will split the line like readline does. |
|
2014 | completer itself will split the line like readline does. | |
2010 |
|
2015 | |||
2011 | line : string, optional |
|
2016 | line : string, optional | |
2012 | The complete line that text is part of. |
|
2017 | The complete line that text is part of. | |
2013 |
|
2018 | |||
2014 | cursor_pos : int, optional |
|
2019 | cursor_pos : int, optional | |
2015 | The position of the cursor on the input line. |
|
2020 | The position of the cursor on the input line. | |
2016 |
|
2021 | |||
2017 | Returns |
|
2022 | Returns | |
2018 | ------- |
|
2023 | ------- | |
2019 | text : string |
|
2024 | text : string | |
2020 | The actual text that was completed. |
|
2025 | The actual text that was completed. | |
2021 |
|
2026 | |||
2022 | matches : list |
|
2027 | matches : list | |
2023 | A sorted list with all possible completions. |
|
2028 | A sorted list with all possible completions. | |
2024 |
|
2029 | |||
2025 | The optional arguments allow the completion to take more context into |
|
2030 | The optional arguments allow the completion to take more context into | |
2026 | account, and are part of the low-level completion API. |
|
2031 | account, and are part of the low-level completion API. | |
2027 |
|
2032 | |||
2028 | This is a wrapper around the completion mechanism, similar to what |
|
2033 | This is a wrapper around the completion mechanism, similar to what | |
2029 | readline does at the command line when the TAB key is hit. By |
|
2034 | readline does at the command line when the TAB key is hit. By | |
2030 | exposing it as a method, it can be used by other non-readline |
|
2035 | exposing it as a method, it can be used by other non-readline | |
2031 | environments (such as GUIs) for text completion. |
|
2036 | environments (such as GUIs) for text completion. | |
2032 |
|
2037 | |||
2033 | Simple usage example: |
|
2038 | Simple usage example: | |
2034 |
|
2039 | |||
2035 | In [1]: x = 'hello' |
|
2040 | In [1]: x = 'hello' | |
2036 |
|
2041 | |||
2037 | In [2]: _ip.complete('x.l') |
|
2042 | In [2]: _ip.complete('x.l') | |
2038 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) |
|
2043 | Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip']) | |
2039 | """ |
|
2044 | """ | |
2040 |
|
2045 | |||
2041 | # Inject names into __builtin__ so we can complete on the added names. |
|
2046 | # Inject names into __builtin__ so we can complete on the added names. | |
2042 | with self.builtin_trap: |
|
2047 | with self.builtin_trap: | |
2043 | return self.Completer.complete(text, line, cursor_pos) |
|
2048 | return self.Completer.complete(text, line, cursor_pos) | |
2044 |
|
2049 | |||
2045 | def set_custom_completer(self, completer, pos=0): |
|
2050 | def set_custom_completer(self, completer, pos=0): | |
2046 | """Adds a new custom completer function. |
|
2051 | """Adds a new custom completer function. | |
2047 |
|
2052 | |||
2048 | The position argument (defaults to 0) is the index in the completers |
|
2053 | The position argument (defaults to 0) is the index in the completers | |
2049 | list where you want the completer to be inserted.""" |
|
2054 | list where you want the completer to be inserted.""" | |
2050 |
|
2055 | |||
2051 | newcomp = types.MethodType(completer,self.Completer) |
|
2056 | newcomp = types.MethodType(completer,self.Completer) | |
2052 | self.Completer.matchers.insert(pos,newcomp) |
|
2057 | self.Completer.matchers.insert(pos,newcomp) | |
2053 |
|
2058 | |||
2054 | def set_completer_frame(self, frame=None): |
|
2059 | def set_completer_frame(self, frame=None): | |
2055 | """Set the frame of the completer.""" |
|
2060 | """Set the frame of the completer.""" | |
2056 | if frame: |
|
2061 | if frame: | |
2057 | self.Completer.namespace = frame.f_locals |
|
2062 | self.Completer.namespace = frame.f_locals | |
2058 | self.Completer.global_namespace = frame.f_globals |
|
2063 | self.Completer.global_namespace = frame.f_globals | |
2059 | else: |
|
2064 | else: | |
2060 | self.Completer.namespace = self.user_ns |
|
2065 | self.Completer.namespace = self.user_ns | |
2061 | self.Completer.global_namespace = self.user_global_ns |
|
2066 | self.Completer.global_namespace = self.user_global_ns | |
2062 |
|
2067 | |||
2063 | #------------------------------------------------------------------------- |
|
2068 | #------------------------------------------------------------------------- | |
2064 | # Things related to magics |
|
2069 | # Things related to magics | |
2065 | #------------------------------------------------------------------------- |
|
2070 | #------------------------------------------------------------------------- | |
2066 |
|
2071 | |||
2067 | def init_magics(self): |
|
2072 | def init_magics(self): | |
2068 | from IPython.core import magics as m |
|
2073 | from IPython.core import magics as m | |
2069 | self.magics_manager = magic.MagicsManager(shell=self, |
|
2074 | self.magics_manager = magic.MagicsManager(shell=self, | |
2070 | parent=self, |
|
2075 | parent=self, | |
2071 | user_magics=m.UserMagics(self)) |
|
2076 | user_magics=m.UserMagics(self)) | |
2072 | self.configurables.append(self.magics_manager) |
|
2077 | self.configurables.append(self.magics_manager) | |
2073 |
|
2078 | |||
2074 | # Expose as public API from the magics manager |
|
2079 | # Expose as public API from the magics manager | |
2075 | self.register_magics = self.magics_manager.register |
|
2080 | self.register_magics = self.magics_manager.register | |
2076 |
|
2081 | |||
2077 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, |
|
2082 | self.register_magics(m.AutoMagics, m.BasicMagics, m.CodeMagics, | |
2078 | m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, |
|
2083 | m.ConfigMagics, m.DisplayMagics, m.ExecutionMagics, | |
2079 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, |
|
2084 | m.ExtensionMagics, m.HistoryMagics, m.LoggingMagics, | |
2080 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, |
|
2085 | m.NamespaceMagics, m.OSMagics, m.PylabMagics, m.ScriptMagics, | |
2081 | ) |
|
2086 | ) | |
2082 |
|
2087 | |||
2083 | # Register Magic Aliases |
|
2088 | # Register Magic Aliases | |
2084 | mman = self.magics_manager |
|
2089 | mman = self.magics_manager | |
2085 | # FIXME: magic aliases should be defined by the Magics classes |
|
2090 | # FIXME: magic aliases should be defined by the Magics classes | |
2086 | # or in MagicsManager, not here |
|
2091 | # or in MagicsManager, not here | |
2087 | mman.register_alias('ed', 'edit') |
|
2092 | mman.register_alias('ed', 'edit') | |
2088 | mman.register_alias('hist', 'history') |
|
2093 | mman.register_alias('hist', 'history') | |
2089 | mman.register_alias('rep', 'recall') |
|
2094 | mman.register_alias('rep', 'recall') | |
2090 | mman.register_alias('SVG', 'svg', 'cell') |
|
2095 | mman.register_alias('SVG', 'svg', 'cell') | |
2091 | mman.register_alias('HTML', 'html', 'cell') |
|
2096 | mman.register_alias('HTML', 'html', 'cell') | |
2092 | mman.register_alias('file', 'writefile', 'cell') |
|
2097 | mman.register_alias('file', 'writefile', 'cell') | |
2093 |
|
2098 | |||
2094 | # FIXME: Move the color initialization to the DisplayHook, which |
|
2099 | # FIXME: Move the color initialization to the DisplayHook, which | |
2095 | # should be split into a prompt manager and displayhook. We probably |
|
2100 | # should be split into a prompt manager and displayhook. We probably | |
2096 | # even need a centralize colors management object. |
|
2101 | # even need a centralize colors management object. | |
2097 | self.run_line_magic('colors', self.colors) |
|
2102 | self.run_line_magic('colors', self.colors) | |
2098 |
|
2103 | |||
2099 | # Defined here so that it's included in the documentation |
|
2104 | # Defined here so that it's included in the documentation | |
2100 | @functools.wraps(magic.MagicsManager.register_function) |
|
2105 | @functools.wraps(magic.MagicsManager.register_function) | |
2101 | def register_magic_function(self, func, magic_kind='line', magic_name=None): |
|
2106 | def register_magic_function(self, func, magic_kind='line', magic_name=None): | |
2102 | self.magics_manager.register_function(func, |
|
2107 | self.magics_manager.register_function(func, | |
2103 | magic_kind=magic_kind, magic_name=magic_name) |
|
2108 | magic_kind=magic_kind, magic_name=magic_name) | |
2104 |
|
2109 | |||
2105 | def run_line_magic(self, magic_name, line, _stack_depth=1): |
|
2110 | def run_line_magic(self, magic_name, line, _stack_depth=1): | |
2106 | """Execute the given line magic. |
|
2111 | """Execute the given line magic. | |
2107 |
|
2112 | |||
2108 | Parameters |
|
2113 | Parameters | |
2109 | ---------- |
|
2114 | ---------- | |
2110 | magic_name : str |
|
2115 | magic_name : str | |
2111 | Name of the desired magic function, without '%' prefix. |
|
2116 | Name of the desired magic function, without '%' prefix. | |
2112 |
|
2117 | |||
2113 | line : str |
|
2118 | line : str | |
2114 | The rest of the input line as a single string. |
|
2119 | The rest of the input line as a single string. | |
2115 |
|
2120 | |||
2116 | _stack_depth : int |
|
2121 | _stack_depth : int | |
2117 | If run_line_magic() is called from magic() then _stack_depth=2. |
|
2122 | If run_line_magic() is called from magic() then _stack_depth=2. | |
2118 | This is added to ensure backward compatibility for use of 'get_ipython().magic()' |
|
2123 | This is added to ensure backward compatibility for use of 'get_ipython().magic()' | |
2119 | """ |
|
2124 | """ | |
2120 | fn = self.find_line_magic(magic_name) |
|
2125 | fn = self.find_line_magic(magic_name) | |
2121 | if fn is None: |
|
2126 | if fn is None: | |
2122 | cm = self.find_cell_magic(magic_name) |
|
2127 | cm = self.find_cell_magic(magic_name) | |
2123 | etpl = "Line magic function `%%%s` not found%s." |
|
2128 | etpl = "Line magic function `%%%s` not found%s." | |
2124 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' |
|
2129 | extra = '' if cm is None else (' (But cell magic `%%%%%s` exists, ' | |
2125 | 'did you mean that instead?)' % magic_name ) |
|
2130 | 'did you mean that instead?)' % magic_name ) | |
2126 | raise UsageError(etpl % (magic_name, extra)) |
|
2131 | raise UsageError(etpl % (magic_name, extra)) | |
2127 | else: |
|
2132 | else: | |
2128 | # Note: this is the distance in the stack to the user's frame. |
|
2133 | # Note: this is the distance in the stack to the user's frame. | |
2129 | # This will need to be updated if the internal calling logic gets |
|
2134 | # This will need to be updated if the internal calling logic gets | |
2130 | # refactored, or else we'll be expanding the wrong variables. |
|
2135 | # refactored, or else we'll be expanding the wrong variables. | |
2131 |
|
2136 | |||
2132 | # Determine stack_depth depending on where run_line_magic() has been called |
|
2137 | # Determine stack_depth depending on where run_line_magic() has been called | |
2133 | stack_depth = _stack_depth |
|
2138 | stack_depth = _stack_depth | |
2134 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2139 | magic_arg_s = self.var_expand(line, stack_depth) | |
2135 | # Put magic args in a list so we can call with f(*a) syntax |
|
2140 | # Put magic args in a list so we can call with f(*a) syntax | |
2136 | args = [magic_arg_s] |
|
2141 | args = [magic_arg_s] | |
2137 | kwargs = {} |
|
2142 | kwargs = {} | |
2138 | # Grab local namespace if we need it: |
|
2143 | # Grab local namespace if we need it: | |
2139 | if getattr(fn, "needs_local_scope", False): |
|
2144 | if getattr(fn, "needs_local_scope", False): | |
2140 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals |
|
2145 | kwargs['local_ns'] = sys._getframe(stack_depth).f_locals | |
2141 | with self.builtin_trap: |
|
2146 | with self.builtin_trap: | |
2142 | result = fn(*args,**kwargs) |
|
2147 | result = fn(*args,**kwargs) | |
2143 | return result |
|
2148 | return result | |
2144 |
|
2149 | |||
2145 | def run_cell_magic(self, magic_name, line, cell): |
|
2150 | def run_cell_magic(self, magic_name, line, cell): | |
2146 | """Execute the given cell magic. |
|
2151 | """Execute the given cell magic. | |
2147 |
|
2152 | |||
2148 | Parameters |
|
2153 | Parameters | |
2149 | ---------- |
|
2154 | ---------- | |
2150 | magic_name : str |
|
2155 | magic_name : str | |
2151 | Name of the desired magic function, without '%' prefix. |
|
2156 | Name of the desired magic function, without '%' prefix. | |
2152 |
|
2157 | |||
2153 | line : str |
|
2158 | line : str | |
2154 | The rest of the first input line as a single string. |
|
2159 | The rest of the first input line as a single string. | |
2155 |
|
2160 | |||
2156 | cell : str |
|
2161 | cell : str | |
2157 | The body of the cell as a (possibly multiline) string. |
|
2162 | The body of the cell as a (possibly multiline) string. | |
2158 | """ |
|
2163 | """ | |
2159 | fn = self.find_cell_magic(magic_name) |
|
2164 | fn = self.find_cell_magic(magic_name) | |
2160 | if fn is None: |
|
2165 | if fn is None: | |
2161 | lm = self.find_line_magic(magic_name) |
|
2166 | lm = self.find_line_magic(magic_name) | |
2162 | etpl = "Cell magic `%%{0}` not found{1}." |
|
2167 | etpl = "Cell magic `%%{0}` not found{1}." | |
2163 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' |
|
2168 | extra = '' if lm is None else (' (But line magic `%{0}` exists, ' | |
2164 | 'did you mean that instead?)'.format(magic_name)) |
|
2169 | 'did you mean that instead?)'.format(magic_name)) | |
2165 | raise UsageError(etpl.format(magic_name, extra)) |
|
2170 | raise UsageError(etpl.format(magic_name, extra)) | |
2166 | elif cell == '': |
|
2171 | elif cell == '': | |
2167 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) |
|
2172 | message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name) | |
2168 | if self.find_line_magic(magic_name) is not None: |
|
2173 | if self.find_line_magic(magic_name) is not None: | |
2169 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) |
|
2174 | message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name) | |
2170 | raise UsageError(message) |
|
2175 | raise UsageError(message) | |
2171 | else: |
|
2176 | else: | |
2172 | # Note: this is the distance in the stack to the user's frame. |
|
2177 | # Note: this is the distance in the stack to the user's frame. | |
2173 | # This will need to be updated if the internal calling logic gets |
|
2178 | # This will need to be updated if the internal calling logic gets | |
2174 | # refactored, or else we'll be expanding the wrong variables. |
|
2179 | # refactored, or else we'll be expanding the wrong variables. | |
2175 | stack_depth = 2 |
|
2180 | stack_depth = 2 | |
2176 | magic_arg_s = self.var_expand(line, stack_depth) |
|
2181 | magic_arg_s = self.var_expand(line, stack_depth) | |
2177 | with self.builtin_trap: |
|
2182 | with self.builtin_trap: | |
2178 | result = fn(magic_arg_s, cell) |
|
2183 | result = fn(magic_arg_s, cell) | |
2179 | return result |
|
2184 | return result | |
2180 |
|
2185 | |||
2181 | def find_line_magic(self, magic_name): |
|
2186 | def find_line_magic(self, magic_name): | |
2182 | """Find and return a line magic by name. |
|
2187 | """Find and return a line magic by name. | |
2183 |
|
2188 | |||
2184 | Returns None if the magic isn't found.""" |
|
2189 | Returns None if the magic isn't found.""" | |
2185 | return self.magics_manager.magics['line'].get(magic_name) |
|
2190 | return self.magics_manager.magics['line'].get(magic_name) | |
2186 |
|
2191 | |||
2187 | def find_cell_magic(self, magic_name): |
|
2192 | def find_cell_magic(self, magic_name): | |
2188 | """Find and return a cell magic by name. |
|
2193 | """Find and return a cell magic by name. | |
2189 |
|
2194 | |||
2190 | Returns None if the magic isn't found.""" |
|
2195 | Returns None if the magic isn't found.""" | |
2191 | return self.magics_manager.magics['cell'].get(magic_name) |
|
2196 | return self.magics_manager.magics['cell'].get(magic_name) | |
2192 |
|
2197 | |||
2193 | def find_magic(self, magic_name, magic_kind='line'): |
|
2198 | def find_magic(self, magic_name, magic_kind='line'): | |
2194 | """Find and return a magic of the given type by name. |
|
2199 | """Find and return a magic of the given type by name. | |
2195 |
|
2200 | |||
2196 | Returns None if the magic isn't found.""" |
|
2201 | Returns None if the magic isn't found.""" | |
2197 | return self.magics_manager.magics[magic_kind].get(magic_name) |
|
2202 | return self.magics_manager.magics[magic_kind].get(magic_name) | |
2198 |
|
2203 | |||
2199 | def magic(self, arg_s): |
|
2204 | def magic(self, arg_s): | |
2200 | """DEPRECATED. Use run_line_magic() instead. |
|
2205 | """DEPRECATED. Use run_line_magic() instead. | |
2201 |
|
2206 | |||
2202 | Call a magic function by name. |
|
2207 | Call a magic function by name. | |
2203 |
|
2208 | |||
2204 | Input: a string containing the name of the magic function to call and |
|
2209 | Input: a string containing the name of the magic function to call and | |
2205 | any additional arguments to be passed to the magic. |
|
2210 | any additional arguments to be passed to the magic. | |
2206 |
|
2211 | |||
2207 | magic('name -opt foo bar') is equivalent to typing at the ipython |
|
2212 | magic('name -opt foo bar') is equivalent to typing at the ipython | |
2208 | prompt: |
|
2213 | prompt: | |
2209 |
|
2214 | |||
2210 | In[1]: %name -opt foo bar |
|
2215 | In[1]: %name -opt foo bar | |
2211 |
|
2216 | |||
2212 | To call a magic without arguments, simply use magic('name'). |
|
2217 | To call a magic without arguments, simply use magic('name'). | |
2213 |
|
2218 | |||
2214 | This provides a proper Python function to call IPython's magics in any |
|
2219 | This provides a proper Python function to call IPython's magics in any | |
2215 | valid Python code you can type at the interpreter, including loops and |
|
2220 | valid Python code you can type at the interpreter, including loops and | |
2216 | compound statements. |
|
2221 | compound statements. | |
2217 | """ |
|
2222 | """ | |
2218 | # TODO: should we issue a loud deprecation warning here? |
|
2223 | # TODO: should we issue a loud deprecation warning here? | |
2219 | magic_name, _, magic_arg_s = arg_s.partition(' ') |
|
2224 | magic_name, _, magic_arg_s = arg_s.partition(' ') | |
2220 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) |
|
2225 | magic_name = magic_name.lstrip(prefilter.ESC_MAGIC) | |
2221 | return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2) |
|
2226 | return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2) | |
2222 |
|
2227 | |||
2223 | #------------------------------------------------------------------------- |
|
2228 | #------------------------------------------------------------------------- | |
2224 | # Things related to macros |
|
2229 | # Things related to macros | |
2225 | #------------------------------------------------------------------------- |
|
2230 | #------------------------------------------------------------------------- | |
2226 |
|
2231 | |||
2227 | def define_macro(self, name, themacro): |
|
2232 | def define_macro(self, name, themacro): | |
2228 | """Define a new macro |
|
2233 | """Define a new macro | |
2229 |
|
2234 | |||
2230 | Parameters |
|
2235 | Parameters | |
2231 | ---------- |
|
2236 | ---------- | |
2232 | name : str |
|
2237 | name : str | |
2233 | The name of the macro. |
|
2238 | The name of the macro. | |
2234 | themacro : str or Macro |
|
2239 | themacro : str or Macro | |
2235 | The action to do upon invoking the macro. If a string, a new |
|
2240 | The action to do upon invoking the macro. If a string, a new | |
2236 | Macro object is created by passing the string to it. |
|
2241 | Macro object is created by passing the string to it. | |
2237 | """ |
|
2242 | """ | |
2238 |
|
2243 | |||
2239 | from IPython.core import macro |
|
2244 | from IPython.core import macro | |
2240 |
|
2245 | |||
2241 | if isinstance(themacro, str): |
|
2246 | if isinstance(themacro, str): | |
2242 | themacro = macro.Macro(themacro) |
|
2247 | themacro = macro.Macro(themacro) | |
2243 | if not isinstance(themacro, macro.Macro): |
|
2248 | if not isinstance(themacro, macro.Macro): | |
2244 | raise ValueError('A macro must be a string or a Macro instance.') |
|
2249 | raise ValueError('A macro must be a string or a Macro instance.') | |
2245 | self.user_ns[name] = themacro |
|
2250 | self.user_ns[name] = themacro | |
2246 |
|
2251 | |||
2247 | #------------------------------------------------------------------------- |
|
2252 | #------------------------------------------------------------------------- | |
2248 | # Things related to the running of system commands |
|
2253 | # Things related to the running of system commands | |
2249 | #------------------------------------------------------------------------- |
|
2254 | #------------------------------------------------------------------------- | |
2250 |
|
2255 | |||
2251 | def system_piped(self, cmd): |
|
2256 | def system_piped(self, cmd): | |
2252 | """Call the given cmd in a subprocess, piping stdout/err |
|
2257 | """Call the given cmd in a subprocess, piping stdout/err | |
2253 |
|
2258 | |||
2254 | Parameters |
|
2259 | Parameters | |
2255 | ---------- |
|
2260 | ---------- | |
2256 | cmd : str |
|
2261 | cmd : str | |
2257 | Command to execute (can not end in '&', as background processes are |
|
2262 | Command to execute (can not end in '&', as background processes are | |
2258 | not supported. Should not be a command that expects input |
|
2263 | not supported. Should not be a command that expects input | |
2259 | other than simple text. |
|
2264 | other than simple text. | |
2260 | """ |
|
2265 | """ | |
2261 | if cmd.rstrip().endswith('&'): |
|
2266 | if cmd.rstrip().endswith('&'): | |
2262 | # this is *far* from a rigorous test |
|
2267 | # this is *far* from a rigorous test | |
2263 | # We do not support backgrounding processes because we either use |
|
2268 | # We do not support backgrounding processes because we either use | |
2264 | # pexpect or pipes to read from. Users can always just call |
|
2269 | # pexpect or pipes to read from. Users can always just call | |
2265 | # os.system() or use ip.system=ip.system_raw |
|
2270 | # os.system() or use ip.system=ip.system_raw | |
2266 | # if they really want a background process. |
|
2271 | # if they really want a background process. | |
2267 | raise OSError("Background processes not supported.") |
|
2272 | raise OSError("Background processes not supported.") | |
2268 |
|
2273 | |||
2269 | # we explicitly do NOT return the subprocess status code, because |
|
2274 | # we explicitly do NOT return the subprocess status code, because | |
2270 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2275 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2271 | # Instead, we store the exit_code in user_ns. |
|
2276 | # Instead, we store the exit_code in user_ns. | |
2272 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) |
|
2277 | self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1)) | |
2273 |
|
2278 | |||
2274 | def system_raw(self, cmd): |
|
2279 | def system_raw(self, cmd): | |
2275 | """Call the given cmd in a subprocess using os.system on Windows or |
|
2280 | """Call the given cmd in a subprocess using os.system on Windows or | |
2276 | subprocess.call using the system shell on other platforms. |
|
2281 | subprocess.call using the system shell on other platforms. | |
2277 |
|
2282 | |||
2278 | Parameters |
|
2283 | Parameters | |
2279 | ---------- |
|
2284 | ---------- | |
2280 | cmd : str |
|
2285 | cmd : str | |
2281 | Command to execute. |
|
2286 | Command to execute. | |
2282 | """ |
|
2287 | """ | |
2283 | cmd = self.var_expand(cmd, depth=1) |
|
2288 | cmd = self.var_expand(cmd, depth=1) | |
2284 | # protect os.system from UNC paths on Windows, which it can't handle: |
|
2289 | # protect os.system from UNC paths on Windows, which it can't handle: | |
2285 | if sys.platform == 'win32': |
|
2290 | if sys.platform == 'win32': | |
2286 | from IPython.utils._process_win32 import AvoidUNCPath |
|
2291 | from IPython.utils._process_win32 import AvoidUNCPath | |
2287 | with AvoidUNCPath() as path: |
|
2292 | with AvoidUNCPath() as path: | |
2288 | if path is not None: |
|
2293 | if path is not None: | |
2289 | cmd = '"pushd %s &&"%s' % (path, cmd) |
|
2294 | cmd = '"pushd %s &&"%s' % (path, cmd) | |
2290 | try: |
|
2295 | try: | |
2291 | ec = os.system(cmd) |
|
2296 | ec = os.system(cmd) | |
2292 | except KeyboardInterrupt: |
|
2297 | except KeyboardInterrupt: | |
2293 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2298 | print('\n' + self.get_exception_only(), file=sys.stderr) | |
2294 | ec = -2 |
|
2299 | ec = -2 | |
2295 | else: |
|
2300 | else: | |
2296 | # For posix the result of the subprocess.call() below is an exit |
|
2301 | # For posix the result of the subprocess.call() below is an exit | |
2297 | # code, which by convention is zero for success, positive for |
|
2302 | # code, which by convention is zero for success, positive for | |
2298 | # program failure. Exit codes above 128 are reserved for signals, |
|
2303 | # program failure. Exit codes above 128 are reserved for signals, | |
2299 | # and the formula for converting a signal to an exit code is usually |
|
2304 | # and the formula for converting a signal to an exit code is usually | |
2300 | # signal_number+128. To more easily differentiate between exit |
|
2305 | # signal_number+128. To more easily differentiate between exit | |
2301 | # codes and signals, ipython uses negative numbers. For instance |
|
2306 | # codes and signals, ipython uses negative numbers. For instance | |
2302 | # since control-c is signal 2 but exit code 130, ipython's |
|
2307 | # since control-c is signal 2 but exit code 130, ipython's | |
2303 | # _exit_code variable will read -2. Note that some shells like |
|
2308 | # _exit_code variable will read -2. Note that some shells like | |
2304 | # csh and fish don't follow sh/bash conventions for exit codes. |
|
2309 | # csh and fish don't follow sh/bash conventions for exit codes. | |
2305 | executable = os.environ.get('SHELL', None) |
|
2310 | executable = os.environ.get('SHELL', None) | |
2306 | try: |
|
2311 | try: | |
2307 | # Use env shell instead of default /bin/sh |
|
2312 | # Use env shell instead of default /bin/sh | |
2308 | ec = subprocess.call(cmd, shell=True, executable=executable) |
|
2313 | ec = subprocess.call(cmd, shell=True, executable=executable) | |
2309 | except KeyboardInterrupt: |
|
2314 | except KeyboardInterrupt: | |
2310 | # intercept control-C; a long traceback is not useful here |
|
2315 | # intercept control-C; a long traceback is not useful here | |
2311 | print('\n' + self.get_exception_only(), file=sys.stderr) |
|
2316 | print('\n' + self.get_exception_only(), file=sys.stderr) | |
2312 | ec = 130 |
|
2317 | ec = 130 | |
2313 | if ec > 128: |
|
2318 | if ec > 128: | |
2314 | ec = -(ec - 128) |
|
2319 | ec = -(ec - 128) | |
2315 |
|
2320 | |||
2316 | # We explicitly do NOT return the subprocess status code, because |
|
2321 | # We explicitly do NOT return the subprocess status code, because | |
2317 | # a non-None value would trigger :func:`sys.displayhook` calls. |
|
2322 | # a non-None value would trigger :func:`sys.displayhook` calls. | |
2318 | # Instead, we store the exit_code in user_ns. Note the semantics |
|
2323 | # Instead, we store the exit_code in user_ns. Note the semantics | |
2319 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, |
|
2324 | # of _exit_code: for control-c, _exit_code == -signal.SIGNIT, | |
2320 | # but raising SystemExit(_exit_code) will give status 254! |
|
2325 | # but raising SystemExit(_exit_code) will give status 254! | |
2321 | self.user_ns['_exit_code'] = ec |
|
2326 | self.user_ns['_exit_code'] = ec | |
2322 |
|
2327 | |||
2323 | # use piped system by default, because it is better behaved |
|
2328 | # use piped system by default, because it is better behaved | |
2324 | system = system_piped |
|
2329 | system = system_piped | |
2325 |
|
2330 | |||
2326 | def getoutput(self, cmd, split=True, depth=0): |
|
2331 | def getoutput(self, cmd, split=True, depth=0): | |
2327 | """Get output (possibly including stderr) from a subprocess. |
|
2332 | """Get output (possibly including stderr) from a subprocess. | |
2328 |
|
2333 | |||
2329 | Parameters |
|
2334 | Parameters | |
2330 | ---------- |
|
2335 | ---------- | |
2331 | cmd : str |
|
2336 | cmd : str | |
2332 | Command to execute (can not end in '&', as background processes are |
|
2337 | Command to execute (can not end in '&', as background processes are | |
2333 | not supported. |
|
2338 | not supported. | |
2334 | split : bool, optional |
|
2339 | split : bool, optional | |
2335 | If True, split the output into an IPython SList. Otherwise, an |
|
2340 | If True, split the output into an IPython SList. Otherwise, an | |
2336 | IPython LSString is returned. These are objects similar to normal |
|
2341 | IPython LSString is returned. These are objects similar to normal | |
2337 | lists and strings, with a few convenience attributes for easier |
|
2342 | lists and strings, with a few convenience attributes for easier | |
2338 | manipulation of line-based output. You can use '?' on them for |
|
2343 | manipulation of line-based output. You can use '?' on them for | |
2339 | details. |
|
2344 | details. | |
2340 | depth : int, optional |
|
2345 | depth : int, optional | |
2341 | How many frames above the caller are the local variables which should |
|
2346 | How many frames above the caller are the local variables which should | |
2342 | be expanded in the command string? The default (0) assumes that the |
|
2347 | be expanded in the command string? The default (0) assumes that the | |
2343 | expansion variables are in the stack frame calling this function. |
|
2348 | expansion variables are in the stack frame calling this function. | |
2344 | """ |
|
2349 | """ | |
2345 | if cmd.rstrip().endswith('&'): |
|
2350 | if cmd.rstrip().endswith('&'): | |
2346 | # this is *far* from a rigorous test |
|
2351 | # this is *far* from a rigorous test | |
2347 | raise OSError("Background processes not supported.") |
|
2352 | raise OSError("Background processes not supported.") | |
2348 | out = getoutput(self.var_expand(cmd, depth=depth+1)) |
|
2353 | out = getoutput(self.var_expand(cmd, depth=depth+1)) | |
2349 | if split: |
|
2354 | if split: | |
2350 | out = SList(out.splitlines()) |
|
2355 | out = SList(out.splitlines()) | |
2351 | else: |
|
2356 | else: | |
2352 | out = LSString(out) |
|
2357 | out = LSString(out) | |
2353 | return out |
|
2358 | return out | |
2354 |
|
2359 | |||
2355 | #------------------------------------------------------------------------- |
|
2360 | #------------------------------------------------------------------------- | |
2356 | # Things related to aliases |
|
2361 | # Things related to aliases | |
2357 | #------------------------------------------------------------------------- |
|
2362 | #------------------------------------------------------------------------- | |
2358 |
|
2363 | |||
2359 | def init_alias(self): |
|
2364 | def init_alias(self): | |
2360 | self.alias_manager = AliasManager(shell=self, parent=self) |
|
2365 | self.alias_manager = AliasManager(shell=self, parent=self) | |
2361 | self.configurables.append(self.alias_manager) |
|
2366 | self.configurables.append(self.alias_manager) | |
2362 |
|
2367 | |||
2363 | #------------------------------------------------------------------------- |
|
2368 | #------------------------------------------------------------------------- | |
2364 | # Things related to extensions |
|
2369 | # Things related to extensions | |
2365 | #------------------------------------------------------------------------- |
|
2370 | #------------------------------------------------------------------------- | |
2366 |
|
2371 | |||
2367 | def init_extension_manager(self): |
|
2372 | def init_extension_manager(self): | |
2368 | self.extension_manager = ExtensionManager(shell=self, parent=self) |
|
2373 | self.extension_manager = ExtensionManager(shell=self, parent=self) | |
2369 | self.configurables.append(self.extension_manager) |
|
2374 | self.configurables.append(self.extension_manager) | |
2370 |
|
2375 | |||
2371 | #------------------------------------------------------------------------- |
|
2376 | #------------------------------------------------------------------------- | |
2372 | # Things related to payloads |
|
2377 | # Things related to payloads | |
2373 | #------------------------------------------------------------------------- |
|
2378 | #------------------------------------------------------------------------- | |
2374 |
|
2379 | |||
2375 | def init_payload(self): |
|
2380 | def init_payload(self): | |
2376 | self.payload_manager = PayloadManager(parent=self) |
|
2381 | self.payload_manager = PayloadManager(parent=self) | |
2377 | self.configurables.append(self.payload_manager) |
|
2382 | self.configurables.append(self.payload_manager) | |
2378 |
|
2383 | |||
2379 | #------------------------------------------------------------------------- |
|
2384 | #------------------------------------------------------------------------- | |
2380 | # Things related to the prefilter |
|
2385 | # Things related to the prefilter | |
2381 | #------------------------------------------------------------------------- |
|
2386 | #------------------------------------------------------------------------- | |
2382 |
|
2387 | |||
2383 | def init_prefilter(self): |
|
2388 | def init_prefilter(self): | |
2384 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) |
|
2389 | self.prefilter_manager = PrefilterManager(shell=self, parent=self) | |
2385 | self.configurables.append(self.prefilter_manager) |
|
2390 | self.configurables.append(self.prefilter_manager) | |
2386 | # Ultimately this will be refactored in the new interpreter code, but |
|
2391 | # Ultimately this will be refactored in the new interpreter code, but | |
2387 | # for now, we should expose the main prefilter method (there's legacy |
|
2392 | # for now, we should expose the main prefilter method (there's legacy | |
2388 | # code out there that may rely on this). |
|
2393 | # code out there that may rely on this). | |
2389 | self.prefilter = self.prefilter_manager.prefilter_lines |
|
2394 | self.prefilter = self.prefilter_manager.prefilter_lines | |
2390 |
|
2395 | |||
2391 | def auto_rewrite_input(self, cmd): |
|
2396 | def auto_rewrite_input(self, cmd): | |
2392 | """Print to the screen the rewritten form of the user's command. |
|
2397 | """Print to the screen the rewritten form of the user's command. | |
2393 |
|
2398 | |||
2394 | This shows visual feedback by rewriting input lines that cause |
|
2399 | This shows visual feedback by rewriting input lines that cause | |
2395 | automatic calling to kick in, like:: |
|
2400 | automatic calling to kick in, like:: | |
2396 |
|
2401 | |||
2397 | /f x |
|
2402 | /f x | |
2398 |
|
2403 | |||
2399 | into:: |
|
2404 | into:: | |
2400 |
|
2405 | |||
2401 | ------> f(x) |
|
2406 | ------> f(x) | |
2402 |
|
2407 | |||
2403 | after the user's input prompt. This helps the user understand that the |
|
2408 | after the user's input prompt. This helps the user understand that the | |
2404 | input line was transformed automatically by IPython. |
|
2409 | input line was transformed automatically by IPython. | |
2405 | """ |
|
2410 | """ | |
2406 | if not self.show_rewritten_input: |
|
2411 | if not self.show_rewritten_input: | |
2407 | return |
|
2412 | return | |
2408 |
|
2413 | |||
2409 | # This is overridden in TerminalInteractiveShell to use fancy prompts |
|
2414 | # This is overridden in TerminalInteractiveShell to use fancy prompts | |
2410 | print("------> " + cmd) |
|
2415 | print("------> " + cmd) | |
2411 |
|
2416 | |||
2412 | #------------------------------------------------------------------------- |
|
2417 | #------------------------------------------------------------------------- | |
2413 | # Things related to extracting values/expressions from kernel and user_ns |
|
2418 | # Things related to extracting values/expressions from kernel and user_ns | |
2414 | #------------------------------------------------------------------------- |
|
2419 | #------------------------------------------------------------------------- | |
2415 |
|
2420 | |||
2416 | def _user_obj_error(self): |
|
2421 | def _user_obj_error(self): | |
2417 | """return simple exception dict |
|
2422 | """return simple exception dict | |
2418 |
|
2423 | |||
2419 | for use in user_expressions |
|
2424 | for use in user_expressions | |
2420 | """ |
|
2425 | """ | |
2421 |
|
2426 | |||
2422 | etype, evalue, tb = self._get_exc_info() |
|
2427 | etype, evalue, tb = self._get_exc_info() | |
2423 | stb = self.InteractiveTB.get_exception_only(etype, evalue) |
|
2428 | stb = self.InteractiveTB.get_exception_only(etype, evalue) | |
2424 |
|
2429 | |||
2425 | exc_info = { |
|
2430 | exc_info = { | |
2426 | u'status' : 'error', |
|
2431 | u'status' : 'error', | |
2427 | u'traceback' : stb, |
|
2432 | u'traceback' : stb, | |
2428 | u'ename' : etype.__name__, |
|
2433 | u'ename' : etype.__name__, | |
2429 | u'evalue' : py3compat.safe_unicode(evalue), |
|
2434 | u'evalue' : py3compat.safe_unicode(evalue), | |
2430 | } |
|
2435 | } | |
2431 |
|
2436 | |||
2432 | return exc_info |
|
2437 | return exc_info | |
2433 |
|
2438 | |||
2434 | def _format_user_obj(self, obj): |
|
2439 | def _format_user_obj(self, obj): | |
2435 | """format a user object to display dict |
|
2440 | """format a user object to display dict | |
2436 |
|
2441 | |||
2437 | for use in user_expressions |
|
2442 | for use in user_expressions | |
2438 | """ |
|
2443 | """ | |
2439 |
|
2444 | |||
2440 | data, md = self.display_formatter.format(obj) |
|
2445 | data, md = self.display_formatter.format(obj) | |
2441 | value = { |
|
2446 | value = { | |
2442 | 'status' : 'ok', |
|
2447 | 'status' : 'ok', | |
2443 | 'data' : data, |
|
2448 | 'data' : data, | |
2444 | 'metadata' : md, |
|
2449 | 'metadata' : md, | |
2445 | } |
|
2450 | } | |
2446 | return value |
|
2451 | return value | |
2447 |
|
2452 | |||
2448 | def user_expressions(self, expressions): |
|
2453 | def user_expressions(self, expressions): | |
2449 | """Evaluate a dict of expressions in the user's namespace. |
|
2454 | """Evaluate a dict of expressions in the user's namespace. | |
2450 |
|
2455 | |||
2451 | Parameters |
|
2456 | Parameters | |
2452 | ---------- |
|
2457 | ---------- | |
2453 | expressions : dict |
|
2458 | expressions : dict | |
2454 | A dict with string keys and string values. The expression values |
|
2459 | A dict with string keys and string values. The expression values | |
2455 | should be valid Python expressions, each of which will be evaluated |
|
2460 | should be valid Python expressions, each of which will be evaluated | |
2456 | in the user namespace. |
|
2461 | in the user namespace. | |
2457 |
|
2462 | |||
2458 | Returns |
|
2463 | Returns | |
2459 | ------- |
|
2464 | ------- | |
2460 | A dict, keyed like the input expressions dict, with the rich mime-typed |
|
2465 | A dict, keyed like the input expressions dict, with the rich mime-typed | |
2461 | display_data of each value. |
|
2466 | display_data of each value. | |
2462 | """ |
|
2467 | """ | |
2463 | out = {} |
|
2468 | out = {} | |
2464 | user_ns = self.user_ns |
|
2469 | user_ns = self.user_ns | |
2465 | global_ns = self.user_global_ns |
|
2470 | global_ns = self.user_global_ns | |
2466 |
|
2471 | |||
2467 | for key, expr in expressions.items(): |
|
2472 | for key, expr in expressions.items(): | |
2468 | try: |
|
2473 | try: | |
2469 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) |
|
2474 | value = self._format_user_obj(eval(expr, global_ns, user_ns)) | |
2470 | except: |
|
2475 | except: | |
2471 | value = self._user_obj_error() |
|
2476 | value = self._user_obj_error() | |
2472 | out[key] = value |
|
2477 | out[key] = value | |
2473 | return out |
|
2478 | return out | |
2474 |
|
2479 | |||
2475 | #------------------------------------------------------------------------- |
|
2480 | #------------------------------------------------------------------------- | |
2476 | # Things related to the running of code |
|
2481 | # Things related to the running of code | |
2477 | #------------------------------------------------------------------------- |
|
2482 | #------------------------------------------------------------------------- | |
2478 |
|
2483 | |||
2479 | def ex(self, cmd): |
|
2484 | def ex(self, cmd): | |
2480 | """Execute a normal python statement in user namespace.""" |
|
2485 | """Execute a normal python statement in user namespace.""" | |
2481 | with self.builtin_trap: |
|
2486 | with self.builtin_trap: | |
2482 | exec(cmd, self.user_global_ns, self.user_ns) |
|
2487 | exec(cmd, self.user_global_ns, self.user_ns) | |
2483 |
|
2488 | |||
2484 | def ev(self, expr): |
|
2489 | def ev(self, expr): | |
2485 | """Evaluate python expression expr in user namespace. |
|
2490 | """Evaluate python expression expr in user namespace. | |
2486 |
|
2491 | |||
2487 | Returns the result of evaluation |
|
2492 | Returns the result of evaluation | |
2488 | """ |
|
2493 | """ | |
2489 | with self.builtin_trap: |
|
2494 | with self.builtin_trap: | |
2490 | return eval(expr, self.user_global_ns, self.user_ns) |
|
2495 | return eval(expr, self.user_global_ns, self.user_ns) | |
2491 |
|
2496 | |||
2492 | def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False): |
|
2497 | def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False): | |
2493 | """A safe version of the builtin execfile(). |
|
2498 | """A safe version of the builtin execfile(). | |
2494 |
|
2499 | |||
2495 | This version will never throw an exception, but instead print |
|
2500 | This version will never throw an exception, but instead print | |
2496 | helpful error messages to the screen. This only works on pure |
|
2501 | helpful error messages to the screen. This only works on pure | |
2497 | Python files with the .py extension. |
|
2502 | Python files with the .py extension. | |
2498 |
|
2503 | |||
2499 | Parameters |
|
2504 | Parameters | |
2500 | ---------- |
|
2505 | ---------- | |
2501 | fname : string |
|
2506 | fname : string | |
2502 | The name of the file to be executed. |
|
2507 | The name of the file to be executed. | |
2503 | where : tuple |
|
2508 | where : tuple | |
2504 | One or two namespaces, passed to execfile() as (globals,locals). |
|
2509 | One or two namespaces, passed to execfile() as (globals,locals). | |
2505 | If only one is given, it is passed as both. |
|
2510 | If only one is given, it is passed as both. | |
2506 | exit_ignore : bool (False) |
|
2511 | exit_ignore : bool (False) | |
2507 | If True, then silence SystemExit for non-zero status (it is always |
|
2512 | If True, then silence SystemExit for non-zero status (it is always | |
2508 | silenced for zero status, as it is so common). |
|
2513 | silenced for zero status, as it is so common). | |
2509 | raise_exceptions : bool (False) |
|
2514 | raise_exceptions : bool (False) | |
2510 | If True raise exceptions everywhere. Meant for testing. |
|
2515 | If True raise exceptions everywhere. Meant for testing. | |
2511 | shell_futures : bool (False) |
|
2516 | shell_futures : bool (False) | |
2512 | If True, the code will share future statements with the interactive |
|
2517 | If True, the code will share future statements with the interactive | |
2513 | shell. It will both be affected by previous __future__ imports, and |
|
2518 | shell. It will both be affected by previous __future__ imports, and | |
2514 | any __future__ imports in the code will affect the shell. If False, |
|
2519 | any __future__ imports in the code will affect the shell. If False, | |
2515 | __future__ imports are not shared in either direction. |
|
2520 | __future__ imports are not shared in either direction. | |
2516 |
|
2521 | |||
2517 | """ |
|
2522 | """ | |
2518 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2523 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2519 |
|
2524 | |||
2520 | # Make sure we can open the file |
|
2525 | # Make sure we can open the file | |
2521 | try: |
|
2526 | try: | |
2522 | with open(fname): |
|
2527 | with open(fname): | |
2523 | pass |
|
2528 | pass | |
2524 | except: |
|
2529 | except: | |
2525 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2530 | warn('Could not open file <%s> for safe execution.' % fname) | |
2526 | return |
|
2531 | return | |
2527 |
|
2532 | |||
2528 | # Find things also in current directory. This is needed to mimic the |
|
2533 | # Find things also in current directory. This is needed to mimic the | |
2529 | # behavior of running a script from the system command line, where |
|
2534 | # behavior of running a script from the system command line, where | |
2530 | # Python inserts the script's directory into sys.path |
|
2535 | # Python inserts the script's directory into sys.path | |
2531 | dname = os.path.dirname(fname) |
|
2536 | dname = os.path.dirname(fname) | |
2532 |
|
2537 | |||
2533 | with prepended_to_syspath(dname), self.builtin_trap: |
|
2538 | with prepended_to_syspath(dname), self.builtin_trap: | |
2534 | try: |
|
2539 | try: | |
2535 | glob, loc = (where + (None, ))[:2] |
|
2540 | glob, loc = (where + (None, ))[:2] | |
2536 | py3compat.execfile( |
|
2541 | py3compat.execfile( | |
2537 | fname, glob, loc, |
|
2542 | fname, glob, loc, | |
2538 | self.compile if shell_futures else None) |
|
2543 | self.compile if shell_futures else None) | |
2539 | except SystemExit as status: |
|
2544 | except SystemExit as status: | |
2540 | # If the call was made with 0 or None exit status (sys.exit(0) |
|
2545 | # If the call was made with 0 or None exit status (sys.exit(0) | |
2541 | # or sys.exit() ), don't bother showing a traceback, as both of |
|
2546 | # or sys.exit() ), don't bother showing a traceback, as both of | |
2542 | # these are considered normal by the OS: |
|
2547 | # these are considered normal by the OS: | |
2543 | # > python -c'import sys;sys.exit(0)'; echo $? |
|
2548 | # > python -c'import sys;sys.exit(0)'; echo $? | |
2544 | # 0 |
|
2549 | # 0 | |
2545 | # > python -c'import sys;sys.exit()'; echo $? |
|
2550 | # > python -c'import sys;sys.exit()'; echo $? | |
2546 | # 0 |
|
2551 | # 0 | |
2547 | # For other exit status, we show the exception unless |
|
2552 | # For other exit status, we show the exception unless | |
2548 | # explicitly silenced, but only in short form. |
|
2553 | # explicitly silenced, but only in short form. | |
2549 | if status.code: |
|
2554 | if status.code: | |
2550 | if raise_exceptions: |
|
2555 | if raise_exceptions: | |
2551 | raise |
|
2556 | raise | |
2552 | if not exit_ignore: |
|
2557 | if not exit_ignore: | |
2553 | self.showtraceback(exception_only=True) |
|
2558 | self.showtraceback(exception_only=True) | |
2554 | except: |
|
2559 | except: | |
2555 | if raise_exceptions: |
|
2560 | if raise_exceptions: | |
2556 | raise |
|
2561 | raise | |
2557 | # tb offset is 2 because we wrap execfile |
|
2562 | # tb offset is 2 because we wrap execfile | |
2558 | self.showtraceback(tb_offset=2) |
|
2563 | self.showtraceback(tb_offset=2) | |
2559 |
|
2564 | |||
2560 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): |
|
2565 | def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False): | |
2561 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. |
|
2566 | """Like safe_execfile, but for .ipy or .ipynb files with IPython syntax. | |
2562 |
|
2567 | |||
2563 | Parameters |
|
2568 | Parameters | |
2564 | ---------- |
|
2569 | ---------- | |
2565 | fname : str |
|
2570 | fname : str | |
2566 | The name of the file to execute. The filename must have a |
|
2571 | The name of the file to execute. The filename must have a | |
2567 | .ipy or .ipynb extension. |
|
2572 | .ipy or .ipynb extension. | |
2568 | shell_futures : bool (False) |
|
2573 | shell_futures : bool (False) | |
2569 | If True, the code will share future statements with the interactive |
|
2574 | If True, the code will share future statements with the interactive | |
2570 | shell. It will both be affected by previous __future__ imports, and |
|
2575 | shell. It will both be affected by previous __future__ imports, and | |
2571 | any __future__ imports in the code will affect the shell. If False, |
|
2576 | any __future__ imports in the code will affect the shell. If False, | |
2572 | __future__ imports are not shared in either direction. |
|
2577 | __future__ imports are not shared in either direction. | |
2573 | raise_exceptions : bool (False) |
|
2578 | raise_exceptions : bool (False) | |
2574 | If True raise exceptions everywhere. Meant for testing. |
|
2579 | If True raise exceptions everywhere. Meant for testing. | |
2575 | """ |
|
2580 | """ | |
2576 | fname = os.path.abspath(os.path.expanduser(fname)) |
|
2581 | fname = os.path.abspath(os.path.expanduser(fname)) | |
2577 |
|
2582 | |||
2578 | # Make sure we can open the file |
|
2583 | # Make sure we can open the file | |
2579 | try: |
|
2584 | try: | |
2580 | with open(fname): |
|
2585 | with open(fname): | |
2581 | pass |
|
2586 | pass | |
2582 | except: |
|
2587 | except: | |
2583 | warn('Could not open file <%s> for safe execution.' % fname) |
|
2588 | warn('Could not open file <%s> for safe execution.' % fname) | |
2584 | return |
|
2589 | return | |
2585 |
|
2590 | |||
2586 | # Find things also in current directory. This is needed to mimic the |
|
2591 | # Find things also in current directory. This is needed to mimic the | |
2587 | # behavior of running a script from the system command line, where |
|
2592 | # behavior of running a script from the system command line, where | |
2588 | # Python inserts the script's directory into sys.path |
|
2593 | # Python inserts the script's directory into sys.path | |
2589 | dname = os.path.dirname(fname) |
|
2594 | dname = os.path.dirname(fname) | |
2590 |
|
2595 | |||
2591 | def get_cells(): |
|
2596 | def get_cells(): | |
2592 | """generator for sequence of code blocks to run""" |
|
2597 | """generator for sequence of code blocks to run""" | |
2593 | if fname.endswith('.ipynb'): |
|
2598 | if fname.endswith('.ipynb'): | |
2594 | from nbformat import read |
|
2599 | from nbformat import read | |
2595 | nb = read(fname, as_version=4) |
|
2600 | nb = read(fname, as_version=4) | |
2596 | if not nb.cells: |
|
2601 | if not nb.cells: | |
2597 | return |
|
2602 | return | |
2598 | for cell in nb.cells: |
|
2603 | for cell in nb.cells: | |
2599 | if cell.cell_type == 'code': |
|
2604 | if cell.cell_type == 'code': | |
2600 | yield cell.source |
|
2605 | yield cell.source | |
2601 | else: |
|
2606 | else: | |
2602 | with open(fname) as f: |
|
2607 | with open(fname) as f: | |
2603 | yield f.read() |
|
2608 | yield f.read() | |
2604 |
|
2609 | |||
2605 | with prepended_to_syspath(dname): |
|
2610 | with prepended_to_syspath(dname): | |
2606 | try: |
|
2611 | try: | |
2607 | for cell in get_cells(): |
|
2612 | for cell in get_cells(): | |
2608 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) |
|
2613 | result = self.run_cell(cell, silent=True, shell_futures=shell_futures) | |
2609 | if raise_exceptions: |
|
2614 | if raise_exceptions: | |
2610 | result.raise_error() |
|
2615 | result.raise_error() | |
2611 | elif not result.success: |
|
2616 | elif not result.success: | |
2612 | break |
|
2617 | break | |
2613 | except: |
|
2618 | except: | |
2614 | if raise_exceptions: |
|
2619 | if raise_exceptions: | |
2615 | raise |
|
2620 | raise | |
2616 | self.showtraceback() |
|
2621 | self.showtraceback() | |
2617 | warn('Unknown failure executing file: <%s>' % fname) |
|
2622 | warn('Unknown failure executing file: <%s>' % fname) | |
2618 |
|
2623 | |||
2619 | def safe_run_module(self, mod_name, where): |
|
2624 | def safe_run_module(self, mod_name, where): | |
2620 | """A safe version of runpy.run_module(). |
|
2625 | """A safe version of runpy.run_module(). | |
2621 |
|
2626 | |||
2622 | This version will never throw an exception, but instead print |
|
2627 | This version will never throw an exception, but instead print | |
2623 | helpful error messages to the screen. |
|
2628 | helpful error messages to the screen. | |
2624 |
|
2629 | |||
2625 | `SystemExit` exceptions with status code 0 or None are ignored. |
|
2630 | `SystemExit` exceptions with status code 0 or None are ignored. | |
2626 |
|
2631 | |||
2627 | Parameters |
|
2632 | Parameters | |
2628 | ---------- |
|
2633 | ---------- | |
2629 | mod_name : string |
|
2634 | mod_name : string | |
2630 | The name of the module to be executed. |
|
2635 | The name of the module to be executed. | |
2631 | where : dict |
|
2636 | where : dict | |
2632 | The globals namespace. |
|
2637 | The globals namespace. | |
2633 | """ |
|
2638 | """ | |
2634 | try: |
|
2639 | try: | |
2635 | try: |
|
2640 | try: | |
2636 | where.update( |
|
2641 | where.update( | |
2637 | runpy.run_module(str(mod_name), run_name="__main__", |
|
2642 | runpy.run_module(str(mod_name), run_name="__main__", | |
2638 | alter_sys=True) |
|
2643 | alter_sys=True) | |
2639 | ) |
|
2644 | ) | |
2640 | except SystemExit as status: |
|
2645 | except SystemExit as status: | |
2641 | if status.code: |
|
2646 | if status.code: | |
2642 | raise |
|
2647 | raise | |
2643 | except: |
|
2648 | except: | |
2644 | self.showtraceback() |
|
2649 | self.showtraceback() | |
2645 | warn('Unknown failure executing module: <%s>' % mod_name) |
|
2650 | warn('Unknown failure executing module: <%s>' % mod_name) | |
2646 |
|
2651 | |||
2647 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): |
|
2652 | def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True): | |
2648 | """Run a complete IPython cell. |
|
2653 | """Run a complete IPython cell. | |
2649 |
|
2654 | |||
2650 | Parameters |
|
2655 | Parameters | |
2651 | ---------- |
|
2656 | ---------- | |
2652 | raw_cell : str |
|
2657 | raw_cell : str | |
2653 | The code (including IPython code such as %magic functions) to run. |
|
2658 | The code (including IPython code such as %magic functions) to run. | |
2654 | store_history : bool |
|
2659 | store_history : bool | |
2655 | If True, the raw and translated cell will be stored in IPython's |
|
2660 | If True, the raw and translated cell will be stored in IPython's | |
2656 | history. For user code calling back into IPython's machinery, this |
|
2661 | history. For user code calling back into IPython's machinery, this | |
2657 | should be set to False. |
|
2662 | should be set to False. | |
2658 | silent : bool |
|
2663 | silent : bool | |
2659 | If True, avoid side-effects, such as implicit displayhooks and |
|
2664 | If True, avoid side-effects, such as implicit displayhooks and | |
2660 | and logging. silent=True forces store_history=False. |
|
2665 | and logging. silent=True forces store_history=False. | |
2661 | shell_futures : bool |
|
2666 | shell_futures : bool | |
2662 | If True, the code will share future statements with the interactive |
|
2667 | If True, the code will share future statements with the interactive | |
2663 | shell. It will both be affected by previous __future__ imports, and |
|
2668 | shell. It will both be affected by previous __future__ imports, and | |
2664 | any __future__ imports in the code will affect the shell. If False, |
|
2669 | any __future__ imports in the code will affect the shell. If False, | |
2665 | __future__ imports are not shared in either direction. |
|
2670 | __future__ imports are not shared in either direction. | |
2666 |
|
2671 | |||
2667 | Returns |
|
2672 | Returns | |
2668 | ------- |
|
2673 | ------- | |
2669 | result : :class:`ExecutionResult` |
|
2674 | result : :class:`ExecutionResult` | |
2670 | """ |
|
2675 | """ | |
2671 | result = None |
|
2676 | result = None | |
2672 | try: |
|
2677 | try: | |
2673 | result = self._run_cell( |
|
2678 | result = self._run_cell( | |
2674 | raw_cell, store_history, silent, shell_futures) |
|
2679 | raw_cell, store_history, silent, shell_futures) | |
2675 | finally: |
|
2680 | finally: | |
2676 | self.events.trigger('post_execute') |
|
2681 | self.events.trigger('post_execute') | |
2677 | if not silent: |
|
2682 | if not silent: | |
2678 | self.events.trigger('post_run_cell', result) |
|
2683 | self.events.trigger('post_run_cell', result) | |
2679 | return result |
|
2684 | return result | |
2680 |
|
2685 | |||
2681 | def _run_cell(self, raw_cell, store_history, silent, shell_futures): |
|
2686 | def _run_cell(self, raw_cell, store_history, silent, shell_futures): | |
2682 | """Internal method to run a complete IPython cell. |
|
2687 | """Internal method to run a complete IPython cell. | |
2683 |
|
2688 | |||
2684 | Parameters |
|
2689 | Parameters | |
2685 | ---------- |
|
2690 | ---------- | |
2686 | raw_cell : str |
|
2691 | raw_cell : str | |
2687 | store_history : bool |
|
2692 | store_history : bool | |
2688 | silent : bool |
|
2693 | silent : bool | |
2689 | shell_futures : bool |
|
2694 | shell_futures : bool | |
2690 |
|
2695 | |||
2691 | Returns |
|
2696 | Returns | |
2692 | ------- |
|
2697 | ------- | |
2693 | result : :class:`ExecutionResult` |
|
2698 | result : :class:`ExecutionResult` | |
2694 | """ |
|
2699 | """ | |
2695 | info = ExecutionInfo( |
|
2700 | info = ExecutionInfo( | |
2696 | raw_cell, store_history, silent, shell_futures) |
|
2701 | raw_cell, store_history, silent, shell_futures) | |
2697 | result = ExecutionResult(info) |
|
2702 | result = ExecutionResult(info) | |
2698 |
|
2703 | |||
2699 | if (not raw_cell) or raw_cell.isspace(): |
|
2704 | if (not raw_cell) or raw_cell.isspace(): | |
2700 | self.last_execution_succeeded = True |
|
2705 | self.last_execution_succeeded = True | |
2701 | self.last_execution_result = result |
|
2706 | self.last_execution_result = result | |
2702 | return result |
|
2707 | return result | |
2703 |
|
2708 | |||
2704 | if silent: |
|
2709 | if silent: | |
2705 | store_history = False |
|
2710 | store_history = False | |
2706 |
|
2711 | |||
2707 | if store_history: |
|
2712 | if store_history: | |
2708 | result.execution_count = self.execution_count |
|
2713 | result.execution_count = self.execution_count | |
2709 |
|
2714 | |||
2710 | def error_before_exec(value): |
|
2715 | def error_before_exec(value): | |
2711 | if store_history: |
|
2716 | if store_history: | |
2712 | self.execution_count += 1 |
|
2717 | self.execution_count += 1 | |
2713 | result.error_before_exec = value |
|
2718 | result.error_before_exec = value | |
2714 | self.last_execution_succeeded = False |
|
2719 | self.last_execution_succeeded = False | |
2715 | self.last_execution_result = result |
|
2720 | self.last_execution_result = result | |
2716 | return result |
|
2721 | return result | |
2717 |
|
2722 | |||
2718 | self.events.trigger('pre_execute') |
|
2723 | self.events.trigger('pre_execute') | |
2719 | if not silent: |
|
2724 | if not silent: | |
2720 | self.events.trigger('pre_run_cell', info) |
|
2725 | self.events.trigger('pre_run_cell', info) | |
2721 |
|
2726 | |||
2722 | # If any of our input transformation (input_transformer_manager or |
|
2727 | # If any of our input transformation (input_transformer_manager or | |
2723 | # prefilter_manager) raises an exception, we store it in this variable |
|
2728 | # prefilter_manager) raises an exception, we store it in this variable | |
2724 | # so that we can display the error after logging the input and storing |
|
2729 | # so that we can display the error after logging the input and storing | |
2725 | # it in the history. |
|
2730 | # it in the history. | |
2726 | preprocessing_exc_tuple = None |
|
2731 | preprocessing_exc_tuple = None | |
2727 | try: |
|
2732 | try: | |
2728 | # Static input transformations |
|
2733 | # Static input transformations | |
2729 | cell = self.transform_cell(raw_cell) |
|
2734 | cell = self.transform_cell(raw_cell) | |
2730 | except Exception: |
|
2735 | except Exception: | |
2731 | preprocessing_exc_tuple = sys.exc_info() |
|
2736 | preprocessing_exc_tuple = sys.exc_info() | |
2732 | cell = raw_cell # cell has to exist so it can be stored/logged |
|
2737 | cell = raw_cell # cell has to exist so it can be stored/logged | |
2733 |
|
2738 | |||
2734 | # Store raw and processed history |
|
2739 | # Store raw and processed history | |
2735 | if store_history: |
|
2740 | if store_history: | |
2736 | self.history_manager.store_inputs(self.execution_count, |
|
2741 | self.history_manager.store_inputs(self.execution_count, | |
2737 | cell, raw_cell) |
|
2742 | cell, raw_cell) | |
2738 | if not silent: |
|
2743 | if not silent: | |
2739 | self.logger.log(cell, raw_cell) |
|
2744 | self.logger.log(cell, raw_cell) | |
2740 |
|
2745 | |||
2741 | # Display the exception if input processing failed. |
|
2746 | # Display the exception if input processing failed. | |
2742 | if preprocessing_exc_tuple is not None: |
|
2747 | if preprocessing_exc_tuple is not None: | |
2743 | self.showtraceback(preprocessing_exc_tuple) |
|
2748 | self.showtraceback(preprocessing_exc_tuple) | |
2744 | if store_history: |
|
2749 | if store_history: | |
2745 | self.execution_count += 1 |
|
2750 | self.execution_count += 1 | |
2746 | return error_before_exec(preprocessing_exc_tuple[2]) |
|
2751 | return error_before_exec(preprocessing_exc_tuple[2]) | |
2747 |
|
2752 | |||
2748 | # Our own compiler remembers the __future__ environment. If we want to |
|
2753 | # Our own compiler remembers the __future__ environment. If we want to | |
2749 | # run code with a separate __future__ environment, use the default |
|
2754 | # run code with a separate __future__ environment, use the default | |
2750 | # compiler |
|
2755 | # compiler | |
2751 | compiler = self.compile if shell_futures else CachingCompiler() |
|
2756 | compiler = self.compile if shell_futures else CachingCompiler() | |
2752 |
|
2757 | |||
2753 | with self.builtin_trap: |
|
2758 | with self.builtin_trap: | |
2754 | cell_name = self.compile.cache(cell, self.execution_count) |
|
2759 | cell_name = self.compile.cache(cell, self.execution_count) | |
2755 |
|
2760 | |||
2756 | with self.display_trap: |
|
2761 | with self.display_trap: | |
2757 | # Compile to bytecode |
|
2762 | # Compile to bytecode | |
2758 | try: |
|
2763 | try: | |
2759 | code_ast = compiler.ast_parse(cell, filename=cell_name) |
|
2764 | code_ast = compiler.ast_parse(cell, filename=cell_name) | |
2760 | except self.custom_exceptions as e: |
|
2765 | except self.custom_exceptions as e: | |
2761 | etype, value, tb = sys.exc_info() |
|
2766 | etype, value, tb = sys.exc_info() | |
2762 | self.CustomTB(etype, value, tb) |
|
2767 | self.CustomTB(etype, value, tb) | |
2763 | return error_before_exec(e) |
|
2768 | return error_before_exec(e) | |
2764 | except IndentationError as e: |
|
2769 | except IndentationError as e: | |
2765 | self.showindentationerror() |
|
2770 | self.showindentationerror() | |
2766 | return error_before_exec(e) |
|
2771 | return error_before_exec(e) | |
2767 | except (OverflowError, SyntaxError, ValueError, TypeError, |
|
2772 | except (OverflowError, SyntaxError, ValueError, TypeError, | |
2768 | MemoryError) as e: |
|
2773 | MemoryError) as e: | |
2769 | self.showsyntaxerror() |
|
2774 | self.showsyntaxerror() | |
2770 | return error_before_exec(e) |
|
2775 | return error_before_exec(e) | |
2771 |
|
2776 | |||
2772 | # Apply AST transformations |
|
2777 | # Apply AST transformations | |
2773 | try: |
|
2778 | try: | |
2774 | code_ast = self.transform_ast(code_ast) |
|
2779 | code_ast = self.transform_ast(code_ast) | |
2775 | except InputRejected as e: |
|
2780 | except InputRejected as e: | |
2776 | self.showtraceback() |
|
2781 | self.showtraceback() | |
2777 | return error_before_exec(e) |
|
2782 | return error_before_exec(e) | |
2778 |
|
2783 | |||
2779 | # Give the displayhook a reference to our ExecutionResult so it |
|
2784 | # Give the displayhook a reference to our ExecutionResult so it | |
2780 | # can fill in the output value. |
|
2785 | # can fill in the output value. | |
2781 | self.displayhook.exec_result = result |
|
2786 | self.displayhook.exec_result = result | |
2782 |
|
2787 | |||
2783 | # Execute the user code |
|
2788 | # Execute the user code | |
2784 | interactivity = 'none' if silent else self.ast_node_interactivity |
|
2789 | interactivity = 'none' if silent else self.ast_node_interactivity | |
2785 | has_raised = self.run_ast_nodes(code_ast.body, cell_name, |
|
2790 | has_raised = self.run_ast_nodes(code_ast.body, cell_name, | |
2786 | interactivity=interactivity, compiler=compiler, result=result) |
|
2791 | interactivity=interactivity, compiler=compiler, result=result) | |
2787 |
|
2792 | |||
2788 | self.last_execution_succeeded = not has_raised |
|
2793 | self.last_execution_succeeded = not has_raised | |
2789 | self.last_execution_result = result |
|
2794 | self.last_execution_result = result | |
2790 |
|
2795 | |||
2791 | # Reset this so later displayed values do not modify the |
|
2796 | # Reset this so later displayed values do not modify the | |
2792 | # ExecutionResult |
|
2797 | # ExecutionResult | |
2793 | self.displayhook.exec_result = None |
|
2798 | self.displayhook.exec_result = None | |
2794 |
|
2799 | |||
2795 | if store_history: |
|
2800 | if store_history: | |
2796 | # Write output to the database. Does nothing unless |
|
2801 | # Write output to the database. Does nothing unless | |
2797 | # history output logging is enabled. |
|
2802 | # history output logging is enabled. | |
2798 | self.history_manager.store_output(self.execution_count) |
|
2803 | self.history_manager.store_output(self.execution_count) | |
2799 | # Each cell is a *single* input, regardless of how many lines it has |
|
2804 | # Each cell is a *single* input, regardless of how many lines it has | |
2800 | self.execution_count += 1 |
|
2805 | self.execution_count += 1 | |
2801 |
|
2806 | |||
2802 | return result |
|
2807 | return result | |
2803 |
|
2808 | |||
2804 | def transform_cell(self, raw_cell): |
|
2809 | def transform_cell(self, raw_cell): | |
2805 | # Static input transformations |
|
2810 | # Static input transformations | |
2806 | cell = self.input_transformer_manager.transform_cell(raw_cell) |
|
2811 | cell = self.input_transformer_manager.transform_cell(raw_cell) | |
2807 |
|
2812 | |||
2808 | if len(cell.splitlines()) == 1: |
|
2813 | if len(cell.splitlines()) == 1: | |
2809 | # Dynamic transformations - only applied for single line commands |
|
2814 | # Dynamic transformations - only applied for single line commands | |
2810 | with self.builtin_trap: |
|
2815 | with self.builtin_trap: | |
2811 | # use prefilter_lines to handle trailing newlines |
|
2816 | # use prefilter_lines to handle trailing newlines | |
2812 | # restore trailing newline for ast.parse |
|
2817 | # restore trailing newline for ast.parse | |
2813 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' |
|
2818 | cell = self.prefilter_manager.prefilter_lines(cell) + '\n' | |
2814 |
|
2819 | |||
2815 | lines = cell.splitlines(keepends=True) |
|
2820 | lines = cell.splitlines(keepends=True) | |
2816 | for transform in self.input_transformers_post: |
|
2821 | for transform in self.input_transformers_post: | |
2817 | lines = transform(lines) |
|
2822 | lines = transform(lines) | |
2818 | cell = ''.join(lines) |
|
2823 | cell = ''.join(lines) | |
2819 |
|
2824 | |||
2820 | return cell |
|
2825 | return cell | |
2821 |
|
2826 | |||
2822 | def transform_ast(self, node): |
|
2827 | def transform_ast(self, node): | |
2823 | """Apply the AST transformations from self.ast_transformers |
|
2828 | """Apply the AST transformations from self.ast_transformers | |
2824 |
|
2829 | |||
2825 | Parameters |
|
2830 | Parameters | |
2826 | ---------- |
|
2831 | ---------- | |
2827 | node : ast.Node |
|
2832 | node : ast.Node | |
2828 | The root node to be transformed. Typically called with the ast.Module |
|
2833 | The root node to be transformed. Typically called with the ast.Module | |
2829 | produced by parsing user input. |
|
2834 | produced by parsing user input. | |
2830 |
|
2835 | |||
2831 | Returns |
|
2836 | Returns | |
2832 | ------- |
|
2837 | ------- | |
2833 | An ast.Node corresponding to the node it was called with. Note that it |
|
2838 | An ast.Node corresponding to the node it was called with. Note that it | |
2834 | may also modify the passed object, so don't rely on references to the |
|
2839 | may also modify the passed object, so don't rely on references to the | |
2835 | original AST. |
|
2840 | original AST. | |
2836 | """ |
|
2841 | """ | |
2837 | for transformer in self.ast_transformers: |
|
2842 | for transformer in self.ast_transformers: | |
2838 | try: |
|
2843 | try: | |
2839 | node = transformer.visit(node) |
|
2844 | node = transformer.visit(node) | |
2840 | except InputRejected: |
|
2845 | except InputRejected: | |
2841 | # User-supplied AST transformers can reject an input by raising |
|
2846 | # User-supplied AST transformers can reject an input by raising | |
2842 | # an InputRejected. Short-circuit in this case so that we |
|
2847 | # an InputRejected. Short-circuit in this case so that we | |
2843 | # don't unregister the transform. |
|
2848 | # don't unregister the transform. | |
2844 | raise |
|
2849 | raise | |
2845 | except Exception: |
|
2850 | except Exception: | |
2846 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) |
|
2851 | warn("AST transformer %r threw an error. It will be unregistered." % transformer) | |
2847 | self.ast_transformers.remove(transformer) |
|
2852 | self.ast_transformers.remove(transformer) | |
2848 |
|
2853 | |||
2849 | if self.ast_transformers: |
|
2854 | if self.ast_transformers: | |
2850 | ast.fix_missing_locations(node) |
|
2855 | ast.fix_missing_locations(node) | |
2851 | return node |
|
2856 | return node | |
2852 |
|
2857 | |||
2853 |
|
2858 | |||
2854 | def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr', |
|
2859 | def run_ast_nodes(self, nodelist:ListType[AST], cell_name:str, interactivity='last_expr', | |
2855 | compiler=compile, result=None): |
|
2860 | compiler=compile, result=None): | |
2856 | """Run a sequence of AST nodes. The execution mode depends on the |
|
2861 | """Run a sequence of AST nodes. The execution mode depends on the | |
2857 | interactivity parameter. |
|
2862 | interactivity parameter. | |
2858 |
|
2863 | |||
2859 | Parameters |
|
2864 | Parameters | |
2860 | ---------- |
|
2865 | ---------- | |
2861 | nodelist : list |
|
2866 | nodelist : list | |
2862 | A sequence of AST nodes to run. |
|
2867 | A sequence of AST nodes to run. | |
2863 | cell_name : str |
|
2868 | cell_name : str | |
2864 | Will be passed to the compiler as the filename of the cell. Typically |
|
2869 | Will be passed to the compiler as the filename of the cell. Typically | |
2865 | the value returned by ip.compile.cache(cell). |
|
2870 | the value returned by ip.compile.cache(cell). | |
2866 | interactivity : str |
|
2871 | interactivity : str | |
2867 | 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none', |
|
2872 | 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none', | |
2868 | specifying which nodes should be run interactively (displaying output |
|
2873 | specifying which nodes should be run interactively (displaying output | |
2869 | from expressions). 'last_expr' will run the last node interactively |
|
2874 | from expressions). 'last_expr' will run the last node interactively | |
2870 | only if it is an expression (i.e. expressions in loops or other blocks |
|
2875 | only if it is an expression (i.e. expressions in loops or other blocks | |
2871 | are not displayed) 'last_expr_or_assign' will run the last expression |
|
2876 | are not displayed) 'last_expr_or_assign' will run the last expression | |
2872 | or the last assignment. Other values for this parameter will raise a |
|
2877 | or the last assignment. Other values for this parameter will raise a | |
2873 | ValueError. |
|
2878 | ValueError. | |
2874 | compiler : callable |
|
2879 | compiler : callable | |
2875 | A function with the same interface as the built-in compile(), to turn |
|
2880 | A function with the same interface as the built-in compile(), to turn | |
2876 | the AST nodes into code objects. Default is the built-in compile(). |
|
2881 | the AST nodes into code objects. Default is the built-in compile(). | |
2877 | result : ExecutionResult, optional |
|
2882 | result : ExecutionResult, optional | |
2878 | An object to store exceptions that occur during execution. |
|
2883 | An object to store exceptions that occur during execution. | |
2879 |
|
2884 | |||
2880 | Returns |
|
2885 | Returns | |
2881 | ------- |
|
2886 | ------- | |
2882 | True if an exception occurred while running code, False if it finished |
|
2887 | True if an exception occurred while running code, False if it finished | |
2883 | running. |
|
2888 | running. | |
2884 | """ |
|
2889 | """ | |
2885 | if not nodelist: |
|
2890 | if not nodelist: | |
2886 | return |
|
2891 | return | |
2887 | if interactivity == 'last_expr_or_assign': |
|
2892 | if interactivity == 'last_expr_or_assign': | |
2888 | if isinstance(nodelist[-1], _assign_nodes): |
|
2893 | if isinstance(nodelist[-1], _assign_nodes): | |
2889 | asg = nodelist[-1] |
|
2894 | asg = nodelist[-1] | |
2890 | if isinstance(asg, ast.Assign) and len(asg.targets) == 1: |
|
2895 | if isinstance(asg, ast.Assign) and len(asg.targets) == 1: | |
2891 | target = asg.targets[0] |
|
2896 | target = asg.targets[0] | |
2892 | elif isinstance(asg, _single_targets_nodes): |
|
2897 | elif isinstance(asg, _single_targets_nodes): | |
2893 | target = asg.target |
|
2898 | target = asg.target | |
2894 | else: |
|
2899 | else: | |
2895 | target = None |
|
2900 | target = None | |
2896 | if isinstance(target, ast.Name): |
|
2901 | if isinstance(target, ast.Name): | |
2897 | nnode = ast.Expr(ast.Name(target.id, ast.Load())) |
|
2902 | nnode = ast.Expr(ast.Name(target.id, ast.Load())) | |
2898 | ast.fix_missing_locations(nnode) |
|
2903 | ast.fix_missing_locations(nnode) | |
2899 | nodelist.append(nnode) |
|
2904 | nodelist.append(nnode) | |
2900 | interactivity = 'last_expr' |
|
2905 | interactivity = 'last_expr' | |
2901 |
|
2906 | |||
2902 | if interactivity == 'last_expr': |
|
2907 | if interactivity == 'last_expr': | |
2903 | if isinstance(nodelist[-1], ast.Expr): |
|
2908 | if isinstance(nodelist[-1], ast.Expr): | |
2904 | interactivity = "last" |
|
2909 | interactivity = "last" | |
2905 | else: |
|
2910 | else: | |
2906 | interactivity = "none" |
|
2911 | interactivity = "none" | |
2907 |
|
2912 | |||
2908 | if interactivity == 'none': |
|
2913 | if interactivity == 'none': | |
2909 | to_run_exec, to_run_interactive = nodelist, [] |
|
2914 | to_run_exec, to_run_interactive = nodelist, [] | |
2910 | elif interactivity == 'last': |
|
2915 | elif interactivity == 'last': | |
2911 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] |
|
2916 | to_run_exec, to_run_interactive = nodelist[:-1], nodelist[-1:] | |
2912 | elif interactivity == 'all': |
|
2917 | elif interactivity == 'all': | |
2913 | to_run_exec, to_run_interactive = [], nodelist |
|
2918 | to_run_exec, to_run_interactive = [], nodelist | |
2914 | else: |
|
2919 | else: | |
2915 | raise ValueError("Interactivity was %r" % interactivity) |
|
2920 | raise ValueError("Interactivity was %r" % interactivity) | |
2916 | try: |
|
2921 | try: | |
2917 | for i, node in enumerate(to_run_exec): |
|
2922 | for i, node in enumerate(to_run_exec): | |
2918 | mod = ast.Module([node]) |
|
2923 | mod = ast.Module([node]) | |
2919 | code = compiler(mod, cell_name, "exec") |
|
2924 | code = compiler(mod, cell_name, "exec") | |
2920 | if self.run_code(code, result): |
|
2925 | if self.run_code(code, result): | |
2921 | return True |
|
2926 | return True | |
2922 |
|
2927 | |||
2923 | for i, node in enumerate(to_run_interactive): |
|
2928 | for i, node in enumerate(to_run_interactive): | |
2924 | mod = ast.Interactive([node]) |
|
2929 | mod = ast.Interactive([node]) | |
2925 | code = compiler(mod, cell_name, "single") |
|
2930 | code = compiler(mod, cell_name, "single") | |
2926 | if self.run_code(code, result): |
|
2931 | if self.run_code(code, result): | |
2927 | return True |
|
2932 | return True | |
2928 |
|
2933 | |||
2929 | # Flush softspace |
|
2934 | # Flush softspace | |
2930 | if softspace(sys.stdout, 0): |
|
2935 | if softspace(sys.stdout, 0): | |
2931 | print() |
|
2936 | print() | |
2932 |
|
2937 | |||
2933 | except: |
|
2938 | except: | |
2934 | # It's possible to have exceptions raised here, typically by |
|
2939 | # It's possible to have exceptions raised here, typically by | |
2935 | # compilation of odd code (such as a naked 'return' outside a |
|
2940 | # compilation of odd code (such as a naked 'return' outside a | |
2936 | # function) that did parse but isn't valid. Typically the exception |
|
2941 | # function) that did parse but isn't valid. Typically the exception | |
2937 | # is a SyntaxError, but it's safest just to catch anything and show |
|
2942 | # is a SyntaxError, but it's safest just to catch anything and show | |
2938 | # the user a traceback. |
|
2943 | # the user a traceback. | |
2939 |
|
2944 | |||
2940 | # We do only one try/except outside the loop to minimize the impact |
|
2945 | # We do only one try/except outside the loop to minimize the impact | |
2941 | # on runtime, and also because if any node in the node list is |
|
2946 | # on runtime, and also because if any node in the node list is | |
2942 | # broken, we should stop execution completely. |
|
2947 | # broken, we should stop execution completely. | |
2943 | if result: |
|
2948 | if result: | |
2944 | result.error_before_exec = sys.exc_info()[1] |
|
2949 | result.error_before_exec = sys.exc_info()[1] | |
2945 | self.showtraceback() |
|
2950 | self.showtraceback() | |
2946 | return True |
|
2951 | return True | |
2947 |
|
2952 | |||
2948 | return False |
|
2953 | return False | |
2949 |
|
2954 | |||
2950 | def run_code(self, code_obj, result=None): |
|
2955 | def run_code(self, code_obj, result=None): | |
2951 | """Execute a code object. |
|
2956 | """Execute a code object. | |
2952 |
|
2957 | |||
2953 | When an exception occurs, self.showtraceback() is called to display a |
|
2958 | When an exception occurs, self.showtraceback() is called to display a | |
2954 | traceback. |
|
2959 | traceback. | |
2955 |
|
2960 | |||
2956 | Parameters |
|
2961 | Parameters | |
2957 | ---------- |
|
2962 | ---------- | |
2958 | code_obj : code object |
|
2963 | code_obj : code object | |
2959 | A compiled code object, to be executed |
|
2964 | A compiled code object, to be executed | |
2960 | result : ExecutionResult, optional |
|
2965 | result : ExecutionResult, optional | |
2961 | An object to store exceptions that occur during execution. |
|
2966 | An object to store exceptions that occur during execution. | |
2962 |
|
2967 | |||
2963 | Returns |
|
2968 | Returns | |
2964 | ------- |
|
2969 | ------- | |
2965 | False : successful execution. |
|
2970 | False : successful execution. | |
2966 | True : an error occurred. |
|
2971 | True : an error occurred. | |
2967 | """ |
|
2972 | """ | |
2968 | # Set our own excepthook in case the user code tries to call it |
|
2973 | # Set our own excepthook in case the user code tries to call it | |
2969 | # directly, so that the IPython crash handler doesn't get triggered |
|
2974 | # directly, so that the IPython crash handler doesn't get triggered | |
2970 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook |
|
2975 | old_excepthook, sys.excepthook = sys.excepthook, self.excepthook | |
2971 |
|
2976 | |||
2972 | # we save the original sys.excepthook in the instance, in case config |
|
2977 | # we save the original sys.excepthook in the instance, in case config | |
2973 | # code (such as magics) needs access to it. |
|
2978 | # code (such as magics) needs access to it. | |
2974 | self.sys_excepthook = old_excepthook |
|
2979 | self.sys_excepthook = old_excepthook | |
2975 | outflag = True # happens in more places, so it's easier as default |
|
2980 | outflag = True # happens in more places, so it's easier as default | |
2976 | try: |
|
2981 | try: | |
2977 | try: |
|
2982 | try: | |
2978 | self.hooks.pre_run_code_hook() |
|
2983 | self.hooks.pre_run_code_hook() | |
2979 | #rprint('Running code', repr(code_obj)) # dbg |
|
2984 | #rprint('Running code', repr(code_obj)) # dbg | |
2980 | exec(code_obj, self.user_global_ns, self.user_ns) |
|
2985 | exec(code_obj, self.user_global_ns, self.user_ns) | |
2981 | finally: |
|
2986 | finally: | |
2982 | # Reset our crash handler in place |
|
2987 | # Reset our crash handler in place | |
2983 | sys.excepthook = old_excepthook |
|
2988 | sys.excepthook = old_excepthook | |
2984 | except SystemExit as e: |
|
2989 | except SystemExit as e: | |
2985 | if result is not None: |
|
2990 | if result is not None: | |
2986 | result.error_in_exec = e |
|
2991 | result.error_in_exec = e | |
2987 | self.showtraceback(exception_only=True) |
|
2992 | self.showtraceback(exception_only=True) | |
2988 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) |
|
2993 | warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1) | |
2989 | except self.custom_exceptions: |
|
2994 | except self.custom_exceptions: | |
2990 | etype, value, tb = sys.exc_info() |
|
2995 | etype, value, tb = sys.exc_info() | |
2991 | if result is not None: |
|
2996 | if result is not None: | |
2992 | result.error_in_exec = value |
|
2997 | result.error_in_exec = value | |
2993 | self.CustomTB(etype, value, tb) |
|
2998 | self.CustomTB(etype, value, tb) | |
2994 | except: |
|
2999 | except: | |
2995 | if result is not None: |
|
3000 | if result is not None: | |
2996 | result.error_in_exec = sys.exc_info()[1] |
|
3001 | result.error_in_exec = sys.exc_info()[1] | |
2997 | self.showtraceback(running_compiled_code=True) |
|
3002 | self.showtraceback(running_compiled_code=True) | |
2998 | else: |
|
3003 | else: | |
2999 | outflag = False |
|
3004 | outflag = False | |
3000 | return outflag |
|
3005 | return outflag | |
3001 |
|
3006 | |||
3002 | # For backwards compatibility |
|
3007 | # For backwards compatibility | |
3003 | runcode = run_code |
|
3008 | runcode = run_code | |
3004 |
|
3009 | |||
3005 | def check_complete(self, code): |
|
3010 | def check_complete(self, code): | |
3006 | """Return whether a block of code is ready to execute, or should be continued |
|
3011 | """Return whether a block of code is ready to execute, or should be continued | |
3007 |
|
3012 | |||
3008 | Parameters |
|
3013 | Parameters | |
3009 | ---------- |
|
3014 | ---------- | |
3010 | source : string |
|
3015 | source : string | |
3011 | Python input code, which can be multiline. |
|
3016 | Python input code, which can be multiline. | |
3012 |
|
3017 | |||
3013 | Returns |
|
3018 | Returns | |
3014 | ------- |
|
3019 | ------- | |
3015 | status : str |
|
3020 | status : str | |
3016 | One of 'complete', 'incomplete', or 'invalid' if source is not a |
|
3021 | One of 'complete', 'incomplete', or 'invalid' if source is not a | |
3017 | prefix of valid code. |
|
3022 | prefix of valid code. | |
3018 | indent : str |
|
3023 | indent : str | |
3019 | When status is 'incomplete', this is some whitespace to insert on |
|
3024 | When status is 'incomplete', this is some whitespace to insert on | |
3020 | the next line of the prompt. |
|
3025 | the next line of the prompt. | |
3021 | """ |
|
3026 | """ | |
3022 | status, nspaces = self.input_transformer_manager.check_complete(code) |
|
3027 | status, nspaces = self.input_transformer_manager.check_complete(code) | |
3023 | return status, ' ' * (nspaces or 0) |
|
3028 | return status, ' ' * (nspaces or 0) | |
3024 |
|
3029 | |||
3025 | #------------------------------------------------------------------------- |
|
3030 | #------------------------------------------------------------------------- | |
3026 | # Things related to GUI support and pylab |
|
3031 | # Things related to GUI support and pylab | |
3027 | #------------------------------------------------------------------------- |
|
3032 | #------------------------------------------------------------------------- | |
3028 |
|
3033 | |||
3029 | active_eventloop = None |
|
3034 | active_eventloop = None | |
3030 |
|
3035 | |||
3031 | def enable_gui(self, gui=None): |
|
3036 | def enable_gui(self, gui=None): | |
3032 | raise NotImplementedError('Implement enable_gui in a subclass') |
|
3037 | raise NotImplementedError('Implement enable_gui in a subclass') | |
3033 |
|
3038 | |||
3034 | def enable_matplotlib(self, gui=None): |
|
3039 | def enable_matplotlib(self, gui=None): | |
3035 | """Enable interactive matplotlib and inline figure support. |
|
3040 | """Enable interactive matplotlib and inline figure support. | |
3036 |
|
3041 | |||
3037 | This takes the following steps: |
|
3042 | This takes the following steps: | |
3038 |
|
3043 | |||
3039 | 1. select the appropriate eventloop and matplotlib backend |
|
3044 | 1. select the appropriate eventloop and matplotlib backend | |
3040 | 2. set up matplotlib for interactive use with that backend |
|
3045 | 2. set up matplotlib for interactive use with that backend | |
3041 | 3. configure formatters for inline figure display |
|
3046 | 3. configure formatters for inline figure display | |
3042 | 4. enable the selected gui eventloop |
|
3047 | 4. enable the selected gui eventloop | |
3043 |
|
3048 | |||
3044 | Parameters |
|
3049 | Parameters | |
3045 | ---------- |
|
3050 | ---------- | |
3046 | gui : optional, string |
|
3051 | gui : optional, string | |
3047 | If given, dictates the choice of matplotlib GUI backend to use |
|
3052 | If given, dictates the choice of matplotlib GUI backend to use | |
3048 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
3053 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', | |
3049 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
3054 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by | |
3050 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
3055 | matplotlib (as dictated by the matplotlib build-time options plus the | |
3051 | user's matplotlibrc configuration file). Note that not all backends |
|
3056 | user's matplotlibrc configuration file). Note that not all backends | |
3052 | make sense in all contexts, for example a terminal ipython can't |
|
3057 | make sense in all contexts, for example a terminal ipython can't | |
3053 | display figures inline. |
|
3058 | display figures inline. | |
3054 | """ |
|
3059 | """ | |
3055 | from IPython.core import pylabtools as pt |
|
3060 | from IPython.core import pylabtools as pt | |
3056 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) |
|
3061 | gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select) | |
3057 |
|
3062 | |||
3058 | if gui != 'inline': |
|
3063 | if gui != 'inline': | |
3059 | # If we have our first gui selection, store it |
|
3064 | # If we have our first gui selection, store it | |
3060 | if self.pylab_gui_select is None: |
|
3065 | if self.pylab_gui_select is None: | |
3061 | self.pylab_gui_select = gui |
|
3066 | self.pylab_gui_select = gui | |
3062 | # Otherwise if they are different |
|
3067 | # Otherwise if they are different | |
3063 | elif gui != self.pylab_gui_select: |
|
3068 | elif gui != self.pylab_gui_select: | |
3064 | print('Warning: Cannot change to a different GUI toolkit: %s.' |
|
3069 | print('Warning: Cannot change to a different GUI toolkit: %s.' | |
3065 | ' Using %s instead.' % (gui, self.pylab_gui_select)) |
|
3070 | ' Using %s instead.' % (gui, self.pylab_gui_select)) | |
3066 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) |
|
3071 | gui, backend = pt.find_gui_and_backend(self.pylab_gui_select) | |
3067 |
|
3072 | |||
3068 | pt.activate_matplotlib(backend) |
|
3073 | pt.activate_matplotlib(backend) | |
3069 | pt.configure_inline_support(self, backend) |
|
3074 | pt.configure_inline_support(self, backend) | |
3070 |
|
3075 | |||
3071 | # Now we must activate the gui pylab wants to use, and fix %run to take |
|
3076 | # Now we must activate the gui pylab wants to use, and fix %run to take | |
3072 | # plot updates into account |
|
3077 | # plot updates into account | |
3073 | self.enable_gui(gui) |
|
3078 | self.enable_gui(gui) | |
3074 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ |
|
3079 | self.magics_manager.registry['ExecutionMagics'].default_runner = \ | |
3075 | pt.mpl_runner(self.safe_execfile) |
|
3080 | pt.mpl_runner(self.safe_execfile) | |
3076 |
|
3081 | |||
3077 | return gui, backend |
|
3082 | return gui, backend | |
3078 |
|
3083 | |||
3079 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): |
|
3084 | def enable_pylab(self, gui=None, import_all=True, welcome_message=False): | |
3080 | """Activate pylab support at runtime. |
|
3085 | """Activate pylab support at runtime. | |
3081 |
|
3086 | |||
3082 | This turns on support for matplotlib, preloads into the interactive |
|
3087 | This turns on support for matplotlib, preloads into the interactive | |
3083 | namespace all of numpy and pylab, and configures IPython to correctly |
|
3088 | namespace all of numpy and pylab, and configures IPython to correctly | |
3084 | interact with the GUI event loop. The GUI backend to be used can be |
|
3089 | interact with the GUI event loop. The GUI backend to be used can be | |
3085 | optionally selected with the optional ``gui`` argument. |
|
3090 | optionally selected with the optional ``gui`` argument. | |
3086 |
|
3091 | |||
3087 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. |
|
3092 | This method only adds preloading the namespace to InteractiveShell.enable_matplotlib. | |
3088 |
|
3093 | |||
3089 | Parameters |
|
3094 | Parameters | |
3090 | ---------- |
|
3095 | ---------- | |
3091 | gui : optional, string |
|
3096 | gui : optional, string | |
3092 | If given, dictates the choice of matplotlib GUI backend to use |
|
3097 | If given, dictates the choice of matplotlib GUI backend to use | |
3093 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', |
|
3098 | (should be one of IPython's supported backends, 'qt', 'osx', 'tk', | |
3094 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by |
|
3099 | 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by | |
3095 | matplotlib (as dictated by the matplotlib build-time options plus the |
|
3100 | matplotlib (as dictated by the matplotlib build-time options plus the | |
3096 | user's matplotlibrc configuration file). Note that not all backends |
|
3101 | user's matplotlibrc configuration file). Note that not all backends | |
3097 | make sense in all contexts, for example a terminal ipython can't |
|
3102 | make sense in all contexts, for example a terminal ipython can't | |
3098 | display figures inline. |
|
3103 | display figures inline. | |
3099 | import_all : optional, bool, default: True |
|
3104 | import_all : optional, bool, default: True | |
3100 | Whether to do `from numpy import *` and `from pylab import *` |
|
3105 | Whether to do `from numpy import *` and `from pylab import *` | |
3101 | in addition to module imports. |
|
3106 | in addition to module imports. | |
3102 | welcome_message : deprecated |
|
3107 | welcome_message : deprecated | |
3103 | This argument is ignored, no welcome message will be displayed. |
|
3108 | This argument is ignored, no welcome message will be displayed. | |
3104 | """ |
|
3109 | """ | |
3105 | from IPython.core.pylabtools import import_pylab |
|
3110 | from IPython.core.pylabtools import import_pylab | |
3106 |
|
3111 | |||
3107 | gui, backend = self.enable_matplotlib(gui) |
|
3112 | gui, backend = self.enable_matplotlib(gui) | |
3108 |
|
3113 | |||
3109 | # We want to prevent the loading of pylab to pollute the user's |
|
3114 | # We want to prevent the loading of pylab to pollute the user's | |
3110 | # namespace as shown by the %who* magics, so we execute the activation |
|
3115 | # namespace as shown by the %who* magics, so we execute the activation | |
3111 | # code in an empty namespace, and we update *both* user_ns and |
|
3116 | # code in an empty namespace, and we update *both* user_ns and | |
3112 | # user_ns_hidden with this information. |
|
3117 | # user_ns_hidden with this information. | |
3113 | ns = {} |
|
3118 | ns = {} | |
3114 | import_pylab(ns, import_all) |
|
3119 | import_pylab(ns, import_all) | |
3115 | # warn about clobbered names |
|
3120 | # warn about clobbered names | |
3116 | ignored = {"__builtins__"} |
|
3121 | ignored = {"__builtins__"} | |
3117 | both = set(ns).intersection(self.user_ns).difference(ignored) |
|
3122 | both = set(ns).intersection(self.user_ns).difference(ignored) | |
3118 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] |
|
3123 | clobbered = [ name for name in both if self.user_ns[name] is not ns[name] ] | |
3119 | self.user_ns.update(ns) |
|
3124 | self.user_ns.update(ns) | |
3120 | self.user_ns_hidden.update(ns) |
|
3125 | self.user_ns_hidden.update(ns) | |
3121 | return gui, backend, clobbered |
|
3126 | return gui, backend, clobbered | |
3122 |
|
3127 | |||
3123 | #------------------------------------------------------------------------- |
|
3128 | #------------------------------------------------------------------------- | |
3124 | # Utilities |
|
3129 | # Utilities | |
3125 | #------------------------------------------------------------------------- |
|
3130 | #------------------------------------------------------------------------- | |
3126 |
|
3131 | |||
3127 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): |
|
3132 | def var_expand(self, cmd, depth=0, formatter=DollarFormatter()): | |
3128 | """Expand python variables in a string. |
|
3133 | """Expand python variables in a string. | |
3129 |
|
3134 | |||
3130 | The depth argument indicates how many frames above the caller should |
|
3135 | The depth argument indicates how many frames above the caller should | |
3131 | be walked to look for the local namespace where to expand variables. |
|
3136 | be walked to look for the local namespace where to expand variables. | |
3132 |
|
3137 | |||
3133 | The global namespace for expansion is always the user's interactive |
|
3138 | The global namespace for expansion is always the user's interactive | |
3134 | namespace. |
|
3139 | namespace. | |
3135 | """ |
|
3140 | """ | |
3136 | ns = self.user_ns.copy() |
|
3141 | ns = self.user_ns.copy() | |
3137 | try: |
|
3142 | try: | |
3138 | frame = sys._getframe(depth+1) |
|
3143 | frame = sys._getframe(depth+1) | |
3139 | except ValueError: |
|
3144 | except ValueError: | |
3140 | # This is thrown if there aren't that many frames on the stack, |
|
3145 | # This is thrown if there aren't that many frames on the stack, | |
3141 | # e.g. if a script called run_line_magic() directly. |
|
3146 | # e.g. if a script called run_line_magic() directly. | |
3142 | pass |
|
3147 | pass | |
3143 | else: |
|
3148 | else: | |
3144 | ns.update(frame.f_locals) |
|
3149 | ns.update(frame.f_locals) | |
3145 |
|
3150 | |||
3146 | try: |
|
3151 | try: | |
3147 | # We have to use .vformat() here, because 'self' is a valid and common |
|
3152 | # We have to use .vformat() here, because 'self' is a valid and common | |
3148 | # name, and expanding **ns for .format() would make it collide with |
|
3153 | # name, and expanding **ns for .format() would make it collide with | |
3149 | # the 'self' argument of the method. |
|
3154 | # the 'self' argument of the method. | |
3150 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) |
|
3155 | cmd = formatter.vformat(cmd, args=[], kwargs=ns) | |
3151 | except Exception: |
|
3156 | except Exception: | |
3152 | # if formatter couldn't format, just let it go untransformed |
|
3157 | # if formatter couldn't format, just let it go untransformed | |
3153 | pass |
|
3158 | pass | |
3154 | return cmd |
|
3159 | return cmd | |
3155 |
|
3160 | |||
3156 | def mktempfile(self, data=None, prefix='ipython_edit_'): |
|
3161 | def mktempfile(self, data=None, prefix='ipython_edit_'): | |
3157 | """Make a new tempfile and return its filename. |
|
3162 | """Make a new tempfile and return its filename. | |
3158 |
|
3163 | |||
3159 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), |
|
3164 | This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp), | |
3160 | but it registers the created filename internally so ipython cleans it up |
|
3165 | but it registers the created filename internally so ipython cleans it up | |
3161 | at exit time. |
|
3166 | at exit time. | |
3162 |
|
3167 | |||
3163 | Optional inputs: |
|
3168 | Optional inputs: | |
3164 |
|
3169 | |||
3165 | - data(None): if data is given, it gets written out to the temp file |
|
3170 | - data(None): if data is given, it gets written out to the temp file | |
3166 | immediately, and the file is closed again.""" |
|
3171 | immediately, and the file is closed again.""" | |
3167 |
|
3172 | |||
3168 | dirname = tempfile.mkdtemp(prefix=prefix) |
|
3173 | dirname = tempfile.mkdtemp(prefix=prefix) | |
3169 | self.tempdirs.append(dirname) |
|
3174 | self.tempdirs.append(dirname) | |
3170 |
|
3175 | |||
3171 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) |
|
3176 | handle, filename = tempfile.mkstemp('.py', prefix, dir=dirname) | |
3172 | os.close(handle) # On Windows, there can only be one open handle on a file |
|
3177 | os.close(handle) # On Windows, there can only be one open handle on a file | |
3173 | self.tempfiles.append(filename) |
|
3178 | self.tempfiles.append(filename) | |
3174 |
|
3179 | |||
3175 | if data: |
|
3180 | if data: | |
3176 | tmp_file = open(filename,'w') |
|
3181 | tmp_file = open(filename,'w') | |
3177 | tmp_file.write(data) |
|
3182 | tmp_file.write(data) | |
3178 | tmp_file.close() |
|
3183 | tmp_file.close() | |
3179 | return filename |
|
3184 | return filename | |
3180 |
|
3185 | |||
3181 | @undoc |
|
3186 | @undoc | |
3182 | def write(self,data): |
|
3187 | def write(self,data): | |
3183 | """DEPRECATED: Write a string to the default output""" |
|
3188 | """DEPRECATED: Write a string to the default output""" | |
3184 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', |
|
3189 | warn('InteractiveShell.write() is deprecated, use sys.stdout instead', | |
3185 | DeprecationWarning, stacklevel=2) |
|
3190 | DeprecationWarning, stacklevel=2) | |
3186 | sys.stdout.write(data) |
|
3191 | sys.stdout.write(data) | |
3187 |
|
3192 | |||
3188 | @undoc |
|
3193 | @undoc | |
3189 | def write_err(self,data): |
|
3194 | def write_err(self,data): | |
3190 | """DEPRECATED: Write a string to the default error output""" |
|
3195 | """DEPRECATED: Write a string to the default error output""" | |
3191 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', |
|
3196 | warn('InteractiveShell.write_err() is deprecated, use sys.stderr instead', | |
3192 | DeprecationWarning, stacklevel=2) |
|
3197 | DeprecationWarning, stacklevel=2) | |
3193 | sys.stderr.write(data) |
|
3198 | sys.stderr.write(data) | |
3194 |
|
3199 | |||
3195 | def ask_yes_no(self, prompt, default=None, interrupt=None): |
|
3200 | def ask_yes_no(self, prompt, default=None, interrupt=None): | |
3196 | if self.quiet: |
|
3201 | if self.quiet: | |
3197 | return True |
|
3202 | return True | |
3198 | return ask_yes_no(prompt,default,interrupt) |
|
3203 | return ask_yes_no(prompt,default,interrupt) | |
3199 |
|
3204 | |||
3200 | def show_usage(self): |
|
3205 | def show_usage(self): | |
3201 | """Show a usage message""" |
|
3206 | """Show a usage message""" | |
3202 | page.page(IPython.core.usage.interactive_usage) |
|
3207 | page.page(IPython.core.usage.interactive_usage) | |
3203 |
|
3208 | |||
3204 | def extract_input_lines(self, range_str, raw=False): |
|
3209 | def extract_input_lines(self, range_str, raw=False): | |
3205 | """Return as a string a set of input history slices. |
|
3210 | """Return as a string a set of input history slices. | |
3206 |
|
3211 | |||
3207 | Parameters |
|
3212 | Parameters | |
3208 | ---------- |
|
3213 | ---------- | |
3209 | range_str : string |
|
3214 | range_str : string | |
3210 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", |
|
3215 | The set of slices is given as a string, like "~5/6-~4/2 4:8 9", | |
3211 | since this function is for use by magic functions which get their |
|
3216 | since this function is for use by magic functions which get their | |
3212 | arguments as strings. The number before the / is the session |
|
3217 | arguments as strings. The number before the / is the session | |
3213 | number: ~n goes n back from the current session. |
|
3218 | number: ~n goes n back from the current session. | |
3214 |
|
3219 | |||
3215 | raw : bool, optional |
|
3220 | raw : bool, optional | |
3216 | By default, the processed input is used. If this is true, the raw |
|
3221 | By default, the processed input is used. If this is true, the raw | |
3217 | input history is used instead. |
|
3222 | input history is used instead. | |
3218 |
|
3223 | |||
3219 | Notes |
|
3224 | Notes | |
3220 | ----- |
|
3225 | ----- | |
3221 |
|
3226 | |||
3222 | Slices can be described with two notations: |
|
3227 | Slices can be described with two notations: | |
3223 |
|
3228 | |||
3224 | * ``N:M`` -> standard python form, means including items N...(M-1). |
|
3229 | * ``N:M`` -> standard python form, means including items N...(M-1). | |
3225 | * ``N-M`` -> include items N..M (closed endpoint). |
|
3230 | * ``N-M`` -> include items N..M (closed endpoint). | |
3226 | """ |
|
3231 | """ | |
3227 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) |
|
3232 | lines = self.history_manager.get_range_by_str(range_str, raw=raw) | |
3228 | return "\n".join(x for _, _, x in lines) |
|
3233 | return "\n".join(x for _, _, x in lines) | |
3229 |
|
3234 | |||
3230 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): |
|
3235 | def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False): | |
3231 | """Get a code string from history, file, url, or a string or macro. |
|
3236 | """Get a code string from history, file, url, or a string or macro. | |
3232 |
|
3237 | |||
3233 | This is mainly used by magic functions. |
|
3238 | This is mainly used by magic functions. | |
3234 |
|
3239 | |||
3235 | Parameters |
|
3240 | Parameters | |
3236 | ---------- |
|
3241 | ---------- | |
3237 |
|
3242 | |||
3238 | target : str |
|
3243 | target : str | |
3239 |
|
3244 | |||
3240 | A string specifying code to retrieve. This will be tried respectively |
|
3245 | A string specifying code to retrieve. This will be tried respectively | |
3241 | as: ranges of input history (see %history for syntax), url, |
|
3246 | as: ranges of input history (see %history for syntax), url, | |
3242 | corresponding .py file, filename, or an expression evaluating to a |
|
3247 | corresponding .py file, filename, or an expression evaluating to a | |
3243 | string or Macro in the user namespace. |
|
3248 | string or Macro in the user namespace. | |
3244 |
|
3249 | |||
3245 | raw : bool |
|
3250 | raw : bool | |
3246 | If true (default), retrieve raw history. Has no effect on the other |
|
3251 | If true (default), retrieve raw history. Has no effect on the other | |
3247 | retrieval mechanisms. |
|
3252 | retrieval mechanisms. | |
3248 |
|
3253 | |||
3249 | py_only : bool (default False) |
|
3254 | py_only : bool (default False) | |
3250 | Only try to fetch python code, do not try alternative methods to decode file |
|
3255 | Only try to fetch python code, do not try alternative methods to decode file | |
3251 | if unicode fails. |
|
3256 | if unicode fails. | |
3252 |
|
3257 | |||
3253 | Returns |
|
3258 | Returns | |
3254 | ------- |
|
3259 | ------- | |
3255 | A string of code. |
|
3260 | A string of code. | |
3256 |
|
3261 | |||
3257 | ValueError is raised if nothing is found, and TypeError if it evaluates |
|
3262 | ValueError is raised if nothing is found, and TypeError if it evaluates | |
3258 | to an object of another type. In each case, .args[0] is a printable |
|
3263 | to an object of another type. In each case, .args[0] is a printable | |
3259 | message. |
|
3264 | message. | |
3260 | """ |
|
3265 | """ | |
3261 | code = self.extract_input_lines(target, raw=raw) # Grab history |
|
3266 | code = self.extract_input_lines(target, raw=raw) # Grab history | |
3262 | if code: |
|
3267 | if code: | |
3263 | return code |
|
3268 | return code | |
3264 | try: |
|
3269 | try: | |
3265 | if target.startswith(('http://', 'https://')): |
|
3270 | if target.startswith(('http://', 'https://')): | |
3266 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) |
|
3271 | return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie) | |
3267 | except UnicodeDecodeError: |
|
3272 | except UnicodeDecodeError: | |
3268 | if not py_only : |
|
3273 | if not py_only : | |
3269 | # Deferred import |
|
3274 | # Deferred import | |
3270 | from urllib.request import urlopen |
|
3275 | from urllib.request import urlopen | |
3271 | response = urlopen(target) |
|
3276 | response = urlopen(target) | |
3272 | return response.read().decode('latin1') |
|
3277 | return response.read().decode('latin1') | |
3273 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3278 | raise ValueError(("'%s' seem to be unreadable.") % target) | |
3274 |
|
3279 | |||
3275 | potential_target = [target] |
|
3280 | potential_target = [target] | |
3276 | try : |
|
3281 | try : | |
3277 | potential_target.insert(0,get_py_filename(target)) |
|
3282 | potential_target.insert(0,get_py_filename(target)) | |
3278 | except IOError: |
|
3283 | except IOError: | |
3279 | pass |
|
3284 | pass | |
3280 |
|
3285 | |||
3281 | for tgt in potential_target : |
|
3286 | for tgt in potential_target : | |
3282 | if os.path.isfile(tgt): # Read file |
|
3287 | if os.path.isfile(tgt): # Read file | |
3283 | try : |
|
3288 | try : | |
3284 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) |
|
3289 | return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie) | |
3285 | except UnicodeDecodeError : |
|
3290 | except UnicodeDecodeError : | |
3286 | if not py_only : |
|
3291 | if not py_only : | |
3287 | with io_open(tgt,'r', encoding='latin1') as f : |
|
3292 | with io_open(tgt,'r', encoding='latin1') as f : | |
3288 | return f.read() |
|
3293 | return f.read() | |
3289 | raise ValueError(("'%s' seem to be unreadable.") % target) |
|
3294 | raise ValueError(("'%s' seem to be unreadable.") % target) | |
3290 | elif os.path.isdir(os.path.expanduser(tgt)): |
|
3295 | elif os.path.isdir(os.path.expanduser(tgt)): | |
3291 | raise ValueError("'%s' is a directory, not a regular file." % target) |
|
3296 | raise ValueError("'%s' is a directory, not a regular file." % target) | |
3292 |
|
3297 | |||
3293 | if search_ns: |
|
3298 | if search_ns: | |
3294 | # Inspect namespace to load object source |
|
3299 | # Inspect namespace to load object source | |
3295 | object_info = self.object_inspect(target, detail_level=1) |
|
3300 | object_info = self.object_inspect(target, detail_level=1) | |
3296 | if object_info['found'] and object_info['source']: |
|
3301 | if object_info['found'] and object_info['source']: | |
3297 | return object_info['source'] |
|
3302 | return object_info['source'] | |
3298 |
|
3303 | |||
3299 | try: # User namespace |
|
3304 | try: # User namespace | |
3300 | codeobj = eval(target, self.user_ns) |
|
3305 | codeobj = eval(target, self.user_ns) | |
3301 | except Exception: |
|
3306 | except Exception: | |
3302 | raise ValueError(("'%s' was not found in history, as a file, url, " |
|
3307 | raise ValueError(("'%s' was not found in history, as a file, url, " | |
3303 | "nor in the user namespace.") % target) |
|
3308 | "nor in the user namespace.") % target) | |
3304 |
|
3309 | |||
3305 | if isinstance(codeobj, str): |
|
3310 | if isinstance(codeobj, str): | |
3306 | return codeobj |
|
3311 | return codeobj | |
3307 | elif isinstance(codeobj, Macro): |
|
3312 | elif isinstance(codeobj, Macro): | |
3308 | return codeobj.value |
|
3313 | return codeobj.value | |
3309 |
|
3314 | |||
3310 | raise TypeError("%s is neither a string nor a macro." % target, |
|
3315 | raise TypeError("%s is neither a string nor a macro." % target, | |
3311 | codeobj) |
|
3316 | codeobj) | |
3312 |
|
3317 | |||
3313 | #------------------------------------------------------------------------- |
|
3318 | #------------------------------------------------------------------------- | |
3314 | # Things related to IPython exiting |
|
3319 | # Things related to IPython exiting | |
3315 | #------------------------------------------------------------------------- |
|
3320 | #------------------------------------------------------------------------- | |
3316 | def atexit_operations(self): |
|
3321 | def atexit_operations(self): | |
3317 | """This will be executed at the time of exit. |
|
3322 | """This will be executed at the time of exit. | |
3318 |
|
3323 | |||
3319 | Cleanup operations and saving of persistent data that is done |
|
3324 | Cleanup operations and saving of persistent data that is done | |
3320 | unconditionally by IPython should be performed here. |
|
3325 | unconditionally by IPython should be performed here. | |
3321 |
|
3326 | |||
3322 | For things that may depend on startup flags or platform specifics (such |
|
3327 | For things that may depend on startup flags or platform specifics (such | |
3323 | as having readline or not), register a separate atexit function in the |
|
3328 | as having readline or not), register a separate atexit function in the | |
3324 | code that has the appropriate information, rather than trying to |
|
3329 | code that has the appropriate information, rather than trying to | |
3325 | clutter |
|
3330 | clutter | |
3326 | """ |
|
3331 | """ | |
3327 | # Close the history session (this stores the end time and line count) |
|
3332 | # Close the history session (this stores the end time and line count) | |
3328 | # this must be *before* the tempfile cleanup, in case of temporary |
|
3333 | # this must be *before* the tempfile cleanup, in case of temporary | |
3329 | # history db |
|
3334 | # history db | |
3330 | self.history_manager.end_session() |
|
3335 | self.history_manager.end_session() | |
3331 |
|
3336 | |||
3332 | # Cleanup all tempfiles and folders left around |
|
3337 | # Cleanup all tempfiles and folders left around | |
3333 | for tfile in self.tempfiles: |
|
3338 | for tfile in self.tempfiles: | |
3334 | try: |
|
3339 | try: | |
3335 | os.unlink(tfile) |
|
3340 | os.unlink(tfile) | |
3336 | except OSError: |
|
3341 | except OSError: | |
3337 | pass |
|
3342 | pass | |
3338 |
|
3343 | |||
3339 | for tdir in self.tempdirs: |
|
3344 | for tdir in self.tempdirs: | |
3340 | try: |
|
3345 | try: | |
3341 | os.rmdir(tdir) |
|
3346 | os.rmdir(tdir) | |
3342 | except OSError: |
|
3347 | except OSError: | |
3343 | pass |
|
3348 | pass | |
3344 |
|
3349 | |||
3345 | # Clear all user namespaces to release all references cleanly. |
|
3350 | # Clear all user namespaces to release all references cleanly. | |
3346 | self.reset(new_session=False) |
|
3351 | self.reset(new_session=False) | |
3347 |
|
3352 | |||
3348 | # Run user hooks |
|
3353 | # Run user hooks | |
3349 | self.hooks.shutdown_hook() |
|
3354 | self.hooks.shutdown_hook() | |
3350 |
|
3355 | |||
3351 | def cleanup(self): |
|
3356 | def cleanup(self): | |
3352 | self.restore_sys_module_state() |
|
3357 | self.restore_sys_module_state() | |
3353 |
|
3358 | |||
3354 |
|
3359 | |||
3355 | # Overridden in terminal subclass to change prompts |
|
3360 | # Overridden in terminal subclass to change prompts | |
3356 | def switch_doctest_mode(self, mode): |
|
3361 | def switch_doctest_mode(self, mode): | |
3357 | pass |
|
3362 | pass | |
3358 |
|
3363 | |||
3359 |
|
3364 | |||
3360 | class InteractiveShellABC(metaclass=abc.ABCMeta): |
|
3365 | class InteractiveShellABC(metaclass=abc.ABCMeta): | |
3361 | """An abstract base class for InteractiveShell.""" |
|
3366 | """An abstract base class for InteractiveShell.""" | |
3362 |
|
3367 | |||
3363 | InteractiveShellABC.register(InteractiveShell) |
|
3368 | InteractiveShellABC.register(InteractiveShell) |
@@ -1,189 +1,195 b'' | |||||
|
1 | """Tests for the token-based transformers in IPython.core.inputtransformer2 | |||
|
2 | ||||
|
3 | Line-based transformers are the simpler ones; token-based transformers are | |||
|
4 | more complex. | |||
|
5 | """ | |||
|
6 | ||||
1 | import nose.tools as nt |
|
7 | import nose.tools as nt | |
2 |
|
8 | |||
3 | from IPython.core import inputtransformer2 as ipt2 |
|
9 | from IPython.core import inputtransformer2 as ipt2 | |
4 | from IPython.core.inputtransformer2 import make_tokens_by_line |
|
10 | from IPython.core.inputtransformer2 import make_tokens_by_line | |
5 |
|
11 | |||
6 | MULTILINE_MAGIC = ("""\ |
|
12 | MULTILINE_MAGIC = ("""\ | |
7 | a = f() |
|
13 | a = f() | |
8 | %foo \\ |
|
14 | %foo \\ | |
9 | bar |
|
15 | bar | |
10 | g() |
|
16 | g() | |
11 | """.splitlines(keepends=True), (2, 0), """\ |
|
17 | """.splitlines(keepends=True), (2, 0), """\ | |
12 | a = f() |
|
18 | a = f() | |
13 | get_ipython().run_line_magic('foo', ' bar') |
|
19 | get_ipython().run_line_magic('foo', ' bar') | |
14 | g() |
|
20 | g() | |
15 | """.splitlines(keepends=True)) |
|
21 | """.splitlines(keepends=True)) | |
16 |
|
22 | |||
17 | INDENTED_MAGIC = ("""\ |
|
23 | INDENTED_MAGIC = ("""\ | |
18 | for a in range(5): |
|
24 | for a in range(5): | |
19 | %ls |
|
25 | %ls | |
20 | """.splitlines(keepends=True), (2, 4), """\ |
|
26 | """.splitlines(keepends=True), (2, 4), """\ | |
21 | for a in range(5): |
|
27 | for a in range(5): | |
22 | get_ipython().run_line_magic('ls', '') |
|
28 | get_ipython().run_line_magic('ls', '') | |
23 | """.splitlines(keepends=True)) |
|
29 | """.splitlines(keepends=True)) | |
24 |
|
30 | |||
25 | MULTILINE_MAGIC_ASSIGN = ("""\ |
|
31 | MULTILINE_MAGIC_ASSIGN = ("""\ | |
26 | a = f() |
|
32 | a = f() | |
27 | b = %foo \\ |
|
33 | b = %foo \\ | |
28 | bar |
|
34 | bar | |
29 | g() |
|
35 | g() | |
30 | """.splitlines(keepends=True), (2, 4), """\ |
|
36 | """.splitlines(keepends=True), (2, 4), """\ | |
31 | a = f() |
|
37 | a = f() | |
32 | b = get_ipython().run_line_magic('foo', ' bar') |
|
38 | b = get_ipython().run_line_magic('foo', ' bar') | |
33 | g() |
|
39 | g() | |
34 | """.splitlines(keepends=True)) |
|
40 | """.splitlines(keepends=True)) | |
35 |
|
41 | |||
36 | MULTILINE_SYSTEM_ASSIGN = ("""\ |
|
42 | MULTILINE_SYSTEM_ASSIGN = ("""\ | |
37 | a = f() |
|
43 | a = f() | |
38 | b = !foo \\ |
|
44 | b = !foo \\ | |
39 | bar |
|
45 | bar | |
40 | g() |
|
46 | g() | |
41 | """.splitlines(keepends=True), (2, 4), """\ |
|
47 | """.splitlines(keepends=True), (2, 4), """\ | |
42 | a = f() |
|
48 | a = f() | |
43 | b = get_ipython().getoutput('foo bar') |
|
49 | b = get_ipython().getoutput('foo bar') | |
44 | g() |
|
50 | g() | |
45 | """.splitlines(keepends=True)) |
|
51 | """.splitlines(keepends=True)) | |
46 |
|
52 | |||
47 | AUTOCALL_QUOTE = ( |
|
53 | AUTOCALL_QUOTE = ( | |
48 | [",f 1 2 3\n"], (1, 0), |
|
54 | [",f 1 2 3\n"], (1, 0), | |
49 | ['f("1", "2", "3")\n'] |
|
55 | ['f("1", "2", "3")\n'] | |
50 | ) |
|
56 | ) | |
51 |
|
57 | |||
52 | AUTOCALL_QUOTE2 = ( |
|
58 | AUTOCALL_QUOTE2 = ( | |
53 | [";f 1 2 3\n"], (1, 0), |
|
59 | [";f 1 2 3\n"], (1, 0), | |
54 | ['f("1 2 3")\n'] |
|
60 | ['f("1 2 3")\n'] | |
55 | ) |
|
61 | ) | |
56 |
|
62 | |||
57 | AUTOCALL_PAREN = ( |
|
63 | AUTOCALL_PAREN = ( | |
58 | ["/f 1 2 3\n"], (1, 0), |
|
64 | ["/f 1 2 3\n"], (1, 0), | |
59 | ['f(1, 2, 3)\n'] |
|
65 | ['f(1, 2, 3)\n'] | |
60 | ) |
|
66 | ) | |
61 |
|
67 | |||
62 | SIMPLE_HELP = ( |
|
68 | SIMPLE_HELP = ( | |
63 | ["foo?\n"], (1, 0), |
|
69 | ["foo?\n"], (1, 0), | |
64 | ["get_ipython().run_line_magic('pinfo', 'foo')\n"] |
|
70 | ["get_ipython().run_line_magic('pinfo', 'foo')\n"] | |
65 | ) |
|
71 | ) | |
66 |
|
72 | |||
67 | DETAILED_HELP = ( |
|
73 | DETAILED_HELP = ( | |
68 | ["foo??\n"], (1, 0), |
|
74 | ["foo??\n"], (1, 0), | |
69 | ["get_ipython().run_line_magic('pinfo2', 'foo')\n"] |
|
75 | ["get_ipython().run_line_magic('pinfo2', 'foo')\n"] | |
70 | ) |
|
76 | ) | |
71 |
|
77 | |||
72 | MAGIC_HELP = ( |
|
78 | MAGIC_HELP = ( | |
73 | ["%foo?\n"], (1, 0), |
|
79 | ["%foo?\n"], (1, 0), | |
74 | ["get_ipython().run_line_magic('pinfo', '%foo')\n"] |
|
80 | ["get_ipython().run_line_magic('pinfo', '%foo')\n"] | |
75 | ) |
|
81 | ) | |
76 |
|
82 | |||
77 | HELP_IN_EXPR = ( |
|
83 | HELP_IN_EXPR = ( | |
78 | ["a = b + c?\n"], (1, 0), |
|
84 | ["a = b + c?\n"], (1, 0), | |
79 | ["get_ipython().set_next_input('a = b + c');" |
|
85 | ["get_ipython().set_next_input('a = b + c');" | |
80 | "get_ipython().run_line_magic('pinfo', 'c')\n"] |
|
86 | "get_ipython().run_line_magic('pinfo', 'c')\n"] | |
81 | ) |
|
87 | ) | |
82 |
|
88 | |||
83 | HELP_CONTINUED_LINE = ("""\ |
|
89 | HELP_CONTINUED_LINE = ("""\ | |
84 | a = \\ |
|
90 | a = \\ | |
85 | zip? |
|
91 | zip? | |
86 | """.splitlines(keepends=True), (1, 0), |
|
92 | """.splitlines(keepends=True), (1, 0), | |
87 | [r"get_ipython().set_next_input('a = \\\nzip');get_ipython().run_line_magic('pinfo', 'zip')" + "\n"] |
|
93 | [r"get_ipython().set_next_input('a = \\\nzip');get_ipython().run_line_magic('pinfo', 'zip')" + "\n"] | |
88 | ) |
|
94 | ) | |
89 |
|
95 | |||
90 | HELP_MULTILINE = ("""\ |
|
96 | HELP_MULTILINE = ("""\ | |
91 | (a, |
|
97 | (a, | |
92 | b) = zip? |
|
98 | b) = zip? | |
93 | """.splitlines(keepends=True), (1, 0), |
|
99 | """.splitlines(keepends=True), (1, 0), | |
94 | [r"get_ipython().set_next_input('(a,\nb) = zip');get_ipython().run_line_magic('pinfo', 'zip')" + "\n"] |
|
100 | [r"get_ipython().set_next_input('(a,\nb) = zip');get_ipython().run_line_magic('pinfo', 'zip')" + "\n"] | |
95 | ) |
|
101 | ) | |
96 |
|
102 | |||
97 | def check_find(transformer, case, match=True): |
|
103 | def check_find(transformer, case, match=True): | |
98 | sample, expected_start, _ = case |
|
104 | sample, expected_start, _ = case | |
99 | tbl = make_tokens_by_line(sample) |
|
105 | tbl = make_tokens_by_line(sample) | |
100 | res = transformer.find(tbl) |
|
106 | res = transformer.find(tbl) | |
101 | if match: |
|
107 | if match: | |
102 | # start_line is stored 0-indexed, expected values are 1-indexed |
|
108 | # start_line is stored 0-indexed, expected values are 1-indexed | |
103 | nt.assert_equal((res.start_line+1, res.start_col), expected_start) |
|
109 | nt.assert_equal((res.start_line+1, res.start_col), expected_start) | |
104 | return res |
|
110 | return res | |
105 | else: |
|
111 | else: | |
106 | nt.assert_is(res, None) |
|
112 | nt.assert_is(res, None) | |
107 |
|
113 | |||
108 | def check_transform(transformer_cls, case): |
|
114 | def check_transform(transformer_cls, case): | |
109 | lines, start, expected = case |
|
115 | lines, start, expected = case | |
110 | transformer = transformer_cls(start) |
|
116 | transformer = transformer_cls(start) | |
111 | nt.assert_equal(transformer.transform(lines), expected) |
|
117 | nt.assert_equal(transformer.transform(lines), expected) | |
112 |
|
118 | |||
113 | def test_continued_line(): |
|
119 | def test_continued_line(): | |
114 | lines = MULTILINE_MAGIC_ASSIGN[0] |
|
120 | lines = MULTILINE_MAGIC_ASSIGN[0] | |
115 | nt.assert_equal(ipt2.find_end_of_continued_line(lines, 1), 2) |
|
121 | nt.assert_equal(ipt2.find_end_of_continued_line(lines, 1), 2) | |
116 |
|
122 | |||
117 | nt.assert_equal(ipt2.assemble_continued_line(lines, (1, 5), 2), "foo bar") |
|
123 | nt.assert_equal(ipt2.assemble_continued_line(lines, (1, 5), 2), "foo bar") | |
118 |
|
124 | |||
119 | def test_find_assign_magic(): |
|
125 | def test_find_assign_magic(): | |
120 | check_find(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN) |
|
126 | check_find(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN) | |
121 | check_find(ipt2.MagicAssign, MULTILINE_SYSTEM_ASSIGN, match=False) |
|
127 | check_find(ipt2.MagicAssign, MULTILINE_SYSTEM_ASSIGN, match=False) | |
122 |
|
128 | |||
123 | def test_transform_assign_magic(): |
|
129 | def test_transform_assign_magic(): | |
124 | check_transform(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN) |
|
130 | check_transform(ipt2.MagicAssign, MULTILINE_MAGIC_ASSIGN) | |
125 |
|
131 | |||
126 | def test_find_assign_system(): |
|
132 | def test_find_assign_system(): | |
127 | check_find(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN) |
|
133 | check_find(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN) | |
128 | check_find(ipt2.SystemAssign, (["a = !ls\n"], (1, 5), None)) |
|
134 | check_find(ipt2.SystemAssign, (["a = !ls\n"], (1, 5), None)) | |
129 | check_find(ipt2.SystemAssign, (["a=!ls\n"], (1, 2), None)) |
|
135 | check_find(ipt2.SystemAssign, (["a=!ls\n"], (1, 2), None)) | |
130 | check_find(ipt2.SystemAssign, MULTILINE_MAGIC_ASSIGN, match=False) |
|
136 | check_find(ipt2.SystemAssign, MULTILINE_MAGIC_ASSIGN, match=False) | |
131 |
|
137 | |||
132 | def test_transform_assign_system(): |
|
138 | def test_transform_assign_system(): | |
133 | check_transform(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN) |
|
139 | check_transform(ipt2.SystemAssign, MULTILINE_SYSTEM_ASSIGN) | |
134 |
|
140 | |||
135 | def test_find_magic_escape(): |
|
141 | def test_find_magic_escape(): | |
136 | check_find(ipt2.EscapedCommand, MULTILINE_MAGIC) |
|
142 | check_find(ipt2.EscapedCommand, MULTILINE_MAGIC) | |
137 | check_find(ipt2.EscapedCommand, INDENTED_MAGIC) |
|
143 | check_find(ipt2.EscapedCommand, INDENTED_MAGIC) | |
138 | check_find(ipt2.EscapedCommand, MULTILINE_MAGIC_ASSIGN, match=False) |
|
144 | check_find(ipt2.EscapedCommand, MULTILINE_MAGIC_ASSIGN, match=False) | |
139 |
|
145 | |||
140 | def test_transform_magic_escape(): |
|
146 | def test_transform_magic_escape(): | |
141 | check_transform(ipt2.EscapedCommand, MULTILINE_MAGIC) |
|
147 | check_transform(ipt2.EscapedCommand, MULTILINE_MAGIC) | |
142 | check_transform(ipt2.EscapedCommand, INDENTED_MAGIC) |
|
148 | check_transform(ipt2.EscapedCommand, INDENTED_MAGIC) | |
143 |
|
149 | |||
144 | def test_find_autocalls(): |
|
150 | def test_find_autocalls(): | |
145 | for case in [AUTOCALL_QUOTE, AUTOCALL_QUOTE2, AUTOCALL_PAREN]: |
|
151 | for case in [AUTOCALL_QUOTE, AUTOCALL_QUOTE2, AUTOCALL_PAREN]: | |
146 | print("Testing %r" % case[0]) |
|
152 | print("Testing %r" % case[0]) | |
147 | check_find(ipt2.EscapedCommand, case) |
|
153 | check_find(ipt2.EscapedCommand, case) | |
148 |
|
154 | |||
149 | def test_transform_autocall(): |
|
155 | def test_transform_autocall(): | |
150 | for case in [AUTOCALL_QUOTE, AUTOCALL_QUOTE2, AUTOCALL_PAREN]: |
|
156 | for case in [AUTOCALL_QUOTE, AUTOCALL_QUOTE2, AUTOCALL_PAREN]: | |
151 | print("Testing %r" % case[0]) |
|
157 | print("Testing %r" % case[0]) | |
152 | check_transform(ipt2.EscapedCommand, case) |
|
158 | check_transform(ipt2.EscapedCommand, case) | |
153 |
|
159 | |||
154 | def test_find_help(): |
|
160 | def test_find_help(): | |
155 | for case in [SIMPLE_HELP, DETAILED_HELP, MAGIC_HELP, HELP_IN_EXPR]: |
|
161 | for case in [SIMPLE_HELP, DETAILED_HELP, MAGIC_HELP, HELP_IN_EXPR]: | |
156 | check_find(ipt2.HelpEnd, case) |
|
162 | check_find(ipt2.HelpEnd, case) | |
157 |
|
163 | |||
158 | tf = check_find(ipt2.HelpEnd, HELP_CONTINUED_LINE) |
|
164 | tf = check_find(ipt2.HelpEnd, HELP_CONTINUED_LINE) | |
159 | nt.assert_equal(tf.q_line, 1) |
|
165 | nt.assert_equal(tf.q_line, 1) | |
160 | nt.assert_equal(tf.q_col, 3) |
|
166 | nt.assert_equal(tf.q_col, 3) | |
161 |
|
167 | |||
162 | tf = check_find(ipt2.HelpEnd, HELP_MULTILINE) |
|
168 | tf = check_find(ipt2.HelpEnd, HELP_MULTILINE) | |
163 | nt.assert_equal(tf.q_line, 1) |
|
169 | nt.assert_equal(tf.q_line, 1) | |
164 | nt.assert_equal(tf.q_col, 8) |
|
170 | nt.assert_equal(tf.q_col, 8) | |
165 |
|
171 | |||
166 | # ? in a comment does not trigger help |
|
172 | # ? in a comment does not trigger help | |
167 | check_find(ipt2.HelpEnd, (["foo # bar?\n"], None, None), match=False) |
|
173 | check_find(ipt2.HelpEnd, (["foo # bar?\n"], None, None), match=False) | |
168 | # Nor in a string |
|
174 | # Nor in a string | |
169 | check_find(ipt2.HelpEnd, (["foo = '''bar?\n"], None, None), match=False) |
|
175 | check_find(ipt2.HelpEnd, (["foo = '''bar?\n"], None, None), match=False) | |
170 |
|
176 | |||
171 | def test_transform_help(): |
|
177 | def test_transform_help(): | |
172 | tf = ipt2.HelpEnd((1, 0), (1, 9)) |
|
178 | tf = ipt2.HelpEnd((1, 0), (1, 9)) | |
173 | nt.assert_equal(tf.transform(HELP_IN_EXPR[0]), HELP_IN_EXPR[2]) |
|
179 | nt.assert_equal(tf.transform(HELP_IN_EXPR[0]), HELP_IN_EXPR[2]) | |
174 |
|
180 | |||
175 | tf = ipt2.HelpEnd((1, 0), (2, 3)) |
|
181 | tf = ipt2.HelpEnd((1, 0), (2, 3)) | |
176 | nt.assert_equal(tf.transform(HELP_CONTINUED_LINE[0]), HELP_CONTINUED_LINE[2]) |
|
182 | nt.assert_equal(tf.transform(HELP_CONTINUED_LINE[0]), HELP_CONTINUED_LINE[2]) | |
177 |
|
183 | |||
178 | tf = ipt2.HelpEnd((1, 0), (2, 8)) |
|
184 | tf = ipt2.HelpEnd((1, 0), (2, 8)) | |
179 | nt.assert_equal(tf.transform(HELP_MULTILINE[0]), HELP_MULTILINE[2]) |
|
185 | nt.assert_equal(tf.transform(HELP_MULTILINE[0]), HELP_MULTILINE[2]) | |
180 |
|
186 | |||
181 | def test_check_complete(): |
|
187 | def test_check_complete(): | |
182 | cc = ipt2.TransformerManager().check_complete |
|
188 | cc = ipt2.TransformerManager().check_complete | |
183 | nt.assert_equal(cc("a = 1"), ('complete', None)) |
|
189 | nt.assert_equal(cc("a = 1"), ('complete', None)) | |
184 | nt.assert_equal(cc("for a in range(5):"), ('incomplete', 4)) |
|
190 | nt.assert_equal(cc("for a in range(5):"), ('incomplete', 4)) | |
185 | nt.assert_equal(cc("raise = 2"), ('invalid', None)) |
|
191 | nt.assert_equal(cc("raise = 2"), ('invalid', None)) | |
186 | nt.assert_equal(cc("a = [1,\n2,"), ('incomplete', 0)) |
|
192 | nt.assert_equal(cc("a = [1,\n2,"), ('incomplete', 0)) | |
187 | nt.assert_equal(cc("a = '''\n hi"), ('incomplete', 3)) |
|
193 | nt.assert_equal(cc("a = '''\n hi"), ('incomplete', 3)) | |
188 | nt.assert_equal(cc("def a():\n x=1\n global x"), ('invalid', None)) |
|
194 | nt.assert_equal(cc("def a():\n x=1\n global x"), ('invalid', None)) | |
189 | nt.assert_equal(cc("a \\ "), ('invalid', None)) # Nothing allowed after backslash |
|
195 | nt.assert_equal(cc("a \\ "), ('invalid', None)) # Nothing allowed after backslash |
General Comments 0
You need to be logged in to leave comments.
Login now