##// END OF EJS Templates
allow unicode in Shell.raw_input
MinRK -
Show More
@@ -1,681 +1,684 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-2011 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 bdb
18 18 import os
19 19 import re
20 20 import sys
21 21 import textwrap
22 22
23 23 # We need to use nested to support python 2.6, once we move to >=2.7, we can
24 24 # use the with keyword's new builtin support for nested managers
25 25 try:
26 26 from contextlib import nested
27 27 except:
28 28 from IPython.utils.nested_context import nested
29 29
30 30 from IPython.core.error import TryNext, UsageError
31 31 from IPython.core.usage import interactive_usage, default_banner
32 32 from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
33 33 from IPython.core.magic import Magics, magics_class, line_magic
34 34 from IPython.testing.skipdoctest import skip_doctest
35 35 from IPython.utils.encoding import get_stream_enc
36 36 from IPython.utils import py3compat
37 37 from IPython.utils.terminal import toggle_set_term_title, set_term_title
38 38 from IPython.utils.process import abbrev_cwd
39 39 from IPython.utils.warn import warn, error
40 40 from IPython.utils.text import num_ini_spaces, SList
41 41 from IPython.utils.traitlets import Integer, CBool, Unicode
42 42
43 43 #-----------------------------------------------------------------------------
44 44 # Utilities
45 45 #-----------------------------------------------------------------------------
46 46
47 47 def get_default_editor():
48 48 try:
49 49 ed = os.environ['EDITOR']
50 50 except KeyError:
51 51 if os.name == 'posix':
52 52 ed = 'vi' # the only one guaranteed to be there!
53 53 else:
54 54 ed = 'notepad' # same in Windows!
55 55 return ed
56 56
57 57
58 58 def get_pasted_lines(sentinel, l_input=py3compat.input):
59 59 """ Yield pasted lines until the user enters the given sentinel value.
60 60 """
61 61 print "Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \
62 62 % sentinel
63 63 while True:
64 64 try:
65 65 l = l_input(':')
66 66 if l == sentinel:
67 67 return
68 68 else:
69 69 yield l
70 70 except EOFError:
71 71 print '<EOF>'
72 72 return
73 73
74 74
75 75 def strip_email_quotes(raw_lines):
76 76 """ Strip email quotation marks at the beginning of each line.
77 77
78 78 We don't do any more input transofrmations here because the main shell's
79 79 prefiltering handles other cases.
80 80 """
81 81 lines = [re.sub(r'^\s*(\s?>)+', '', l) for l in raw_lines]
82 82 return '\n'.join(lines) + '\n'
83 83
84 84
85 85 # These two functions are needed by the %paste/%cpaste magics. In practice
86 86 # they are basically methods (they take the shell as their first argument), but
87 87 # we leave them as standalone functions because eventually the magics
88 88 # themselves will become separate objects altogether. At that point, the
89 89 # magics will have access to the shell object, and these functions can be made
90 90 # methods of the magic object, but not of the shell.
91 91
92 92 def store_or_execute(shell, block, name):
93 93 """ Execute a block, or store it in a variable, per the user's request.
94 94 """
95 95 # Dedent and prefilter so what we store matches what is executed by
96 96 # run_cell.
97 97 b = shell.prefilter(textwrap.dedent(block))
98 98
99 99 if name:
100 100 # If storing it for further editing, run the prefilter on it
101 101 shell.user_ns[name] = SList(b.splitlines())
102 102 print "Block assigned to '%s'" % name
103 103 else:
104 104 shell.user_ns['pasted_block'] = b
105 105 shell.run_cell(b)
106 106
107 107
108 108 def rerun_pasted(shell, name='pasted_block'):
109 109 """ Rerun a previously pasted command.
110 110 """
111 111 b = shell.user_ns.get(name)
112 112
113 113 # Sanity checks
114 114 if b is None:
115 115 raise UsageError('No previous pasted block available')
116 116 if not isinstance(b, basestring):
117 117 raise UsageError(
118 118 "Variable 'pasted_block' is not a string, can't execute")
119 119
120 120 print "Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))
121 121 shell.run_cell(b)
122 122
123 123
124 124 #------------------------------------------------------------------------
125 125 # Terminal-specific magics
126 126 #------------------------------------------------------------------------
127 127
128 128 @magics_class
129 129 class TerminalMagics(Magics):
130 130
131 131 @line_magic
132 132 def autoindent(self, parameter_s = ''):
133 133 """Toggle autoindent on/off (if available)."""
134 134
135 135 self.shell.set_autoindent()
136 136 print "Automatic indentation is:",['OFF','ON'][self.shell.autoindent]
137 137
138 138 @skip_doctest
139 139 @line_magic
140 140 def cpaste(self, parameter_s=''):
141 141 """Paste & execute a pre-formatted code block from clipboard.
142 142
143 143 You must terminate the block with '--' (two minus-signs) or Ctrl-D
144 144 alone on the line. You can also provide your own sentinel with '%paste
145 145 -s %%' ('%%' is the new sentinel for this operation)
146 146
147 147 The block is dedented prior to execution to enable execution of method
148 148 definitions. '>' and '+' characters at the beginning of a line are
149 149 ignored, to allow pasting directly from e-mails, diff files and
150 150 doctests (the '...' continuation prompt is also stripped). The
151 151 executed block is also assigned to variable named 'pasted_block' for
152 152 later editing with '%edit pasted_block'.
153 153
154 154 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
155 155 This assigns the pasted block to variable 'foo' as string, without
156 156 dedenting or executing it (preceding >>> and + is still stripped)
157 157
158 158 '%cpaste -r' re-executes the block previously entered by cpaste.
159 159
160 160 Do not be alarmed by garbled output on Windows (it's a readline bug).
161 161 Just press enter and type -- (and press enter again) and the block
162 162 will be what was just pasted.
163 163
164 164 IPython statements (magics, shell escapes) are not supported (yet).
165 165
166 166 See also
167 167 --------
168 168 paste: automatically pull code from clipboard.
169 169
170 170 Examples
171 171 --------
172 172 ::
173 173
174 174 In [8]: %cpaste
175 175 Pasting code; enter '--' alone on the line to stop.
176 176 :>>> a = ["world!", "Hello"]
177 177 :>>> print " ".join(sorted(a))
178 178 :--
179 179 Hello world!
180 180 """
181 181
182 182 opts, name = self.parse_options(parameter_s, 'rs:', mode='string')
183 183 if 'r' in opts:
184 184 rerun_pasted(self.shell)
185 185 return
186 186
187 187 sentinel = opts.get('s', '--')
188 188 block = strip_email_quotes(get_pasted_lines(sentinel))
189 189 store_or_execute(self.shell, block, name)
190 190
191 191 @line_magic
192 192 def paste(self, parameter_s=''):
193 193 """Paste & execute a pre-formatted code block from clipboard.
194 194
195 195 The text is pulled directly from the clipboard without user
196 196 intervention and printed back on the screen before execution (unless
197 197 the -q flag is given to force quiet mode).
198 198
199 199 The block is dedented prior to execution to enable execution of method
200 200 definitions. '>' and '+' characters at the beginning of a line are
201 201 ignored, to allow pasting directly from e-mails, diff files and
202 202 doctests (the '...' continuation prompt is also stripped). The
203 203 executed block is also assigned to variable named 'pasted_block' for
204 204 later editing with '%edit pasted_block'.
205 205
206 206 You can also pass a variable name as an argument, e.g. '%paste foo'.
207 207 This assigns the pasted block to variable 'foo' as string, without
208 208 dedenting or executing it (preceding >>> and + is still stripped)
209 209
210 210 Options
211 211 -------
212 212
213 213 -r: re-executes the block previously entered by cpaste.
214 214
215 215 -q: quiet mode: do not echo the pasted text back to the terminal.
216 216
217 217 IPython statements (magics, shell escapes) are not supported (yet).
218 218
219 219 See also
220 220 --------
221 221 cpaste: manually paste code into terminal until you mark its end.
222 222 """
223 223 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
224 224 if 'r' in opts:
225 225 rerun_pasted(self.shell)
226 226 return
227 227 try:
228 228 text = self.shell.hooks.clipboard_get()
229 229 block = strip_email_quotes(text.splitlines())
230 230 except TryNext as clipboard_exc:
231 231 message = getattr(clipboard_exc, 'args')
232 232 if message:
233 233 error(message[0])
234 234 else:
235 235 error('Could not get text from the clipboard.')
236 236 return
237 237
238 238 # By default, echo back to terminal unless quiet mode is requested
239 239 if 'q' not in opts:
240 240 write = self.shell.write
241 241 write(self.shell.pycolorize(block))
242 242 if not block.endswith('\n'):
243 243 write('\n')
244 244 write("## -- End pasted text --\n")
245 245
246 246 store_or_execute(self.shell, block, name)
247 247
248 248 # Class-level: add a '%cls' magic only on Windows
249 249 if sys.platform == 'win32':
250 250 @line_magic
251 251 def cls(self, s):
252 252 """Clear screen.
253 253 """
254 254 os.system("cls")
255 255
256 256 #-----------------------------------------------------------------------------
257 257 # Main class
258 258 #-----------------------------------------------------------------------------
259 259
260 260 class TerminalInteractiveShell(InteractiveShell):
261 261
262 262 autoedit_syntax = CBool(False, config=True,
263 263 help="auto editing of files with syntax errors.")
264 264 banner = Unicode('')
265 265 banner1 = Unicode(default_banner, config=True,
266 266 help="""The part of the banner to be printed before the profile"""
267 267 )
268 268 banner2 = Unicode('', config=True,
269 269 help="""The part of the banner to be printed after the profile"""
270 270 )
271 271 confirm_exit = CBool(True, config=True,
272 272 help="""
273 273 Set to confirm when you try to exit IPython with an EOF (Control-D
274 274 in Unix, Control-Z/Enter in Windows). By typing 'exit' or 'quit',
275 275 you can force a direct exit without any confirmation.""",
276 276 )
277 277 # This display_banner only controls whether or not self.show_banner()
278 278 # is called when mainloop/interact are called. The default is False
279 279 # because for the terminal based application, the banner behavior
280 280 # is controlled by Global.display_banner, which IPythonApp looks at
281 281 # to determine if *it* should call show_banner() by hand or not.
282 282 display_banner = CBool(False) # This isn't configurable!
283 283 embedded = CBool(False)
284 284 embedded_active = CBool(False)
285 285 editor = Unicode(get_default_editor(), config=True,
286 286 help="Set the editor used by IPython (default to $EDITOR/vi/notepad)."
287 287 )
288 288 pager = Unicode('less', config=True,
289 289 help="The shell program to be used for paging.")
290 290
291 291 screen_length = Integer(0, config=True,
292 292 help=
293 293 """Number of lines of your screen, used to control printing of very
294 294 long strings. Strings longer than this number of lines will be sent
295 295 through a pager instead of directly printed. The default value for
296 296 this is 0, which means IPython will auto-detect your screen size every
297 297 time it needs to print certain potentially long strings (this doesn't
298 298 change the behavior of the 'print' keyword, it's only triggered
299 299 internally). If for some reason this isn't working well (it needs
300 300 curses support), specify it yourself. Otherwise don't change the
301 301 default.""",
302 302 )
303 303 term_title = CBool(False, config=True,
304 304 help="Enable auto setting the terminal title."
305 305 )
306 306
307 307 # In the terminal, GUI control is done via PyOS_InputHook
308 308 from IPython.lib.inputhook import enable_gui
309 309 enable_gui = staticmethod(enable_gui)
310 310
311 311 def __init__(self, config=None, ipython_dir=None, profile_dir=None,
312 312 user_ns=None, user_module=None, custom_exceptions=((),None),
313 313 usage=None, banner1=None, banner2=None, display_banner=None):
314 314
315 315 super(TerminalInteractiveShell, self).__init__(
316 316 config=config, profile_dir=profile_dir, user_ns=user_ns,
317 317 user_module=user_module, custom_exceptions=custom_exceptions
318 318 )
319 319 # use os.system instead of utils.process.system by default,
320 320 # because piped system doesn't make sense in the Terminal:
321 321 self.system = self.system_raw
322 322
323 323 self.init_term_title()
324 324 self.init_usage(usage)
325 325 self.init_banner(banner1, banner2, display_banner)
326 326
327 327 #-------------------------------------------------------------------------
328 328 # Things related to the terminal
329 329 #-------------------------------------------------------------------------
330 330
331 331 @property
332 332 def usable_screen_length(self):
333 333 if self.screen_length == 0:
334 334 return 0
335 335 else:
336 336 num_lines_bot = self.separate_in.count('\n')+1
337 337 return self.screen_length - num_lines_bot
338 338
339 339 def init_term_title(self):
340 340 # Enable or disable the terminal title.
341 341 if self.term_title:
342 342 toggle_set_term_title(True)
343 343 set_term_title('IPython: ' + abbrev_cwd())
344 344 else:
345 345 toggle_set_term_title(False)
346 346
347 347 #-------------------------------------------------------------------------
348 348 # Things related to aliases
349 349 #-------------------------------------------------------------------------
350 350
351 351 def init_alias(self):
352 352 # The parent class defines aliases that can be safely used with any
353 353 # frontend.
354 354 super(TerminalInteractiveShell, self).init_alias()
355 355
356 356 # Now define aliases that only make sense on the terminal, because they
357 357 # need direct access to the console in a way that we can't emulate in
358 358 # GUI or web frontend
359 359 if os.name == 'posix':
360 360 aliases = [('clear', 'clear'), ('more', 'more'), ('less', 'less'),
361 361 ('man', 'man')]
362 362 elif os.name == 'nt':
363 363 aliases = [('cls', 'cls')]
364 364
365 365
366 366 for name, cmd in aliases:
367 367 self.alias_manager.define_alias(name, cmd)
368 368
369 369 #-------------------------------------------------------------------------
370 370 # Things related to the banner and usage
371 371 #-------------------------------------------------------------------------
372 372
373 373 def _banner1_changed(self):
374 374 self.compute_banner()
375 375
376 376 def _banner2_changed(self):
377 377 self.compute_banner()
378 378
379 379 def _term_title_changed(self, name, new_value):
380 380 self.init_term_title()
381 381
382 382 def init_banner(self, banner1, banner2, display_banner):
383 383 if banner1 is not None:
384 384 self.banner1 = banner1
385 385 if banner2 is not None:
386 386 self.banner2 = banner2
387 387 if display_banner is not None:
388 388 self.display_banner = display_banner
389 389 self.compute_banner()
390 390
391 391 def show_banner(self, banner=None):
392 392 if banner is None:
393 393 banner = self.banner
394 394 self.write(banner)
395 395
396 396 def compute_banner(self):
397 397 self.banner = self.banner1
398 398 if self.profile and self.profile != 'default':
399 399 self.banner += '\nIPython profile: %s\n' % self.profile
400 400 if self.banner2:
401 401 self.banner += '\n' + self.banner2
402 402
403 403 def init_usage(self, usage=None):
404 404 if usage is None:
405 405 self.usage = interactive_usage
406 406 else:
407 407 self.usage = usage
408 408
409 409 #-------------------------------------------------------------------------
410 410 # Mainloop and code execution logic
411 411 #-------------------------------------------------------------------------
412 412
413 413 def mainloop(self, display_banner=None):
414 414 """Start the mainloop.
415 415
416 416 If an optional banner argument is given, it will override the
417 417 internally created default banner.
418 418 """
419 419
420 420 with nested(self.builtin_trap, self.display_trap):
421 421
422 422 while 1:
423 423 try:
424 424 self.interact(display_banner=display_banner)
425 425 #self.interact_with_readline()
426 426 # XXX for testing of a readline-decoupled repl loop, call
427 427 # interact_with_readline above
428 428 break
429 429 except KeyboardInterrupt:
430 430 # this should not be necessary, but KeyboardInterrupt
431 431 # handling seems rather unpredictable...
432 432 self.write("\nKeyboardInterrupt in interact()\n")
433 433
434 434 def _replace_rlhist_multiline(self, source_raw, hlen_before_cell):
435 435 """Store multiple lines as a single entry in history"""
436 436
437 437 # do nothing without readline or disabled multiline
438 438 if not self.has_readline or not self.multiline_history:
439 439 return hlen_before_cell
440 440
441 441 # windows rl has no remove_history_item
442 442 if not hasattr(self.readline, "remove_history_item"):
443 443 return hlen_before_cell
444 444
445 445 # skip empty cells
446 446 if not source_raw.rstrip():
447 447 return hlen_before_cell
448 448
449 449 # nothing changed do nothing, e.g. when rl removes consecutive dups
450 450 hlen = self.readline.get_current_history_length()
451 451 if hlen == hlen_before_cell:
452 452 return hlen_before_cell
453 453
454 454 for i in range(hlen - hlen_before_cell):
455 455 self.readline.remove_history_item(hlen - i - 1)
456 456 stdin_encoding = get_stream_enc(sys.stdin, 'utf-8')
457 457 self.readline.add_history(py3compat.unicode_to_str(source_raw.rstrip(),
458 458 stdin_encoding))
459 459 return self.readline.get_current_history_length()
460 460
461 461 def interact(self, display_banner=None):
462 462 """Closely emulate the interactive Python console."""
463 463
464 464 # batch run -> do not interact
465 465 if self.exit_now:
466 466 return
467 467
468 468 if display_banner is None:
469 469 display_banner = self.display_banner
470 470
471 471 if isinstance(display_banner, basestring):
472 472 self.show_banner(display_banner)
473 473 elif display_banner:
474 474 self.show_banner()
475 475
476 476 more = False
477 477
478 478 if self.has_readline:
479 479 self.readline_startup_hook(self.pre_readline)
480 480 hlen_b4_cell = self.readline.get_current_history_length()
481 481 else:
482 482 hlen_b4_cell = 0
483 483 # exit_now is set by a call to %Exit or %Quit, through the
484 484 # ask_exit callback.
485 485
486 486 while not self.exit_now:
487 487 self.hooks.pre_prompt_hook()
488 488 if more:
489 489 try:
490 490 prompt = self.prompt_manager.render('in2')
491 491 except:
492 492 self.showtraceback()
493 493 if self.autoindent:
494 494 self.rl_do_indent = True
495 495
496 496 else:
497 497 try:
498 498 prompt = self.separate_in + self.prompt_manager.render('in')
499 499 except:
500 500 self.showtraceback()
501 501 try:
502 502 line = self.raw_input(prompt)
503 503 if self.exit_now:
504 504 # quick exit on sys.std[in|out] close
505 505 break
506 506 if self.autoindent:
507 507 self.rl_do_indent = False
508 508
509 509 except KeyboardInterrupt:
510 510 #double-guard against keyboardinterrupts during kbdint handling
511 511 try:
512 512 self.write('\nKeyboardInterrupt\n')
513 513 source_raw = self.input_splitter.source_raw_reset()[1]
514 514 hlen_b4_cell = \
515 515 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
516 516 more = False
517 517 except KeyboardInterrupt:
518 518 pass
519 519 except EOFError:
520 520 if self.autoindent:
521 521 self.rl_do_indent = False
522 522 if self.has_readline:
523 523 self.readline_startup_hook(None)
524 524 self.write('\n')
525 525 self.exit()
526 526 except bdb.BdbQuit:
527 527 warn('The Python debugger has exited with a BdbQuit exception.\n'
528 528 'Because of how pdb handles the stack, it is impossible\n'
529 529 'for IPython to properly format this particular exception.\n'
530 530 'IPython will resume normal operation.')
531 531 except:
532 532 # exceptions here are VERY RARE, but they can be triggered
533 533 # asynchronously by signal handlers, for example.
534 534 self.showtraceback()
535 535 else:
536 536 self.input_splitter.push(line)
537 537 more = self.input_splitter.push_accepts_more()
538 538 if (self.SyntaxTB.last_syntax_error and
539 539 self.autoedit_syntax):
540 540 self.edit_syntax_error()
541 541 if not more:
542 542 source_raw = self.input_splitter.source_raw_reset()[1]
543 543 self.run_cell(source_raw, store_history=True)
544 544 hlen_b4_cell = \
545 545 self._replace_rlhist_multiline(source_raw, hlen_b4_cell)
546 546
547 547 # Turn off the exit flag, so the mainloop can be restarted if desired
548 548 self.exit_now = False
549 549
550 550 def raw_input(self, prompt=''):
551 551 """Write a prompt and read a line.
552 552
553 553 The returned line does not include the trailing newline.
554 554 When the user enters the EOF key sequence, EOFError is raised.
555 555
556 556 Optional inputs:
557 557
558 558 - prompt(''): a string to be printed to prompt the user.
559 559
560 560 - continue_prompt(False): whether this line is the first one or a
561 561 continuation in a sequence of inputs.
562 562 """
563 563 # Code run by the user may have modified the readline completer state.
564 564 # We must ensure that our completer is back in place.
565 565
566 566 if self.has_readline:
567 567 self.set_readline_completer()
568
569 # raw_input expects str, but we pass it unicode sometimes
570 prompt = py3compat.cast_bytes_py2(prompt)
568 571
569 572 try:
570 573 line = py3compat.str_to_unicode(self.raw_input_original(prompt))
571 574 except ValueError:
572 575 warn("\n********\nYou or a %run:ed script called sys.stdin.close()"
573 " or sys.stdout.close()!\nExiting IPython!")
576 " or sys.stdout.close()!\nExiting IPython!\n")
574 577 self.ask_exit()
575 578 return ""
576 579
577 580 # Try to be reasonably smart about not re-indenting pasted input more
578 581 # than necessary. We do this by trimming out the auto-indent initial
579 582 # spaces, if the user's actual input started itself with whitespace.
580 583 if self.autoindent:
581 584 if num_ini_spaces(line) > self.indent_current_nsp:
582 585 line = line[self.indent_current_nsp:]
583 586 self.indent_current_nsp = 0
584 587
585 588 return line
586 589
587 590 #-------------------------------------------------------------------------
588 591 # Methods to support auto-editing of SyntaxErrors.
589 592 #-------------------------------------------------------------------------
590 593
591 594 def edit_syntax_error(self):
592 595 """The bottom half of the syntax error handler called in the main loop.
593 596
594 597 Loop until syntax error is fixed or user cancels.
595 598 """
596 599
597 600 while self.SyntaxTB.last_syntax_error:
598 601 # copy and clear last_syntax_error
599 602 err = self.SyntaxTB.clear_err_state()
600 603 if not self._should_recompile(err):
601 604 return
602 605 try:
603 606 # may set last_syntax_error again if a SyntaxError is raised
604 607 self.safe_execfile(err.filename,self.user_ns)
605 608 except:
606 609 self.showtraceback()
607 610 else:
608 611 try:
609 612 f = open(err.filename)
610 613 try:
611 614 # This should be inside a display_trap block and I
612 615 # think it is.
613 616 sys.displayhook(f.read())
614 617 finally:
615 618 f.close()
616 619 except:
617 620 self.showtraceback()
618 621
619 622 def _should_recompile(self,e):
620 623 """Utility routine for edit_syntax_error"""
621 624
622 625 if e.filename in ('<ipython console>','<input>','<string>',
623 626 '<console>','<BackgroundJob compilation>',
624 627 None):
625 628
626 629 return False
627 630 try:
628 631 if (self.autoedit_syntax and
629 632 not self.ask_yes_no('Return to editor to correct syntax error? '
630 633 '[Y/n] ','y')):
631 634 return False
632 635 except EOFError:
633 636 return False
634 637
635 638 def int0(x):
636 639 try:
637 640 return int(x)
638 641 except TypeError:
639 642 return 0
640 643 # always pass integer line and offset values to editor hook
641 644 try:
642 645 self.hooks.fix_error_editor(e.filename,
643 646 int0(e.lineno),int0(e.offset),e.msg)
644 647 except TryNext:
645 648 warn('Could not open editor')
646 649 return False
647 650 return True
648 651
649 652 #-------------------------------------------------------------------------
650 653 # Things related to exiting
651 654 #-------------------------------------------------------------------------
652 655
653 656 def ask_exit(self):
654 657 """ Ask the shell to exit. Can be overiden and used as a callback. """
655 658 self.exit_now = True
656 659
657 660 def exit(self):
658 661 """Handle interactive exit.
659 662
660 663 This method calls the ask_exit callback."""
661 664 if self.confirm_exit:
662 665 if self.ask_yes_no('Do you really want to exit ([y]/n)?','y'):
663 666 self.ask_exit()
664 667 else:
665 668 self.ask_exit()
666 669
667 670 #-------------------------------------------------------------------------
668 671 # Things related to magics
669 672 #-------------------------------------------------------------------------
670 673
671 674 def init_magics(self):
672 675 super(TerminalInteractiveShell, self).init_magics()
673 676 self.register_magics(TerminalMagics)
674 677
675 678 def showindentationerror(self):
676 679 super(TerminalInteractiveShell, self).showindentationerror()
677 680 print("If you want to paste code into IPython, try the "
678 681 "%paste and %cpaste magic functions.")
679 682
680 683
681 684 InteractiveShellABC.register(TerminalInteractiveShell)
General Comments 0
You need to be logged in to leave comments. Login now