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