##// END OF EJS Templates
Remove duplicate raw_input in TerminalInteractiveShell
Thomas Kluyver -
Show More
@@ -1,619 +1,558 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 27 from IPython.lib.inputhook import enable_gui
28 28 from IPython.lib.pylabtools import pylab_activate
29 29 from IPython.testing import decorators as testdec
30 30 from IPython.utils.terminal import toggle_set_term_title, set_term_title
31 31 from IPython.utils.process import abbrev_cwd
32 32 from IPython.utils.warn import warn
33 33 from IPython.utils.text import num_ini_spaces
34 34 from IPython.utils.traitlets import Int, Str, CBool
35 35
36 36 #-----------------------------------------------------------------------------
37 37 # Utilities
38 38 #-----------------------------------------------------------------------------
39 39
40 40 def get_default_editor():
41 41 try:
42 42 ed = os.environ['EDITOR']
43 43 except KeyError:
44 44 if os.name == 'posix':
45 45 ed = 'vi' # the only one guaranteed to be there!
46 46 else:
47 47 ed = 'notepad' # same in Windows!
48 48 return ed
49 49
50 50
51 51 # store the builtin raw_input globally, and use this always, in case user code
52 52 # overwrites it (like wx.py.PyShell does)
53 53 raw_input_original = raw_input
54 54
55 55 #-----------------------------------------------------------------------------
56 56 # Main class
57 57 #-----------------------------------------------------------------------------
58 58
59 59 class TerminalInteractiveShell(InteractiveShell):
60 60
61 61 autoedit_syntax = CBool(False, config=True)
62 62 banner = Str('')
63 63 banner1 = Str(default_banner, config=True)
64 64 banner2 = Str('', config=True)
65 65 confirm_exit = CBool(True, config=True)
66 66 # This display_banner only controls whether or not self.show_banner()
67 67 # is called when mainloop/interact are called. The default is False
68 68 # because for the terminal based application, the banner behavior
69 69 # is controlled by Global.display_banner, which IPythonApp looks at
70 70 # to determine if *it* should call show_banner() by hand or not.
71 71 display_banner = CBool(False) # This isn't configurable!
72 72 embedded = CBool(False)
73 73 embedded_active = CBool(False)
74 74 editor = Str(get_default_editor(), config=True)
75 75 pager = Str('less', config=True)
76 76
77 77 screen_length = Int(0, config=True)
78 78 term_title = CBool(False, config=True)
79 79
80 80 def __init__(self, config=None, ipython_dir=None, user_ns=None,
81 81 user_global_ns=None, custom_exceptions=((),None),
82 82 usage=None, banner1=None, banner2=None,
83 83 display_banner=None):
84 84
85 85 super(TerminalInteractiveShell, self).__init__(
86 86 config=config, ipython_dir=ipython_dir, user_ns=user_ns,
87 87 user_global_ns=user_global_ns, custom_exceptions=custom_exceptions
88 88 )
89 89 self.init_term_title()
90 90 self.init_usage(usage)
91 91 self.init_banner(banner1, banner2, display_banner)
92 92
93 93 #-------------------------------------------------------------------------
94 94 # Things related to the terminal
95 95 #-------------------------------------------------------------------------
96 96
97 97 @property
98 98 def usable_screen_length(self):
99 99 if self.screen_length == 0:
100 100 return 0
101 101 else:
102 102 num_lines_bot = self.separate_in.count('\n')+1
103 103 return self.screen_length - num_lines_bot
104 104
105 105 def init_term_title(self):
106 106 # Enable or disable the terminal title.
107 107 if self.term_title:
108 108 toggle_set_term_title(True)
109 109 set_term_title('IPython: ' + abbrev_cwd())
110 110 else:
111 111 toggle_set_term_title(False)
112 112
113 113 #-------------------------------------------------------------------------
114 114 # Things related to aliases
115 115 #-------------------------------------------------------------------------
116 116
117 117 def init_alias(self):
118 118 # The parent class defines aliases that can be safely used with any
119 119 # frontend.
120 120 super(TerminalInteractiveShell, self).init_alias()
121 121
122 122 # Now define aliases that only make sense on the terminal, because they
123 123 # need direct access to the console in a way that we can't emulate in
124 124 # GUI or web frontend
125 125 if os.name == 'posix':
126 126 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
127 127 ('man', 'man')]
128 128 elif os.name == 'nt':
129 129 aliases = [('cls', 'cls')]
130 130
131 131
132 132 for name, cmd in aliases:
133 133 self.alias_manager.define_alias(name, cmd)
134 134
135 135 #-------------------------------------------------------------------------
136 136 # Things related to the banner and usage
137 137 #-------------------------------------------------------------------------
138 138
139 139 def _banner1_changed(self):
140 140 self.compute_banner()
141 141
142 142 def _banner2_changed(self):
143 143 self.compute_banner()
144 144
145 145 def _term_title_changed(self, name, new_value):
146 146 self.init_term_title()
147 147
148 148 def init_banner(self, banner1, banner2, display_banner):
149 149 if banner1 is not None:
150 150 self.banner1 = banner1
151 151 if banner2 is not None:
152 152 self.banner2 = banner2
153 153 if display_banner is not None:
154 154 self.display_banner = display_banner
155 155 self.compute_banner()
156 156
157 157 def show_banner(self, banner=None):
158 158 if banner is None:
159 159 banner = self.banner
160 160 self.write(banner)
161 161
162 162 def compute_banner(self):
163 163 self.banner = self.banner1
164 164 if self.profile:
165 165 self.banner += '\nIPython profile: %s\n' % self.profile
166 166 if self.banner2:
167 167 self.banner += '\n' + self.banner2
168 168
169 169 def init_usage(self, usage=None):
170 170 if usage is None:
171 171 self.usage = interactive_usage
172 172 else:
173 173 self.usage = usage
174 174
175 175 #-------------------------------------------------------------------------
176 176 # Mainloop and code execution logic
177 177 #-------------------------------------------------------------------------
178 178
179 179 def mainloop(self, display_banner=None):
180 180 """Start the mainloop.
181 181
182 182 If an optional banner argument is given, it will override the
183 183 internally created default banner.
184 184 """
185 185
186 186 with nested(self.builtin_trap, self.display_trap):
187 187
188 188 while 1:
189 189 try:
190 190 self.interact(display_banner=display_banner)
191 191 #self.interact_with_readline()
192 192 # XXX for testing of a readline-decoupled repl loop, call
193 193 # interact_with_readline above
194 194 break
195 195 except KeyboardInterrupt:
196 196 # this should not be necessary, but KeyboardInterrupt
197 197 # handling seems rather unpredictable...
198 198 self.write("\nKeyboardInterrupt in interact()\n")
199 199
200 200 def interact(self, display_banner=None):
201 201 """Closely emulate the interactive Python console."""
202 202
203 203 # batch run -> do not interact
204 204 if self.exit_now:
205 205 return
206 206
207 207 if display_banner is None:
208 208 display_banner = self.display_banner
209 209 if display_banner:
210 210 self.show_banner()
211 211
212 212 more = False
213 213
214 214 # Mark activity in the builtins
215 215 __builtin__.__dict__['__IPYTHON__active'] += 1
216 216
217 217 if self.has_readline:
218 218 self.readline_startup_hook(self.pre_readline)
219 219 # exit_now is set by a call to %Exit or %Quit, through the
220 220 # ask_exit callback.
221 221
222 222 while not self.exit_now:
223 223 self.hooks.pre_prompt_hook()
224 224 if more:
225 225 try:
226 226 prompt = self.hooks.generate_prompt(True)
227 227 except:
228 228 self.showtraceback()
229 229 if self.autoindent:
230 230 self.rl_do_indent = True
231 231
232 232 else:
233 233 try:
234 234 prompt = self.hooks.generate_prompt(False)
235 235 except:
236 236 self.showtraceback()
237 237 try:
238 238 line = self.raw_input(prompt)
239 239 if self.exit_now:
240 240 # quick exit on sys.std[in|out] close
241 241 break
242 242 if self.autoindent:
243 243 self.rl_do_indent = False
244 244
245 245 except KeyboardInterrupt:
246 246 #double-guard against keyboardinterrupts during kbdint handling
247 247 try:
248 248 self.write('\nKeyboardInterrupt\n')
249 249 self.resetbuffer()
250 250 more = False
251 251 except KeyboardInterrupt:
252 252 pass
253 253 except EOFError:
254 254 if self.autoindent:
255 255 self.rl_do_indent = False
256 256 if self.has_readline:
257 257 self.readline_startup_hook(None)
258 258 self.write('\n')
259 259 self.exit()
260 260 except bdb.BdbQuit:
261 261 warn('The Python debugger has exited with a BdbQuit exception.\n'
262 262 'Because of how pdb handles the stack, it is impossible\n'
263 263 'for IPython to properly format this particular exception.\n'
264 264 'IPython will resume normal operation.')
265 265 except:
266 266 # exceptions here are VERY RARE, but they can be triggered
267 267 # asynchronously by signal handlers, for example.
268 268 self.showtraceback()
269 269 else:
270 270 self.input_splitter.push(line)
271 271 more = self.input_splitter.push_accepts_more()
272 272 if (self.SyntaxTB.last_syntax_error and
273 273 self.autoedit_syntax):
274 274 self.edit_syntax_error()
275 275 if not more:
276 276 source_raw = self.input_splitter.source_raw_reset()[1]
277 277 self.run_cell(source_raw)
278 278
279 279 # We are off again...
280 280 __builtin__.__dict__['__IPYTHON__active'] -= 1
281 281
282 282 # Turn off the exit flag, so the mainloop can be restarted if desired
283 283 self.exit_now = False
284 284
285 def raw_input(self, prompt='', continue_prompt=False):
286 """Write a prompt and read a line.
287
288 The returned line does not include the trailing newline.
289 When the user enters the EOF key sequence, EOFError is raised.
290
291 Optional inputs:
292
293 - prompt(''): a string to be printed to prompt the user.
294
295 - continue_prompt(False): whether this line is the first one or a
296 continuation in a sequence of inputs.
297 """
298 # Code run by the user may have modified the readline completer state.
299 # We must ensure that our completer is back in place.
300
301 if self.has_readline:
302 self.set_readline_completer()
303
304 try:
305 line = raw_input_original(prompt).decode(self.stdin_encoding)
306 except ValueError:
307 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
308 " or sys.stdout.close()!\nExiting IPython!")
309 self.ask_exit()
310 return ""
311
312 # Try to be reasonably smart about not re-indenting pasted input more
313 # than necessary. We do this by trimming out the auto-indent initial
314 # spaces, if the user's actual input started itself with whitespace.
315 if self.autoindent:
316 if num_ini_spaces(line) > self.indent_current_nsp:
317 line = line[self.indent_current_nsp:]
318 self.indent_current_nsp = 0
319
320 # store the unfiltered input before the user has any chance to modify
321 # it.
322 if line.strip():
323 if continue_prompt:
324 if self.has_readline and self.readline_use:
325 histlen = self.readline.get_current_history_length()
326 if histlen > 1:
327 newhist = self.history_manager.input_hist_raw[-1].rstrip()
328 self.readline.remove_history_item(histlen-1)
329 self.readline.replace_history_item(histlen-2,
330 newhist.encode(self.stdin_encoding))
331 else:
332 self.history_manager.input_hist_raw.append('%s\n' % line)
333 elif not continue_prompt:
334 self.history_manager.input_hist_raw.append('\n')
335 try:
336 lineout = self.prefilter_manager.prefilter_lines(line,continue_prompt)
337 except:
338 # blanket except, in case a user-defined prefilter crashes, so it
339 # can't take all of ipython with it.
340 self.showtraceback()
341 return ''
342 else:
343 return lineout
344
345
346 285 def raw_input(self, prompt=''):
347 286 """Write a prompt and read a line.
348 287
349 288 The returned line does not include the trailing newline.
350 289 When the user enters the EOF key sequence, EOFError is raised.
351 290
352 291 Optional inputs:
353 292
354 293 - prompt(''): a string to be printed to prompt the user.
355 294
356 295 - continue_prompt(False): whether this line is the first one or a
357 296 continuation in a sequence of inputs.
358 297 """
359 298 # Code run by the user may have modified the readline completer state.
360 299 # We must ensure that our completer is back in place.
361 300
362 301 if self.has_readline:
363 302 self.set_readline_completer()
364 303
365 304 try:
366 305 line = raw_input_original(prompt).decode(self.stdin_encoding)
367 306 except ValueError:
368 307 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
369 308 " or sys.stdout.close()!\nExiting IPython!")
370 309 self.ask_exit()
371 310 return ""
372 311
373 312 # Try to be reasonably smart about not re-indenting pasted input more
374 313 # than necessary. We do this by trimming out the auto-indent initial
375 314 # spaces, if the user's actual input started itself with whitespace.
376 315 if self.autoindent:
377 316 if num_ini_spaces(line) > self.indent_current_nsp:
378 317 line = line[self.indent_current_nsp:]
379 318 self.indent_current_nsp = 0
380 319
381 320 return line
382 321
383 322 #-------------------------------------------------------------------------
384 323 # Methods to support auto-editing of SyntaxErrors.
385 324 #-------------------------------------------------------------------------
386 325
387 326 def edit_syntax_error(self):
388 327 """The bottom half of the syntax error handler called in the main loop.
389 328
390 329 Loop until syntax error is fixed or user cancels.
391 330 """
392 331
393 332 while self.SyntaxTB.last_syntax_error:
394 333 # copy and clear last_syntax_error
395 334 err = self.SyntaxTB.clear_err_state()
396 335 if not self._should_recompile(err):
397 336 return
398 337 try:
399 338 # may set last_syntax_error again if a SyntaxError is raised
400 339 self.safe_execfile(err.filename,self.user_ns)
401 340 except:
402 341 self.showtraceback()
403 342 else:
404 343 try:
405 344 f = file(err.filename)
406 345 try:
407 346 # This should be inside a display_trap block and I
408 347 # think it is.
409 348 sys.displayhook(f.read())
410 349 finally:
411 350 f.close()
412 351 except:
413 352 self.showtraceback()
414 353
415 354 def _should_recompile(self,e):
416 355 """Utility routine for edit_syntax_error"""
417 356
418 357 if e.filename in ('<ipython console>','<input>','<string>',
419 358 '<console>','<BackgroundJob compilation>',
420 359 None):
421 360
422 361 return False
423 362 try:
424 363 if (self.autoedit_syntax and
425 364 not self.ask_yes_no('Return to editor to correct syntax error? '
426 365 '[Y/n] ','y')):
427 366 return False
428 367 except EOFError:
429 368 return False
430 369
431 370 def int0(x):
432 371 try:
433 372 return int(x)
434 373 except TypeError:
435 374 return 0
436 375 # always pass integer line and offset values to editor hook
437 376 try:
438 377 self.hooks.fix_error_editor(e.filename,
439 378 int0(e.lineno),int0(e.offset),e.msg)
440 379 except TryNext:
441 380 warn('Could not open editor')
442 381 return False
443 382 return True
444 383
445 384 #-------------------------------------------------------------------------
446 385 # Things related to GUI support and pylab
447 386 #-------------------------------------------------------------------------
448 387
449 388 def enable_pylab(self, gui=None):
450 389 """Activate pylab support at runtime.
451 390
452 391 This turns on support for matplotlib, preloads into the interactive
453 392 namespace all of numpy and pylab, and configures IPython to correcdtly
454 393 interact with the GUI event loop. The GUI backend to be used can be
455 394 optionally selected with the optional :param:`gui` argument.
456 395
457 396 Parameters
458 397 ----------
459 398 gui : optional, string
460 399
461 400 If given, dictates the choice of matplotlib GUI backend to use
462 401 (should be one of IPython's supported backends, 'tk', 'qt', 'wx' or
463 402 'gtk'), otherwise we use the default chosen by matplotlib (as
464 403 dictated by the matplotlib build-time options plus the user's
465 404 matplotlibrc configuration file).
466 405 """
467 406 # We want to prevent the loading of pylab to pollute the user's
468 407 # namespace as shown by the %who* magics, so we execute the activation
469 408 # code in an empty namespace, and we update *both* user_ns and
470 409 # user_ns_hidden with this information.
471 410 ns = {}
472 411 gui = pylab_activate(ns, gui)
473 412 self.user_ns.update(ns)
474 413 self.user_ns_hidden.update(ns)
475 414 # Now we must activate the gui pylab wants to use, and fix %run to take
476 415 # plot updates into account
477 416 enable_gui(gui)
478 417 self.magic_run = self._pylab_magic_run
479 418
480 419 #-------------------------------------------------------------------------
481 420 # Things related to exiting
482 421 #-------------------------------------------------------------------------
483 422
484 423 def ask_exit(self):
485 424 """ Ask the shell to exit. Can be overiden and used as a callback. """
486 425 self.exit_now = True
487 426
488 427 def exit(self):
489 428 """Handle interactive exit.
490 429
491 430 This method calls the ask_exit callback."""
492 431 if self.confirm_exit:
493 432 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
494 433 self.ask_exit()
495 434 else:
496 435 self.ask_exit()
497 436
498 437 #------------------------------------------------------------------------
499 438 # Magic overrides
500 439 #------------------------------------------------------------------------
501 440 # Once the base class stops inheriting from magic, this code needs to be
502 441 # moved into a separate machinery as well. For now, at least isolate here
503 442 # the magics which this class needs to implement differently from the base
504 443 # class, or that are unique to it.
505 444
506 445 def magic_autoindent(self, parameter_s = ''):
507 446 """Toggle autoindent on/off (if available)."""
508 447
509 448 self.shell.set_autoindent()
510 449 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
511 450
512 451 @testdec.skip_doctest
513 452 def magic_cpaste(self, parameter_s=''):
514 453 """Paste & execute a pre-formatted code block from clipboard.
515 454
516 455 You must terminate the block with '--' (two minus-signs) alone on the
517 456 line. You can also provide your own sentinel with '%paste -s %%' ('%%'
518 457 is the new sentinel for this operation)
519 458
520 459 The block is dedented prior to execution to enable execution of method
521 460 definitions. '>' and '+' characters at the beginning of a line are
522 461 ignored, to allow pasting directly from e-mails, diff files and
523 462 doctests (the '...' continuation prompt is also stripped). The
524 463 executed block is also assigned to variable named 'pasted_block' for
525 464 later editing with '%edit pasted_block'.
526 465
527 466 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
528 467 This assigns the pasted block to variable 'foo' as string, without
529 468 dedenting or executing it (preceding >>> and + is still stripped)
530 469
531 470 '%cpaste -r' re-executes the block previously entered by cpaste.
532 471
533 472 Do not be alarmed by garbled output on Windows (it's a readline bug).
534 473 Just press enter and type -- (and press enter again) and the block
535 474 will be what was just pasted.
536 475
537 476 IPython statements (magics, shell escapes) are not supported (yet).
538 477
539 478 See also
540 479 --------
541 480 paste: automatically pull code from clipboard.
542 481
543 482 Examples
544 483 --------
545 484 ::
546 485
547 486 In [8]: %cpaste
548 487 Pasting code; enter '--' alone on the line to stop.
549 488 :>>> a = ["world!", "Hello"]
550 489 :>>> print " ".join(sorted(a))
551 490 :--
552 491 Hello world!
553 492 """
554 493
555 494 opts,args = self.parse_options(parameter_s,'rs:',mode='string')
556 495 par = args.strip()
557 496 if opts.has_key('r'):
558 497 self._rerun_pasted()
559 498 return
560 499
561 500 sentinel = opts.get('s','--')
562 501
563 502 block = self._strip_pasted_lines_for_code(
564 503 self._get_pasted_lines(sentinel))
565 504
566 505 self._execute_block(block, par)
567 506
568 507 def magic_paste(self, parameter_s=''):
569 508 """Paste & execute a pre-formatted code block from clipboard.
570 509
571 510 The text is pulled directly from the clipboard without user
572 511 intervention and printed back on the screen before execution (unless
573 512 the -q flag is given to force quiet mode).
574 513
575 514 The block is dedented prior to execution to enable execution of method
576 515 definitions. '>' and '+' characters at the beginning of a line are
577 516 ignored, to allow pasting directly from e-mails, diff files and
578 517 doctests (the '...' continuation prompt is also stripped). The
579 518 executed block is also assigned to variable named 'pasted_block' for
580 519 later editing with '%edit pasted_block'.
581 520
582 521 You can also pass a variable name as an argument, e.g. '%paste foo'.
583 522 This assigns the pasted block to variable 'foo' as string, without
584 523 dedenting or executing it (preceding >>> and + is still stripped)
585 524
586 525 Options
587 526 -------
588 527
589 528 -r: re-executes the block previously entered by cpaste.
590 529
591 530 -q: quiet mode: do not echo the pasted text back to the terminal.
592 531
593 532 IPython statements (magics, shell escapes) are not supported (yet).
594 533
595 534 See also
596 535 --------
597 536 cpaste: manually paste code into terminal until you mark its end.
598 537 """
599 538 opts,args = self.parse_options(parameter_s,'rq',mode='string')
600 539 par = args.strip()
601 540 if opts.has_key('r'):
602 541 self._rerun_pasted()
603 542 return
604 543
605 544 text = self.shell.hooks.clipboard_get()
606 545 block = self._strip_pasted_lines_for_code(text.splitlines())
607 546
608 547 # By default, echo back to terminal unless quiet mode is requested
609 548 if not opts.has_key('q'):
610 549 write = self.shell.write
611 550 write(self.shell.pycolorize(block))
612 551 if not block.endswith('\n'):
613 552 write('\n')
614 553 write("## -- End pasted text --\n")
615 554
616 555 self._execute_block(block, par)
617 556
618 557
619 558 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now