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